diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.java index 9c01dfc2525..6f6c2383995 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidationAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2020 the original author or authors. + * Copyright 2012-2021 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. @@ -28,6 +28,7 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnResource; import org.springframework.boot.validation.MessageInterpolatorFactory; import org.springframework.boot.validation.beanvalidation.FilteredMethodValidationPostProcessor; import org.springframework.boot.validation.beanvalidation.MethodValidationExcludeFilter; +import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @@ -54,9 +55,9 @@ 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(); + MessageInterpolatorFactory interpolatorFactory = new MessageInterpolatorFactory(applicationContext); factoryBean.setMessageInterpolator(interpolatorFactory.getObject()); return factoryBean; } diff --git a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapter.java b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapter.java index b7fdd206c27..dae7346039e 100644 --- a/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapter.java +++ b/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/validation/ValidatorAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2021 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. @@ -25,6 +25,7 @@ import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.boot.validation.MessageInterpolatorFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; +import org.springframework.context.MessageSource; import org.springframework.validation.Errors; import org.springframework.validation.SmartValidator; import org.springframework.validation.Validator; @@ -114,7 +115,7 @@ public class ValidatorAdapter implements SmartValidator, ApplicationContextAware if (existing != null) { return wrap(existing, true); } - return create(); + return create(applicationContext); } private static Validator getExisting(ApplicationContext applicationContext) { @@ -130,10 +131,10 @@ public class ValidatorAdapter implements SmartValidator, ApplicationContextAware } } - private static Validator create() { + private static Validator create(MessageSource messageSource) { OptionalValidatorFactoryBean validator = new OptionalValidatorFactoryBean(); try { - MessageInterpolatorFactory factory = new MessageInterpolatorFactory(); + MessageInterpolatorFactory factory = new MessageInterpolatorFactory(messageSource); validator.setMessageInterpolator(factory.getObject()); } catch (ValidationException ex) { diff --git a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/validation.adoc b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/validation.adoc index 06cd5f77832..cf7b4d79c43 100644 --- a/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/validation.adoc +++ b/spring-boot-project/spring-boot-docs/src/docs/asciidoc/io/validation.adoc @@ -10,3 +10,7 @@ For instance, the following service triggers the validation of the first argumen ---- include::{docs-java}/features/validation/MyBean.java[] ---- + +The application's `MessageSource` is used when resolving +`{parameters}`+ in constraint messages. +This allows you to use <> for Bean Validation messages. +Once the parameters have been resolved, message interpolation is completed using Bean Validation's default interpolator. diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesJsr303Validator.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesJsr303Validator.java index cc4151e7751..f926b989339 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesJsr303Validator.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/context/properties/ConfigurationPropertiesJsr303Validator.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2021 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. @@ -65,7 +65,7 @@ final class ConfigurationPropertiesJsr303Validator implements Validator { Delegate(ApplicationContext applicationContext) { setApplicationContext(applicationContext); - setMessageInterpolator(new MessageInterpolatorFactory().getObject()); + setMessageInterpolator(new MessageInterpolatorFactory(applicationContext).getObject()); afterPropertiesSet(); } diff --git a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/validation/MessageInterpolatorFactory.java b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/validation/MessageInterpolatorFactory.java index 06a2f13c701..77722058864 100644 --- a/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/validation/MessageInterpolatorFactory.java +++ b/spring-boot-project/spring-boot/src/main/java/org/springframework/boot/validation/MessageInterpolatorFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2021 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. @@ -27,6 +27,7 @@ import javax.validation.ValidationException; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeansException; import org.springframework.beans.factory.ObjectFactory; +import org.springframework.context.MessageSource; import org.springframework.util.ClassUtils; /** @@ -47,8 +48,33 @@ public class MessageInterpolatorFactory implements ObjectFactory + * The message parameter prefix { and suffix } can + * be escaped using {@code \}, e.g. \{escaped\}. + * @param message the message containing the parameters to be replaced + * @param locale the locale to use when resolving replacements + * @return the message with parameters replaced + */ + private String replaceParameters(String message, Locale locale) { + return replaceParameters(message, locale, new LinkedHashSet<>(4)); + } + + private String replaceParameters(String message, Locale locale, Set 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 '{" + String.join(" -> ", visitedParameters) + + " -> " + parameter + "}'"); + } + String value = replaceParameter(parameter, locale, 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 String replaceParameter(String parameter, Locale locale, Set visitedParameters) { + parameter = replaceParameters(parameter, locale, visitedParameters); + String value = this.messageSource.getMessage(parameter, null, null, locale); + return (value != null) ? replaceParameters(value, locale, visitedParameters) : null; + } + +} diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryTests.java index 9ca7cf0b62f..e45c92679ce 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2021 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. @@ -21,7 +21,11 @@ import javax.validation.MessageInterpolator; 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}. @@ -36,4 +40,15 @@ class MessageInterpolatorFactoryTests { assertThat(interpolator).isInstanceOf(ResourceBundleMessageInterpolator.class); } + @Test + void getObjectShouldReturnMessageSourceMessageInterpolatorDelegateWithResourceBundleMessageInterpolator() { + MessageSource messageSource = mock(MessageSource.class); + MessageInterpolatorFactory interpolatorFactory = new MessageInterpolatorFactory(messageSource); + MessageInterpolator interpolator = interpolatorFactory.getObject(); + assertThat(interpolator).isInstanceOf(MessageSourceMessageInterpolator.class); + assertThat(interpolator).hasFieldOrPropertyWithValue("messageSource", messageSource); + assertThat(ReflectionTestUtils.getField(interpolator, "messageInterpolator")) + .isInstanceOf(ResourceBundleMessageInterpolator.class); + } + } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java index 6aceb755fb8..817c3586fcc 100644 --- a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageInterpolatorFactoryWithoutElIntegrationTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2019 the original author or authors. + * Copyright 2012-2021 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. @@ -24,9 +24,12 @@ import org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator 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. @@ -50,4 +53,15 @@ class MessageInterpolatorFactoryWithoutElIntegrationTests { assertThat(interpolator).isInstanceOf(ParameterMessageInterpolator.class); } + @Test + void getObjectShouldUseMessageSourceMessageInterpolatorDelegateWithFallback() { + MessageSource messageSource = mock(MessageSource.class); + MessageInterpolatorFactory interpolatorFactory = new MessageInterpolatorFactory(messageSource); + MessageInterpolator interpolator = interpolatorFactory.getObject(); + assertThat(interpolator).isInstanceOf(MessageSourceMessageInterpolator.class); + assertThat(interpolator).hasFieldOrPropertyWithValue("messageSource", messageSource); + assertThat(ReflectionTestUtils.getField(interpolator, "messageInterpolator")) + .isInstanceOf(ParameterMessageInterpolator.class); + } + } diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorIntegrationTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorIntegrationTests.java new file mode 100644 index 00000000000..34b0b4d4b2b --- /dev/null +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorIntegrationTests.java @@ -0,0 +1,143 @@ +/* + * Copyright 2012-2021 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.ArrayList; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +import javax.validation.ConstraintViolation; +import javax.validation.Validator; +import javax.validation.constraints.NotNull; + +import org.junit.jupiter.api.Test; + +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.context.support.StaticMessageSource; +import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Integration tests for {@link MessageSourceMessageInterpolator}. + * + * @author Dmytro Nosan + */ +class MessageSourceMessageInterpolatorIntegrationTests { + + private final Validator validator = buildValidator(); + + @NotNull + private String defaultMessage; + + @NotNull(message = "{null}") + private String nullable; + + @NotNull(message = "{blank}") + private String blank; + + @NotNull(message = "{unknown}") + private String unknown; + + @NotNull(message = "{recursion}") + private String recursion; + + @NotNull(message = "\\{null}") + private String escapePrefix; + + @NotNull(message = "{null\\}") + private String escapeSuffix; + + @NotNull(message = "\\{null\\}") + private String escapePrefixSuffix; + + @NotNull(message = "\\\\{null}") + private String escapeEscape; + + @Test + void defaultMessage() { + assertThat(validate("defaultMessage")).containsExactly("must not be null"); + } + + @Test + void nullable() { + assertThat(validate("nullable")).containsExactly("must not be null"); + } + + @Test + void blank() { + assertThat(validate("blank")).containsExactly("must not be null or must not be blank"); + } + + @Test + void recursion() { + assertThatThrownBy(() -> validate("recursion")) + .hasStackTraceContaining("Circular reference '{recursion -> middle -> recursion}'"); + } + + @Test + void unknown() { + assertThat(validate("unknown")).containsExactly("{unknown}"); + } + + @Test + void escapePrefix() { + assertThat(validate("escapePrefix")).containsExactly("\\{null}"); + } + + @Test + void escapeSuffix() { + assertThat(validate("escapeSuffix")).containsExactly("{null\\}"); + } + + @Test + void escapePrefixSuffix() { + assertThat(validate("escapePrefixSuffix")).containsExactly("{null}"); + } + + @Test + void escapeEscape() { + assertThat(validate("escapeEscape")).containsExactly("\\must not be null"); + } + + private List validate(String property) { + List messages = new ArrayList<>(); + Set> constraints = this.validator.validateProperty(this, property); + for (ConstraintViolation constraint : constraints) { + messages.add(constraint.getMessage()); + } + return messages; + } + + private static Validator buildValidator() { + Locale locale = LocaleContextHolder.getLocale(); + StaticMessageSource messageSource = new StaticMessageSource(); + messageSource.addMessage("blank", locale, "{null} or {javax.validation.constraints.NotBlank.message}"); + messageSource.addMessage("null", locale, "{javax.validation.constraints.NotNull.message}"); + messageSource.addMessage("recursion", locale, "{middle}"); + messageSource.addMessage("middle", locale, "{recursion}"); + MessageInterpolatorFactory messageInterpolatorFactory = new MessageInterpolatorFactory(messageSource); + try (LocalValidatorFactoryBean validatorFactory = new LocalValidatorFactoryBean()) { + validatorFactory.setMessageInterpolator(messageInterpolatorFactory.getObject()); + validatorFactory.afterPropertiesSet(); + return validatorFactory.getValidator(); + } + } + +} diff --git a/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorTests.java b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorTests.java new file mode 100644 index 00000000000..c33d4997eeb --- /dev/null +++ b/spring-boot-project/spring-boot/src/test/java/org/springframework/boot/validation/MessageSourceMessageInterpolatorTests.java @@ -0,0 +1,119 @@ +/* + * Copyright 2012-2021 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 javax.validation.MessageInterpolator.Context; + +import org.junit.jupiter.api.Test; + +import org.springframework.context.support.StaticMessageSource; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; +import static org.mockito.Mockito.mock; + +/** + * Tests for {@link MessageSourceMessageInterpolator}. + * + * @author Dmytro Nosan + * @author Andy Wilkinson + */ +class MessageSourceMessageInterpolatorTests { + + private final Context context = mock(Context.class); + + private final StaticMessageSource messageSource = new StaticMessageSource(); + + private final MessageSourceMessageInterpolator interpolator = new MessageSourceMessageInterpolator( + this.messageSource, new IdentityMessageInterpolator()); + + @Test + void interpolateShouldReplaceParameters() { + this.messageSource.addMessage("foo", Locale.getDefault(), "fooValue"); + this.messageSource.addMessage("bar", Locale.getDefault(), ""); + assertThat(this.interpolator.interpolate("{foo}{bar}", this.context)).isEqualTo("fooValue"); + } + + @Test + void interpolateWhenParametersAreUnknownShouldLeaveThemUnchanged() { + this.messageSource.addMessage("top", Locale.getDefault(), "{child}+{child}"); + assertThat(this.interpolator.interpolate("{foo}{top}{bar}", this.context)) + .isEqualTo("{foo}{child}+{child}{bar}"); + } + + @Test + void interpolateWhenParametersAreNestedShouldFullyReplaceAllParameters() { + this.messageSource.addMessage("top", Locale.getDefault(), "{child}+{child}"); + this.messageSource.addMessage("child", Locale.getDefault(), "{{differentiator}.grandchild}"); + this.messageSource.addMessage("differentiator", Locale.getDefault(), "first"); + this.messageSource.addMessage("first.grandchild", Locale.getDefault(), "actualValue"); + assertThat(this.interpolator.interpolate("{top}", this.context)).isEqualTo("actualValue+actualValue"); + } + + @Test + void interpolateWhenParameterBracesAreUnbalancedShouldLeaveThemUnchanged() { + this.messageSource.addMessage("top", Locale.getDefault(), "topValue"); + assertThat(this.interpolator.interpolate("\\{top}", this.context)).isEqualTo("\\{top}"); + assertThat(this.interpolator.interpolate("{top\\}", this.context)).isEqualTo("{top\\}"); + assertThat(this.interpolator.interpolate("{{top}", this.context)).isEqualTo("{{top}"); + assertThat(this.interpolator.interpolate("{top}}", this.context)).isEqualTo("topValue}"); + } + + @Test + void interpolateWhenBracesAreEscapedShouldIgnore() { + this.messageSource.addMessage("foo", Locale.getDefault(), "fooValue"); + this.messageSource.addMessage("bar", Locale.getDefault(), "\\{foo}"); + this.messageSource.addMessage("bazz\\}", Locale.getDefault(), "bazzValue"); + assertThat(this.interpolator.interpolate("{foo}", this.context)).isEqualTo("fooValue"); + assertThat(this.interpolator.interpolate("{foo}\\a", this.context)).isEqualTo("fooValue\\a"); + assertThat(this.interpolator.interpolate("\\\\{foo}", this.context)).isEqualTo("\\\\fooValue"); + assertThat(this.interpolator.interpolate("\\\\\\{foo}", this.context)).isEqualTo("\\\\\\{foo}"); + assertThat(this.interpolator.interpolate("\\{foo}", this.context)).isEqualTo("\\{foo}"); + assertThat(this.interpolator.interpolate("{foo\\}", this.context)).isEqualTo("{foo\\}"); + assertThat(this.interpolator.interpolate("\\{foo\\}", this.context)).isEqualTo("\\{foo\\}"); + assertThat(this.interpolator.interpolate("{foo}\\", this.context)).isEqualTo("fooValue\\"); + assertThat(this.interpolator.interpolate("{bar}", this.context)).isEqualTo("\\{foo}"); + assertThat(this.interpolator.interpolate("{bazz\\}}", this.context)).isEqualTo("bazzValue"); + } + + @Test + void interpolateWhenParametersContainACycleShouldThrow() { + this.messageSource.addMessage("a", Locale.getDefault(), "{b}"); + this.messageSource.addMessage("b", Locale.getDefault(), "{c}"); + this.messageSource.addMessage("c", Locale.getDefault(), "{a}"); + assertThatIllegalArgumentException().isThrownBy(() -> this.interpolator.interpolate("{a}", this.context)) + .withMessage("Circular reference '{a -> b -> c -> a}'"); + } + + private static final class IdentityMessageInterpolator implements MessageInterpolator { + + @Override + public String interpolate(String messageTemplate, Context context) { + return messageTemplate; + } + + @Override + public String interpolate(String messageTemplate, Context context, Locale locale) { + return messageTemplate; + } + + } + +}