@Test public void testValidation() throws Exception { final String value = Strings.random(16); ValidatedBean bean = new ValidatedBean(); assertNull(bean.getValue()); /* Null test! */ try { store.store(bean); fail("ConstraintViolationException not thrown"); } catch (ConstraintViolationException exception) { final Set<ConstraintViolation<?>> violations = exception.getConstraintViolations(); assertEquals(violations.size(), 1, "Wrong number of violations"); final ConstraintViolation<?> violation = violations.iterator().next(); assertNotNull(violation, "Null violation"); assertEquals( violation.getMessage(), "The null value shall not be saved!", "Wrong violation message"); assertEquals(violation.getPropertyPath().toString(), "value", "Wrong violation path"); System.out.println(violation.getPropertyPath().toString()); // TODO validate! } /* Empty string test! */ try { bean.setValue(""); store.store(bean); fail("ConstraintViolationException not thrown"); } catch (ConstraintViolationException exception) { final Set<ConstraintViolation<?>> violations = exception.getConstraintViolations(); assertEquals(violations.size(), 1, "Wrong number of violations"); final ConstraintViolation<?> violation = violations.iterator().next(); assertNotNull(violation, "Null violation"); assertEquals( violation.getMessage(), "The value shall be longer than 1 characters!", "Wrong violation message"); assertEquals(violation.getPropertyPath().toString(), "value", "Wrong violation path"); } /* Good value test! */ bean.setValue(value); bean = store.store(bean); assertNotNull(bean, "Null stored bean"); assertEquals(bean.value, value, "Wrong stored value"); /* Re-read to ensure */ bean = store.find(bean.id()); assertNotNull(bean, "Null retrieved bean"); assertEquals(bean.value, value, "Wrong retrieved value"); }
@Override public Category add( Category category) { // throws FieldNotValidException, CategoryExistentException { Not needed as it // is mentioned in the interface // Validating the Hibernate Annotations Set<ConstraintViolation<Category>> errors = validator.validate(category); Iterator<ConstraintViolation<Category>> itErrors = errors.iterator(); if (itErrors.hasNext()) { ConstraintViolation<Category> violation = itErrors.next(); throw new FieldNotValidException( violation.getPropertyPath().toString(), violation.getMessage()); // violation.getPropertyPath().toString() => // return "Category [id=" + id + ", name=" + name + "]"; } if (categoryRepo.alreadyExists(category)) { throw new CategoryExistentException(); } return categoryRepo.add(category); }
private static void doSomething(ApplicationContext context) { OrderService orderService = context.getBean(OrderService.class); String customerId = "CUS0001"; Item item = context.getBean(Item.class); item.setName("ITEM0001"); item.setZipCode("110000"); Order order = null; try { order = orderService.placeOrder(customerId, item, 3); } catch (ConstraintViolationException e) { // TODO Auto-generated catch block Set<ConstraintViolation<?>> results = e.getConstraintViolations(); for (ConstraintViolation<?> result : results) { // System.out.println("校验错误信息模板: " + result.getMessageTemplate()); System.out.println( "" + result.getLeafBean().getClass().getName() + "." + result.getPropertyPath() + ": " + result.getMessage()); // System.out.println(result.getConstraintDescriptor()); } // System.out.println(results); } System.out.println("返回的订单信息: " + order); }
@SuppressWarnings("unchecked") public void afterPropertiesSet() throws Exception { Assert.state(yaml != null, "Yaml document should not be null"); Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); try { logger.trace("Yaml document is\n" + yaml); configuration = (T) (new Yaml(constructor)).load(yaml); Set<ConstraintViolation<T>> errors = validator.validate(configuration); if (!errors.isEmpty()) { logger.error("YAML configuration failed validation"); for (ConstraintViolation<?> error : errors) { logger.error(error.getPropertyPath() + ": " + error.getMessage()); } if (exceptionIfInvalid) { @SuppressWarnings("rawtypes") ConstraintViolationException summary = new ConstraintViolationException((Set) errors); throw summary; } } } catch (YAMLException e) { if (exceptionIfInvalid) { throw e; } logger.error("Failed to load YAML validation bean. Your YAML file may be invalid.", e); } }
public static <T> List<ValidationMessages> validateEntity( Validator validator, T entity, Class<?>... groups) { Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity, groups); Map<String, List<String>> fieldMessages = new HashMap<>(); if (!constraintViolations.isEmpty()) { for (ConstraintViolation<T> constraintViolation : constraintViolations) { String property = constraintViolation.getPropertyPath().toString(); List<String> messages = fieldMessages.get(property); if (messages == null) { messages = new ArrayList<>(); fieldMessages.put(property, messages); } messages.add(constraintViolation.getMessage()); } } List<ValidationMessages> validationErrors = new ArrayList<>(); fieldMessages.forEach( (k, v) -> { ValidationMessages errors = new ValidationMessages(); errors.setField(k); errors.setMessages(v.toArray(new String[v.size()])); validationErrors.add(errors); }); return validationErrors; }
public Type getConstraintType(Object o) { if (!(o instanceof ConstraintViolation)) { throw new RuntimeException(Messages.MESSAGES.unknownObjectPassedAsConstraintViolation(o)); } ConstraintViolation<?> v = ConstraintViolation.class.cast(o); if (v instanceof MethodConstraintViolation) { MethodConstraintViolation<?> mv = MethodConstraintViolation.class.cast(v); return mv.getKind() == MethodConstraintViolation.Kind.PARAMETER ? Type.PARAMETER : Type.RETURN_VALUE; } Object b = v.getRootBean(); String fieldName = null; Iterator<Node> it = v.getPropertyPath().iterator(); while (it.hasNext()) { Node node = it.next(); fieldName = node.getName(); if (fieldName == null) { return Type.CLASS; } } String getterName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); try { // getMethod(v.getLeafBean().getClass(), getterName); getMethod(v.getRootBeanClass(), getterName); return Type.PROPERTY; } catch (NoSuchMethodException e) { return Type.FIELD; } }
@SuppressWarnings("rawtypes") @Override public Response toResponse(javax.validation.ValidationException exception) { Response.Status errorStatus = Response.Status.INTERNAL_SERVER_ERROR; List<String> errorsList = new ArrayList<String>(); if (exception instanceof ConstraintViolationException) { ConstraintViolationException constraint = (ConstraintViolationException) exception; Iterator i$ = constraint.getConstraintViolations().iterator(); while (i$.hasNext()) { ConstraintViolation violation = (ConstraintViolation) i$.next(); String errorMessage = this.getPropertyName(violation) + ": " + violation.getMessage(); errorsList.add(errorMessage); LOG.error( violation.getRootBeanClass().getSimpleName() + "." + violation.getPropertyPath() + ": " + violation.getMessage()); } if (!(constraint instanceof ResponseConstraintViolationException)) { errorStatus = Response.Status.BAD_REQUEST; } } String errorsAsString = StringUtils.join(errorsList, ", "); Response response = Response.status(errorStatus).entity(errorsAsString).build(); return response; }
private Path.Node getLeafNode(ConstraintViolation<?> constraintViolation) { Iterator<Path.Node> nodes = constraintViolation.getPropertyPath().iterator(); Path.Node leafNode = null; while (nodes.hasNext()) { leafNode = nodes.next(); } return leafNode; }
/** * @param e * @param errorCode * @param propertyPath */ public static void assertViolationContainsTemplateAndPath( final ConstraintViolationException e, final String errorCode, final String propertyPath) { Assert.assertNotNull(e.getConstraintViolations()); Assert.assertEquals(1, CollectionUtils.size(e.getConstraintViolations())); final ConstraintViolation<?> violation = e.getConstraintViolations().iterator().next(); Assert.assertEquals(errorCode, violation.getMessageTemplate()); Assert.assertEquals(propertyPath, violation.getPropertyPath().toString()); }
private <T> Map<String, ConstraintViolation<T>> validate(T user) { Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); Map<String, ConstraintViolation<T>> violations = new HashMap<String, ConstraintViolation<T>>(); for (ConstraintViolation<T> violation : validator.validate(user)) { violations.put(violation.getPropertyPath().toString(), violation); } return violations; }
@Override public String getPath() { /* * TODO(bobv,nchalko): Determine the correct way to extract this * information from the ConstraintViolation. */ return v.getPropertyPath().toString(); }
/** 辅助方法, 转换Set<ConstraintViolation>为List<propertyPath +separator+ message>. */ @SuppressWarnings("rawtypes") public static List<String> extractPropertyAndMessageAsList( Set<? extends ConstraintViolation> constraintViolations, String separator) { List<String> errorMessages = Lists.newArrayList(); for (ConstraintViolation violation : constraintViolations) { errorMessages.add(violation.getPropertyPath() + separator + violation.getMessage()); } return errorMessages; }
/** 辅助方法, 转换Set<ConstraintViolation>为Map<property, message>. */ @SuppressWarnings("rawtypes") public static Map<String, String> extractPropertyAndMessage( Set<? extends ConstraintViolation> constraintViolations) { Map<String, String> errorMessages = Maps.newHashMap(); for (ConstraintViolation violation : constraintViolations) { errorMessages.put(violation.getPropertyPath().toString(), violation.getMessage()); } return errorMessages; }
@SuppressWarnings("rawtypes") private String getPropertyName(ConstraintViolation violation) { Iterator iterator = violation.getPropertyPath().iterator(); Path.Node property = (Path.Node) iterator.next(); while (iterator.hasNext()) { property = (Path.Node) iterator.next(); } return property.getName(); }
private void checkConstraint(String expected, ConstraintViolationException e) { for (ConstraintViolation<?> constraintViolation : e.getConstraintViolations()) { String actual = constraintViolation.getPropertyPath().toString(); if (actual.equals(expected)) { return; } } fail(); }
/** * Process the given JSR-303 ConstraintViolations, adding corresponding errors to the provided * Spring {@link Errors} object. * * @param violations the JSR-303 ConstraintViolation results * @param errors the Spring errors object to register to */ protected void processConstraintViolations( Set<ConstraintViolation<Object>> violations, Errors errors) { for (ConstraintViolation<Object> violation : violations) { String field = violation.getPropertyPath().toString(); FieldError fieldError = errors.getFieldError(field); if (fieldError == null || !fieldError.isBindingFailure()) { try { ConstraintDescriptor<?> cd = violation.getConstraintDescriptor(); String errorCode = cd.getAnnotation().annotationType().getSimpleName(); Object[] errorArgs = getArgumentsForConstraint(errors.getObjectName(), field, cd); if (errors instanceof BindingResult) { // Can do custom FieldError registration with invalid value from ConstraintViolation, // as necessary for Hibernate Validator compatibility (non-indexed set path in field) BindingResult bindingResult = (BindingResult) errors; String nestedField = bindingResult.getNestedPath() + field; if ("".equals(nestedField)) { String[] errorCodes = bindingResult.resolveMessageCodes(errorCode); bindingResult.addError( new ObjectError( errors.getObjectName(), errorCodes, errorArgs, violation.getMessage())); } else { Object invalidValue = violation.getInvalidValue(); if (!"".equals(field) && (invalidValue == violation.getLeafBean() || (field.contains(".") && !field.contains("[]")))) { // Possibly a bean constraint with property path: retrieve the actual property // value. // However, explicitly avoid this for "address[]" style paths that we can't handle. invalidValue = bindingResult.getRawFieldValue(field); } String[] errorCodes = bindingResult.resolveMessageCodes(errorCode, field); bindingResult.addError( new FieldError( errors.getObjectName(), nestedField, invalidValue, false, errorCodes, errorArgs, violation.getMessage())); } } else { // got no BindingResult - can only do standard rejectValue call // with automatic extraction of the current field value errors.rejectValue(field, errorCode, errorArgs, violation.getMessage()); } } catch (NotReadablePropertyException ex) { throw new IllegalStateException( "JSR-303 validated property '" + field + "' does not have a corresponding accessor for Spring data binding - " + "check your DataBinder's configuration (bean property versus direct field access)", ex); } } } }
public static void main(String[] args) { Movimentacao m = new Movimentacao(); m.setValor(BigDecimal.ZERO); Validator validator = new ValidatorUtil().getValidator(); Set<ConstraintViolation<Movimentacao>> list = validator.validate(m); for (ConstraintViolation<Movimentacao> erro : list) { System.out.println(erro.getMessage()); System.out.println(erro.getPropertyPath()); } }
public <T> Validator addAll(Set<ConstraintViolation<T>> errors) { for (ConstraintViolation<T> v : errors) { String msg = interpolator.interpolate(v.getMessageTemplate(), new BeanValidatorContext(v), locale); String category = v.getPropertyPath().toString(); add(new SimpleMessage(category, msg)); logger.debug("added message {}={} for contraint violation", category, msg); } return this; }
/** Converts a ConstraintViolation to a FieldError */ private static FieldError of(ConstraintViolation<?> constraintViolation) { // Get the field name by removing the first part of the propertyPath. // (The first part would be the service method name) String field = StringUtils.substringAfter(constraintViolation.getPropertyPath().toString(), "."); return new FieldError( field, constraintViolation.getMessageTemplate(), constraintViolation.getMessage()); }
@Test public void testValidator() { User user = new User(); user.setEmail("s"); user.setPassword("12345678"); Set<ConstraintViolation<User>> errors = validator.validate(user); for (ConstraintViolation<User> error : errors) { System.out.println(error.getPropertyPath() + error.getMessage()); } }
@Test public void invalidUser() throws Exception { User user = new User("us", "password", "name", "email"); Set<ConstraintViolation<User>> constraintViolations = validator.validate(user); assertEquals(2, constraintViolations.size()); Iterator<ConstraintViolation<User>> violations = constraintViolations.iterator(); while (violations.hasNext()) { ConstraintViolation<User> each = violations.next(); System.out.println(each.getPropertyPath() + " : " + each.getMessage()); } }
private Response.ResponseBuilder createViolationResponse(Set<ConstraintViolation<?>> violations) { logger.fine("Validation completed. violations found: " + violations.size()); Map<String, String> responseObj = new HashMap<String, String>(); for (ConstraintViolation<?> violation : violations) { responseObj.put(violation.getPropertyPath().toString(), violation.getMessage()); } return Response.status(Response.Status.BAD_REQUEST).entity(responseObj); }
private void displayContraintViolations(Set<ConstraintViolation<Book03>> constraintViolations) { for (ConstraintViolation constraintViolation : constraintViolations) { System.out.println( "### " + constraintViolation.getRootBeanClass().getSimpleName() + "." + constraintViolation.getPropertyPath() + " - Invalid Value = " + constraintViolation.getInvalidValue() + " - Error Msg = " + constraintViolation.getMessage()); } }
@Test public void testeNomeNulo() { Titulo titulo = new Titulo(); titulo.setNome(null); titulo.setIsbn("1234567890"); titulo.setTipo("TIPO"); Validator validator = createValidator(); Set<ConstraintViolation<Titulo>> constraintViolations = validator.validate(titulo); Assert.assertEquals(1, constraintViolations.size()); ConstraintViolation<Titulo> violacao = constraintViolations.iterator().next(); Assert.assertEquals(violacao.getPropertyPath().toString(), "nome"); }
public void add(Estado obj) { if (obj == null) { throw new AppException("El estado no puede ser nulo"); } Set<ConstraintViolation<Estado>> violations = this.validator.validate(obj); if (!violations.isEmpty()) { String msg = ""; for (ConstraintViolation<Estado> v : violations) { msg += v.getPropertyPath() + ": " + v.getMessage(); } throw new AppException(msg); } this.usuarioDAO.add(obj); }
private void validateFixture(IFixture fixture, Validator validator) { Set<ConstraintViolation<IFixture>> violations = validator.validate(fixture); for (ConstraintViolation<IFixture> violation : violations) { if (violation.getLeafBean() instanceof ICompetition && "detail.competition.name".equals(violation.getPropertyPath().toString())) { assertEquals(violation.getLeafBean(), fixture.getCompetition()); Annotation annotation = violation.getConstraintDescriptor().getAnnotation(); assertEquals(annotation.annotationType(), NotNull.class); return; } } fail("@NotNull constraint violation for 'detail.competition.name' not detected"); }
@POST @ValidateOnExecution(type = ExecutableType.NONE) public Response formPost(@Valid @BeanParam FormDataBean form) { final BindingResult vr = getVr(); if (vr.isFailed()) { final Set<ConstraintViolation<?>> set = vr.getAllViolations(); final ConstraintViolation<?> cv = set.iterator().next(); final String property = cv.getPropertyPath().toString(); error.setProperty(property.substring(property.lastIndexOf('.') + 1)); error.setValue(cv.getInvalidValue()); error.setMessage(cv.getMessage()); return Response.status(BAD_REQUEST).entity("error.jsp").build(); } return Response.status(OK).entity("data.jsp").build(); }
@Test public void testeTipoVazio() { Titulo titulo = new Titulo(); titulo.setNome("Nome"); titulo.setIsbn("1234567890"); titulo.setTipo(""); Validator validator = createValidator(); Set<ConstraintViolation<Titulo>> constraintViolations = validator.validate(titulo); Assert.assertEquals(1, constraintViolations.size()); ConstraintViolation<Titulo> violacao = constraintViolations.iterator().next(); Assert.assertEquals(violacao.getMessage(), "Campo obrigatório"); Assert.assertEquals(violacao.getPropertyPath().toString(), "tipo"); }
@Test public void testeISBN13CaracteresComEspaco() { Titulo titulo = new Titulo(); titulo.setNome("Nome"); titulo.setIsbn("123456 789011"); titulo.setTipo("TIPO"); Validator validator = createValidator(); Set<ConstraintViolation<Titulo>> constraintViolations = validator.validate(titulo); Assert.assertEquals(1, constraintViolations.size()); ConstraintViolation<Titulo> violacao = constraintViolations.iterator().next(); Assert.assertEquals(violacao.getMessage(), "O isbn não pode conter espaços"); Assert.assertEquals(violacao.getPropertyPath().toString(), "isbn"); }
/* * (non-Javadoc) * * @see java.lang.Throwable#getMessage() */ @Override public String getMessage() { String message = "There are violations [" + ls; for (ConstraintViolation<AbstractValidatedCatalogue> violation : violations) { message += violation.getRootBeanClass().getName() + "." + violation.getPropertyPath() + " " + violation.getMessage() + ls; } message += "]"; return message; }