Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

BeanValidator.java 6.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. /*
  2. * Copyright 2000-2016 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. }
  62. private String propertyName;
  63. private Class<?> beanType;
  64. /**
  65. * Creates a new JSR-303 {@code BeanValidator} that validates values of the
  66. * specified property. Localizes validation messages using the
  67. * {@linkplain Locale#getDefault() default locale}.
  68. *
  69. * @param beanType
  70. * the bean type declaring the property, not null
  71. * @param propertyName
  72. * the property to validate, not null
  73. * @throws IllegalStateException
  74. * if {@link BeanUtil#checkBeanValidationAvailable()} returns
  75. * false
  76. */
  77. public BeanValidator(Class<?> beanType, String propertyName) {
  78. if (!BeanUtil.checkBeanValidationAvailable()) {
  79. throw new IllegalStateException("Cannot create a "
  80. + BeanValidator.class.getSimpleName()
  81. + ": a JSR-303 Bean Validation implementation not found on the classpath");
  82. }
  83. Objects.requireNonNull(beanType, "bean class cannot be null");
  84. Objects.requireNonNull(propertyName, "property name cannot be null");
  85. this.beanType = beanType;
  86. this.propertyName = propertyName;
  87. }
  88. /**
  89. * Validates the given value as if it were the value of the bean property
  90. * configured for this validator. Returns {@code Result.ok} if there are no
  91. * JSR-303 constraint violations, a {@code Result.error} of chained
  92. * constraint violation messages otherwise.
  93. * <p>
  94. * Null values are accepted unless the property has an {@code @NotNull}
  95. * annotation or equivalent.
  96. *
  97. * @param value
  98. * the input value to validate
  99. * @param context
  100. * the value context for validation
  101. * @return the validation result
  102. */
  103. @Override
  104. public ValidationResult apply(final Object value, ValueContext context) {
  105. Set<? extends ConstraintViolation<?>> violations = getJavaxBeanValidator()
  106. .validateValue(beanType, propertyName, value);
  107. Locale locale = context.getLocale().orElse(Locale.getDefault());
  108. Optional<ValidationResult> result = violations.stream()
  109. .map(violation -> ValidationResult
  110. .error(getMessage(violation, locale)))
  111. .findFirst();
  112. return result.orElse(ValidationResult.ok());
  113. }
  114. @Override
  115. public String toString() {
  116. return String.format("%s[%s.%s]", getClass().getSimpleName(),
  117. beanType.getSimpleName(), propertyName);
  118. }
  119. /**
  120. * Returns the underlying JSR-303 bean validator factory used. A factory is
  121. * created using {@link Validation} if necessary.
  122. *
  123. * @return the validator factory to use
  124. */
  125. protected static ValidatorFactory getJavaxBeanValidatorFactory() {
  126. return LazyFactoryInitializer.FACTORY;
  127. }
  128. /**
  129. * Returns a shared JSR-303 validator instance to use.
  130. *
  131. * @return the validator to use
  132. */
  133. protected javax.validation.Validator getJavaxBeanValidator() {
  134. return getJavaxBeanValidatorFactory().getValidator();
  135. }
  136. /**
  137. * Returns the interpolated error message for the given constraint violation
  138. * using the locale specified for this validator.
  139. *
  140. * @param violation
  141. * the constraint violation
  142. * @param locale
  143. * the used locale
  144. * @return the localized error message
  145. */
  146. protected String getMessage(ConstraintViolation<?> violation,
  147. Locale locale) {
  148. return getJavaxBeanValidatorFactory().getMessageInterpolator()
  149. .interpolate(violation.getMessageTemplate(),
  150. createContext(violation), locale);
  151. }
  152. /**
  153. * Creates a simple message interpolation context based on the given
  154. * constraint violation.
  155. *
  156. * @param violation
  157. * the constraint violation
  158. * @return the message interpolation context
  159. */
  160. protected Context createContext(ConstraintViolation<?> violation) {
  161. return new ContextImpl(violation);
  162. }
  163. private static class LazyFactoryInitializer implements Serializable {
  164. private static final ValidatorFactory FACTORY = getFactory();
  165. private static ValidatorFactory getFactory() {
  166. return Validation.buildDefaultValidatorFactory();
  167. }
  168. private LazyFactoryInitializer() {
  169. }
  170. }
  171. }