001 package org.springframework.binding.validation.support; 002 003 import java.util.Locale; 004 005 import org.apache.commons.lang.StringUtils; 006 import org.apache.commons.logging.Log; 007 import org.apache.commons.logging.LogFactory; 008 import org.hibernate.validator.MessageInterpolator; 009 import org.hibernate.validator.Validator; 010 import org.springframework.context.support.MessageSourceAccessor; 011 import org.springframework.richclient.application.ApplicationServicesLocator; 012 013 /** 014 * Custom interpolator which requires a "messageSource" bean, which is a 015 * MessageSource implementation. This way the validation messages from Hibernate 016 * can be overwritten through the i18n facilities of Spring RCP. 017 * 018 * The different keys of the validators can be found in the Hibernate Reference, 019 * or you can look in the DefaultValidationMessage.properties file inside the 020 * hibernate-validator jar. 021 * 022 * @author Lieven Doclo 023 * 024 */ 025 public class HibernateRulesMessageInterpolator implements MessageInterpolator { 026 027 private MessageSourceAccessor messageSourceAccessor; 028 029 private static Log log = LogFactory.getLog(HibernateRulesMessageInterpolator.class); 030 031 private String annotationMessage; 032 033 private String interpolateMessage; 034 035 /** 036 * Initialize the MessageSourceAccessor by finding it inside the application 037 * Spring context. 038 */ 039 private void initializeMessageSourceAccessor() { 040 this.messageSourceAccessor = (MessageSourceAccessor) ApplicationServicesLocator.services().getService( 041 MessageSourceAccessor.class); 042 } 043 044 /** 045 * Retrieve the message for the validator. 046 */ 047 public String interpolate(String message, Validator validator, MessageInterpolator defaultInterpolator) { 048 if (annotationMessage != null && annotationMessage.equals(message)) { 049 // short cut 050 return interpolateMessage; 051 } 052 else { 053 message = message.replaceAll("[\\{\\}]", ""); 054 String string = null; 055 string = messageSourceAccessor != null ? messageSourceAccessor.getMessage(message, new Object[0], Locale 056 .getDefault()) : null; 057 if (StringUtils.isEmpty(string)) { 058 log.info("Message not found in messageSourceAccessor (it may not exist), " 059 + "trying Hibernate default messages"); 060 return defaultInterpolator.interpolate(message, validator, defaultInterpolator); 061 } 062 return string; 063 } 064 } 065 066 /** 067 * Create a new instance of the interpolator. 068 */ 069 public HibernateRulesMessageInterpolator() { 070 initializeMessageSourceAccessor(); 071 } 072 }