Skip to content

Instantly share code, notes, and snippets.

@krrrr38
Last active July 18, 2016 12:27
Show Gist options
  • Save krrrr38/3ef6eb6a6d5803bfbb7b8caf15282584 to your computer and use it in GitHub Desktop.
Save krrrr38/3ef6eb6a6d5803bfbb7b8caf15282584 to your computer and use it in GitHub Desktop.
@Configuration
public class Config extends WebMvcConfigurerAdapter {
@Bean
public LocalValidatorFactoryBean validator() {
LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
TermTranslateMessageInterpolator reTransableMessageInterpolator
= new TermTranslateMessageInterpolator(messageSource());
localValidatorFactoryBean.setMessageInterpolator(reTransableMessageInterpolator);
return localValidatorFactoryBean;
}
@Slf4j
private static class TermTranslateMessageInterpolator extends ResourceBundleMessageInterpolator {
private static final Pattern TERM_TRANSLATE_PATTERN = Pattern.compile("\\{([^\\}]*?)\\}");
private final MessageSource messageSource;
private final Map<TermMessageCacheKey, String> termInterpolateCache = new ConcurrentHashMap<>();
TermTranslateMessageInterpolatorr(MessageSource messageSource) {
super(new MessageSourceResourceBundleLocator(messageSource));
this.messageSource = messageSource;
}
@Override
public String interpolate(Context context, Locale locale, String term) {
String result = super.interpolate(context, locale, term);
String interpolated = termInterpolateCache.get(new TermMessageCacheKey(result, locale));
if (interpolated != null) {
return interpolated;
}
interpolated = result;
Matcher matcher = TERM_TRANSLATE_PATTERN.matcher(interpolated);
while(matcher.find()) {
String key = matcher.group(1);
String i18n = messageSource.getMessage(key, null, locale);
interpolated = StringUtils.replaceOnce(interpolated, "{" + key + "}", i18n);
}
termInterpolateCache.put(new TermMessageCacheKey(result, locale), interpolated);
return interpolated;
}
@Value
static class TermMessageCacheKey {
private String result;
private Locale locale;
}
}
@Bean
public MessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
@Override
public Validator getValidator() {
return validator();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment