You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BeanValidator.java 6.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. /*
  2. * Copyright 2000-2018 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.data.validator;
  17. import java.io.Serializable;
  18. import java.util.Locale;
  19. import java.util.Objects;
  20. import java.util.Optional;
  21. import java.util.Set;
  22. import javax.validation.ConstraintViolation;
  23. import javax.validation.MessageInterpolator.Context;
  24. import javax.validation.Validation;
  25. import javax.validation.ValidatorFactory;
  26. import javax.validation.metadata.ConstraintDescriptor;
  27. import com.vaadin.data.ValidationResult;
  28. import com.vaadin.data.Validator;
  29. import com.vaadin.data.ValueContext;
  30. import com.vaadin.data.util.BeanUtil;
  31. /**
  32. * A {@code Validator} using the JSR-303 (javax.validation) annotation-based
  33. * bean validation mechanism. Values passed to this validator are compared
  34. * against the constraints, if any, specified by annotations on the
  35. * corresponding bean property.
  36. * <p>
  37. * Note that a JSR-303 implementation (for instance
  38. * <a href="http://hibernate.org/validator/">Hibernate Validator</a> or
  39. * <a href="http://bval.apache.org/">Apache BVal</a>) must be present on the
  40. * project classpath when using bean validation. Specification versions 1.0 and
  41. * 1.1 are supported.
  42. *
  43. * @author Vaadin Ltd.
  44. *
  45. * @since 8.0
  46. */
  47. public class BeanValidator implements Validator<Object> {
  48. private static final class ContextImpl implements Context, Serializable {
  49. private final ConstraintViolation<?> violation;
  50. private ContextImpl(ConstraintViolation<?> violation) {
  51. this.violation = violation;
  52. }
  53. @Override
  54. public ConstraintDescriptor<?> getConstraintDescriptor() {
  55. return violation.getConstraintDescriptor();
  56. }
  57. @Override
  58. public Object getValidatedValue() {
  59. return violation.getInvalidValue();
  60. }
  61. @Override
  62. public <T> T unwrap(Class<T> type) {
  63. return violation.unwrap(type);
  64. }
  65. }
  66. private String propertyName;
  67. private Class<?> beanType;
  68. /**
  69. * Creates a new JSR-303 {@code BeanValidator} that validates values of the
  70. * specified property. Localizes validation messages using the
  71. * {@linkplain Locale#getDefault() default locale}.
  72. *
  73. * @param beanType
  74. * the bean type declaring the property, not null
  75. * @param propertyName
  76. * the property to validate, not null
  77. * @throws IllegalStateException
  78. * if {@link BeanUtil#checkBeanValidationAvailable()} returns
  79. * false
  80. */
  81. public BeanValidator(Class<?> beanType, String propertyName) {
  82. if (!BeanUtil.checkBeanValidationAvailable()) {
  83. throw new IllegalStateException("Cannot create a "
  84. + BeanValidator.class.getSimpleName()
  85. + ": a JSR-303 Bean Validation implementation not found on the classpath");
  86. }
  87. Objects.requireNonNull(beanType, "bean class cannot be null");
  88. Objects.requireNonNull(propertyName, "property name cannot be null");
  89. this.beanType = beanType;
  90. this.propertyName = propertyName;
  91. }
  92. /**
  93. * Validates the given value as if it were the value of the bean property
  94. * configured for this validator. Returns {@code Result.ok} if there are no
  95. * JSR-303 constraint violations, a {@code Result.error} of chained
  96. * constraint violation messages otherwise.
  97. * <p>
  98. * Null values are accepted unless the property has an {@code @NotNull}
  99. * annotation or equivalent.
  100. *
  101. * @param value
  102. * the input value to validate
  103. * @param context
  104. * the value context for validation
  105. * @return the validation result
  106. */
  107. @Override
  108. public ValidationResult apply(final Object value, ValueContext context) {
  109. Set<? extends ConstraintViolation<?>> violations = getJavaxBeanValidator()
  110. .validateValue(beanType, propertyName, value);
  111. Locale locale = context.getLocale().orElse(Locale.getDefault());
  112. Optional<ValidationResult> result = violations.stream()
  113. .map(violation -> ValidationResult
  114. .error(getMessage(violation, locale)))
  115. .findFirst();
  116. return result.orElse(ValidationResult.ok());
  117. }
  118. @Override
  119. public String toString() {
  120. return String.format("%s[%s.%s]", getClass().getSimpleName(),
  121. beanType.getSimpleName(), propertyName);
  122. }
  123. /**
  124. * Returns the underlying JSR-303 bean validator factory used. A factory is
  125. * created using {@link Validation} if necessary.
  126. *
  127. * @return the validator factory to use
  128. */
  129. protected static ValidatorFactory getJavaxBeanValidatorFactory() {
  130. return LazyFactoryInitializer.FACTORY;
  131. }
  132. /**
  133. * Returns a shared JSR-303 validator instance to use.
  134. *
  135. * @return the validator to use
  136. */
  137. public javax.validation.Validator getJavaxBeanValidator() {
  138. return getJavaxBeanValidatorFactory().getValidator();
  139. }
  140. /**
  141. * Returns the interpolated error message for the given constraint violation
  142. * using the locale specified for this validator.
  143. *
  144. * @param violation
  145. * the constraint violation
  146. * @param locale
  147. * the used locale
  148. * @return the localized error message
  149. */
  150. protected String getMessage(ConstraintViolation<?> violation,
  151. Locale locale) {
  152. return getJavaxBeanValidatorFactory().getMessageInterpolator()
  153. .interpolate(violation.getMessageTemplate(),
  154. createContext(violation), locale);
  155. }
  156. /**
  157. * Creates a simple message interpolation context based on the given
  158. * constraint violation.
  159. *
  160. * @param violation
  161. * the constraint violation
  162. * @return the message interpolation context
  163. */
  164. protected Context createContext(ConstraintViolation<?> violation) {
  165. return new ContextImpl(violation);
  166. }
  167. private static class LazyFactoryInitializer implements Serializable {
  168. private static final ValidatorFactory FACTORY = getFactory();
  169. private static ValidatorFactory getFactory() {
  170. return Validation.buildDefaultValidatorFactory();
  171. }
  172. private LazyFactoryInitializer() {
  173. }
  174. }
  175. }