@Test public void testCustomConstraintValidatorFactory() { Configuration<?> configuration = Validation.byDefaultProvider().configure(); assertDefaultBuilderAndFactory(configuration); ValidatorFactory factory = configuration.buildValidatorFactory(); Validator validator = factory.getValidator(); Customer customer = new Customer(); customer.setFirstName("John"); Set<ConstraintViolation<Customer>> constraintViolations = validator.validate(customer); assertEquals(constraintViolations.size(), 1, "Wrong number of constraints"); ConstraintViolation<Customer> constraintViolation = constraintViolations.iterator().next(); assertEquals("may not be empty", constraintViolation.getMessage(), "Wrong message"); // get a new factory using a custom configuration configuration = Validation.byDefaultProvider().configure(); configuration.constraintValidatorFactory( new ConstraintValidatorFactory() { public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) { if (key == NotNullValidator.class) { return (T) new BadlyBehavedNotNullConstraintValidator(); } return new ConstraintValidatorFactoryImpl().getInstance(key); } }); factory = configuration.buildValidatorFactory(); validator = factory.getValidator(); constraintViolations = validator.validate(customer); assertEquals(constraintViolations.size(), 0, "Wrong number of constraints"); }
@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; }
@BeforeClass public static void setupForAll() { ConstraintViolation cv = mock(ConstraintViolation.class); when(cv.getMessage()).thenReturn(ERROR_MESSAGE_1); ConstraintViolation cv2 = mock(ConstraintViolation.class); when(cv2.getMessage()).thenReturn(ERROR_MESSAGE_2); nonEmptyViolationCollection.addAll(asList(cv, cv2)); }
/** * 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); } } } }
@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"); }
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); }
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; }
@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); }
public void testBeanValidation() throws Exception { Artist a = new Artist(); a.setName("TOO OLD ARTIST"); a.setAge(120); XPersistence.getManager().persist(a); try { XPersistence.commit(); } catch (RollbackException ex) { if (ex.getCause() instanceof javax.validation.ConstraintViolationException) { javax.validation.ConstraintViolationException vex = (javax.validation.ConstraintViolationException) ex.getCause(); assertEquals("1 invalid value is expected", 1, vex.getConstraintViolations().size()); ConstraintViolation violation = vex.getConstraintViolations().iterator().next(); assertEquals("Bean", "Artist", violation.getRootBeanClass().getSimpleName()); String expectedMessage = "es".equals(Locale.getDefault().getLanguage()) ? "tiene que ser menor o igual que 90" : "must be less than or equal to 90"; assertEquals("Message text", expectedMessage, violation.getMessage()); return; } } fail("A constraint violation exception should be thrown"); }
protected boolean jsr303ValidateBean(T bean) { try { if (javaxBeanValidator == null) { javaxBeanValidator = getJavaxBeanValidatorFactory().getValidator(); } } catch (Throwable t) { // This may happen without JSR303 validation framework Logger.getLogger(getClass().getName()).fine("JSR303 validation failed"); return true; } Set<ConstraintViolation<T>> constraintViolations = new HashSet(javaxBeanValidator.validate(bean, getValidationGroups())); if (constraintViolations.isEmpty()) { return true; } Iterator<ConstraintViolation<T>> iterator = constraintViolations.iterator(); while (iterator.hasNext()) { ConstraintViolation<T> constraintViolation = iterator.next(); Class<? extends Annotation> annotationType = constraintViolation.getConstraintDescriptor().getAnnotation().annotationType(); AbstractComponent errortarget = validatorToErrorTarget.get(annotationType); if (errortarget != null) { // user has declared a target component for this constraint errortarget.setComponentError(new UserError(constraintViolation.getMessage())); iterator.remove(); } // else leave as "bean level error" } this.jsr303beanLevelViolations = constraintViolations; return false; }
@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); } }
@Override public void saveEntities(DataImportContext context) { bindEntities(context); Object[] entities = context.getEntities(); SystemDAO systemDAO = DAOFactory.getInstance().getSystemDAO(); for (int i = 0; i < entities.length; i++) { Object entity = entities[i]; Set<ConstraintViolation<Object>> constraintViolations = systemDAO.validateEntity(entity); if (constraintViolations.size() == 0) { systemDAO.persistEntity(entity); } else { String message = ""; for (ConstraintViolation<Object> constraintViolation : constraintViolations) { message += constraintViolation.getMessage() + '\n'; } throw new SmvcRuntimeException( PyramusStatusCode.VALIDATION_FAILURE, "Validation failure: " + message); } } }
protected boolean existsViolationsForJSF(Serializable entidade) { Set<ConstraintViolation<Serializable>> toReturn = getViolations(entidade); if (toReturn.isEmpty()) return false; for (ConstraintViolation<Serializable> constraintViolation : toReturn) { createFacesErrorMessage(constraintViolation.getMessage(), null); } return true; }
public CommandConstraintException(Set<ConstraintViolation<ICommand>> constraintViolations) { if (UtilValidator.isNotEmpty(constraintViolations)) { for (ConstraintViolation constraintViolation : constraintViolations) { constraintMessages.add(constraintViolation.getMessage()); } this.constraintViolations = constraintViolations; } }
/** 辅助方法, 转换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; }
public void handleValidationException(ValidationException exception, ResponseBuilder builder) { builder.status(BAD_REQUEST); ValidationErrorMessageWrapper error = new ValidationErrorMessageWrapper(); for (ConstraintViolation<Object> violation : exception.getViolations()) { error.addMessage(violation.getMessage()); } builder.entity(error); }
/** * When dealing with @ValidateWith annotations, and message parameter is not used in the * annotation, extract the message from validator's getErrorMessageKey() method */ protected String getMessageForConstraintViolation(ConstraintViolation<Object> violation) { String errorMessage = violation.getMessage(); Annotation annotation = violation.getConstraintDescriptor().getAnnotation(); if (annotation instanceof Constraints.ValidateWith) { Constraints.ValidateWith validateWithAnnotation = (Constraints.ValidateWith) annotation; if (violation.getMessage().equals(Constraints.ValidateWithValidator.defaultMessage)) { Constraints.ValidateWithValidator validateWithValidator = new Constraints.ValidateWithValidator(); validateWithValidator.initialize(validateWithAnnotation); Tuple<String, Object[]> errorMessageKey = validateWithValidator.getErrorMessageKey(); if (errorMessageKey != null && errorMessageKey._1 != null) { errorMessage = errorMessageKey._1; } } } return errorMessage; }
/** 辅助方法, 转换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; }
/** 辅助方法, 转换Set<ConstraintViolation>为List<message> */ @SuppressWarnings("rawtypes") public static List<String> extractMessage( Set<? extends ConstraintViolation> constraintViolations) { List<String> errorMessages = Lists.newArrayList(); for (ConstraintViolation violation : constraintViolations) { errorMessages.add(violation.getMessage()); } return errorMessages; }
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()); } }
/** 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()); } }
public String formatInvalidationInfo(Set<ConstraintViolation<T>> infos, String model) { Iterator<ConstraintViolation<T>> it = infos.iterator(); StringBuilder sb = new StringBuilder(); while (it.hasNext()) { ConstraintViolation<T> t = it.next(); sb.append(model + " ").append(t.getMessage()).append(" "); } return sb.toString(); }
@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); }
@Test(expected = AppException.class) public void createWithValidationError() throws AppException { SampleEntity sample = createSampleEntity(ID, "IPI"); Set<ConstraintViolation<SampleEntity>> violations = new HashSet<>(); ConstraintViolation constraintViolation = Mockito.mock(ConstraintViolation.class); violations.add(constraintViolation); Mockito.when(constraintViolation.getMessage()).thenReturn("Error"); Mockito.when(validator.validate(sample)).thenReturn(violations); service.create(sample); }
// Validación de las propiedades del objeto Artículo public List<String> directValidate() { Set<ConstraintViolation<Articulo>> violations = Validation.getValidator().validate(this); List<String> errors = new ArrayList<String>(); for (ConstraintViolation<Articulo> cv : violations) { errors.add(cv.getMessage()); } String violation = this.validate(); if (violation != null) { errors.add(violation); } return errors; }
public static boolean hasErrors(Object obj, String message) { if (message != null) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> errors = validator.validate(obj); for (ConstraintViolation<Object> constraintViolation : errors) { if (message.equals(constraintViolation.getMessage())) { return true; } } } return false; }
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 testeNomeVazio() { Titulo titulo = new Titulo(); titulo.setNome(""); 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.getMessage(), "Campo obrigatório"); Assert.assertEquals(violacao.getPropertyPath().toString(), "nome"); }