Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use MessageSource to interpolate bean validation messages #17530

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Provide a way to to interpolate message for JSR-303 validation
  • Loading branch information
nosan committed Nov 25, 2019
commit 0cbb3465386484f3ca27c3d7842f000acfa5e335
Expand Up @@ -25,6 +25,7 @@
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnResource;
import org.springframework.boot.validation.MessageInterpolatorFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
Expand All @@ -51,9 +52,10 @@ public class ValidationAutoConfiguration {
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@ConditionalOnMissingBean(Validator.class)
public static LocalValidatorFactoryBean defaultValidator() {
public static LocalValidatorFactoryBean defaultValidator(ApplicationContext applicationContext) {
LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
MessageInterpolatorFactory interpolatorFactory = new MessageInterpolatorFactory();
interpolatorFactory.setMessageSource(applicationContext);
factoryBean.setMessageInterpolator(interpolatorFactory.getObject());
return factoryBean;
}
Expand Down
Expand Up @@ -114,7 +114,7 @@ private static Validator getExistingOrCreate(ApplicationContext applicationConte
if (existing != null) {
return wrap(existing, true);
}
return create();
return create(applicationContext);
}

private static Validator getExisting(ApplicationContext applicationContext) {
Expand All @@ -130,10 +130,11 @@ private static Validator getExisting(ApplicationContext applicationContext) {
}
}

private static Validator create() {
private static Validator create(ApplicationContext applicationContext) {
OptionalValidatorFactoryBean validator = new OptionalValidatorFactoryBean();
try {
MessageInterpolatorFactory factory = new MessageInterpolatorFactory();
factory.setMessageSource(applicationContext);
validator.setMessageInterpolator(factory.getObject());
}
catch (ValidationException ex) {
Expand Down
Expand Up @@ -65,7 +65,9 @@ private static class Delegate extends LocalValidatorFactoryBean {

Delegate(ApplicationContext applicationContext) {
setApplicationContext(applicationContext);
setMessageInterpolator(new MessageInterpolatorFactory().getObject());
MessageInterpolatorFactory factory = new MessageInterpolatorFactory();
factory.setMessageSource(applicationContext);
setMessageInterpolator(factory.getObject());
afterPropertiesSet();
}

Expand Down
Expand Up @@ -27,6 +27,8 @@
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.util.ClassUtils;

/**
Expand All @@ -37,7 +39,7 @@
* @author Phillip Webb
* @since 1.5.0
*/
public class MessageInterpolatorFactory implements ObjectFactory<MessageInterpolator> {
public class MessageInterpolatorFactory implements ObjectFactory<MessageInterpolator>, MessageSourceAware {

private static final Set<String> FALLBACKS;

Expand All @@ -47,8 +49,30 @@ public class MessageInterpolatorFactory implements ObjectFactory<MessageInterpol
FALLBACKS = Collections.unmodifiableSet(fallbacks);
}

private MessageSource messageSource;

/**
* Sets the {@link MessageSource} used to create
* {@link MessageSourceInterpolatorDelegate}.
* @param messageSource the message source that resolves any message parameters before
* final interpolation
*/
@Override
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}

@Override
public MessageInterpolator getObject() throws BeansException {
MessageInterpolator messageInterpolator = getMessageInterpolator();
MessageSource messageSource = this.messageSource;
if (messageSource != null) {
return new MessageSourceInterpolatorDelegate(messageSource, messageInterpolator);
}
return messageInterpolator;
}

private MessageInterpolator getMessageInterpolator() {
try {
return Validation.byDefaultProvider().configure().getDefaultMessageInterpolator();
}
Expand Down
@@ -0,0 +1,105 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.boot.validation;

import java.util.LinkedHashSet;
import java.util.Set;
import java.util.function.Function;

/**
* Utility class to extract message parameters ({@code {param}}) from the message. These
* parameters can be substituted for supplied values.
*
* @author Dmytro Nosan
*/
final class MessageParameterPlaceholderHelper {

private static final char PREFIX = '{';

private static final char SUFFIX = '}';

private static final char ESCAPE = '\\';

/**
* Replaces all message parameters using the given {@code parameterResolver}.
* <p>
* If returned value has other message parameters, they will be replaced recursively
* until no replacement is performed;
* <p>
* Resolver can return {@code null} to signal that no further actions need to be done
* and replacement should be omitted;
* <p>
* The message parameter can be escaped by the {@code '\'} symbol;
* @param message the value containing the parameters to be replaced
* @param parameterResolver the {@code parameterResolver} to use for replacement
* @return the replaced message
*/
String replaceParameters(String message, Function<String, String> parameterResolver) {
return replaceParameters(message, parameterResolver, new LinkedHashSet<>(4));
}

private static String replaceParameters(String message, Function<String, String> parameterResolver,
Set<String> visitedParameters) {
StringBuilder buf = new StringBuilder(message);
int parentheses = 0;
int startIndex = -1;
int endIndex = -1;
for (int i = 0; i < buf.length(); i++) {
if (buf.charAt(i) == ESCAPE) {
i++;
}
else if (buf.charAt(i) == PREFIX) {
if (startIndex == -1) {
startIndex = i;
}
parentheses++;
}
else if (buf.charAt(i) == SUFFIX) {
if (parentheses > 0) {
parentheses--;
}
endIndex = i;
}
if (parentheses == 0 && startIndex < endIndex) {
String parameter = buf.substring(startIndex + 1, endIndex);
if (!visitedParameters.add(parameter)) {
throw new IllegalArgumentException("Circular reference '{" + parameter + "}'");
}
String value = replaceParameter(parameter, parameterResolver, visitedParameters);
if (value != null) {
buf.replace(startIndex, endIndex + 1, value);
i = startIndex + value.length() - 1;
}
visitedParameters.remove(parameter);
startIndex = -1;
endIndex = -1;
}
}
return buf.toString();
}

private static String replaceParameter(String parameter, Function<String, String> parameterResolver,
Set<String> visitedParameters) {
parameter = replaceParameters(parameter, parameterResolver, visitedParameters);
String value = parameterResolver.apply(parameter);
if (value != null) {
return replaceParameters(value, parameterResolver, visitedParameters);
}
return null;
}

}
@@ -0,0 +1,57 @@
/*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.boot.validation;

import java.util.Locale;

import javax.validation.MessageInterpolator;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

/**
* Resolves any message parameters via {@link MessageSource} and then interpolates a
* message using the underlying {@link MessageInterpolator}.
*
* @author Dmytro Nosan
*/
class MessageSourceInterpolatorDelegate implements MessageInterpolator {

private static final MessageParameterPlaceholderHelper helper = new MessageParameterPlaceholderHelper();

private final MessageSource messageSource;

private final MessageInterpolator messageInterpolator;

MessageSourceInterpolatorDelegate(MessageSource messageSource, MessageInterpolator messageInterpolator) {
this.messageSource = messageSource;
this.messageInterpolator = messageInterpolator;
}

@Override
public String interpolate(String messageTemplate, Context context) {
return interpolate(messageTemplate, context, LocaleContextHolder.getLocale());
}

@Override
public String interpolate(String messageTemplate, Context context, Locale locale) {
String message = helper.replaceParameters(messageTemplate,
(parameter) -> this.messageSource.getMessage(parameter, null, null, locale));
return this.messageInterpolator.interpolate(message, context, locale);
}

}
Expand Up @@ -21,7 +21,11 @@
import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
import org.junit.jupiter.api.Test;

import org.springframework.context.MessageSource;
import org.springframework.test.util.ReflectionTestUtils;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;

/**
* Tests for {@link MessageInterpolatorFactory}.
Expand All @@ -36,4 +40,16 @@ void getObjectShouldReturnResourceBundleMessageInterpolator() {
assertThat(interpolator).isInstanceOf(ResourceBundleMessageInterpolator.class);
}

@Test
void getObjectShouldReturnMessageSourceMessageInterpolatorDelegateWithResourceBundleMessageInterpolator() {
MessageInterpolatorFactory interpolatorFactory = new MessageInterpolatorFactory();
MessageSource messageSource = mock(MessageSource.class);
interpolatorFactory.setMessageSource(messageSource);
MessageInterpolator interpolator = interpolatorFactory.getObject();
assertThat(interpolator).isInstanceOf(MessageSourceInterpolatorDelegate.class);
assertThat(interpolator).hasFieldOrPropertyWithValue("messageSource", messageSource);
assertThat(ReflectionTestUtils.getField(interpolator, "messageInterpolator"))
.isInstanceOf(ResourceBundleMessageInterpolator.class);
}

}
Expand Up @@ -24,9 +24,12 @@
import org.junit.jupiter.api.Test;

import org.springframework.boot.testsupport.classpath.ClassPathExclusions;
import org.springframework.context.MessageSource;
import org.springframework.test.util.ReflectionTestUtils;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.mockito.Mockito.mock;

/**
* Integration tests for {@link MessageInterpolatorFactory} without EL.
Expand All @@ -50,4 +53,16 @@ void getObjectShouldUseFallback() {
assertThat(interpolator).isInstanceOf(ParameterMessageInterpolator.class);
}

@Test
void getObjectShouldUseMessageSourceMessageInterpolatorDelegateWithFallback() {
MessageInterpolatorFactory interpolatorFactory = new MessageInterpolatorFactory();
MessageSource messageSource = mock(MessageSource.class);
interpolatorFactory.setMessageSource(messageSource);
MessageInterpolator interpolator = interpolatorFactory.getObject();
assertThat(interpolator).isInstanceOf(MessageSourceInterpolatorDelegate.class);
assertThat(interpolator).hasFieldOrPropertyWithValue("messageSource", messageSource);
assertThat(ReflectionTestUtils.getField(interpolator, "messageInterpolator"))
.isInstanceOf(ParameterMessageInterpolator.class);
}

}