private boolean validateInterestDate(Object validateThis, ConstraintValidatorContext ctx, Field fieldObj, Field dependentFieldObj) throws IllegalAccessException { InterestDate interestDate = (InterestDate) fieldObj.get(validateThis); Interest interest = (Interest) dependentFieldObj.get(validateThis); if (interest != null && !interestTypeIsNoInterest(interest.getType())) { Set<ConstraintViolation<Object>> violations = validator.validate(interestDate); if (!violations.isEmpty()) { ctx.disableDefaultConstraintViolation(); ctx.buildConstraintViolationWithTemplate(getViolationMessages(violations, ctx)) .addPropertyNode(field) .addConstraintViolation(); return false; } } return true; }
public static void main(String[] args) throws NoSuchMethodException, SecurityException { AutoRunHelper.run(App.class); // 测试参数校验 App app = new App(); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); ExecutableValidator executableValidator = factory.getValidator().forExecutables(); Method method = App.class.getMethod("showEmail", String.class); Object[] parameterValues = {"email"}; Set<ConstraintViolation<App>> violations = executableValidator.validateParameters(app, method, parameterValues); String message = violations.iterator().hasNext() ? violations.iterator().next().getMessage() : ""; System.out.println("values:" + parameterValues[0].toString() + " size: " + violations.size() + " msg:" + message); Object[] parameterValues2 = {"abc"}; violations = executableValidator.validateParameters(app, method, parameterValues2); message = violations.iterator().hasNext() ? violations.iterator().next().getMessage() : ""; System.out.println("values:" + parameterValues2[0].toString() + " size: " + violations.size() + " msg:" + message); }
/** * 对象校验,依据validator * use case * 派单前做的工单校验 * * @param t * @param <T> * @return */ public <T> T checkObjParamValidate(@NotNull T t, Class<?>... groups) { BusinessAssert.requireNonEmpty(t, MessageSourceUtil.getChinese(messageSource, "param.null")); //是否符合validator校验 StringBuilder errorMsg = new StringBuilder(); Set<ConstraintViolation<T>> constraintViolationSet = null; if (!Check.isNullObjects(groups)) { constraintViolationSet = validator.validate(t, groups); } else { constraintViolationSet = validator.validate(t); } if (!Check.isNullOrEmpty(constraintViolationSet)) { Iterator<ConstraintViolation<T>> iterator = constraintViolationSet.iterator(); while (iterator.hasNext()) { ConstraintViolation<T> constraint = iterator.next(); errorMsg.append(constraint.getMessage()).append(","); } //设置错误信息 if (errorMsg.length() != 0) { errorMsg.deleteCharAt(errorMsg.length() - 1); throw new ValidatorException(errorMsg.toString()); } } return t; }
@Override protected void handleValidation(final Message message, final Object resourceInstance, final Method method, final List<Object> arguments) { super.handleValidation(message, resourceInstance, method, arguments); // Check each parameter final Set<ConstraintViolation<?>> validationErrors = new HashSet<>(); for (int index = 0; index < arguments.size(); index++) { final Parameter parameter = method.getParameters()[index]; if (hasToBeValidated(parameter)) { // This parameter is a not context, path or query parameter validate(arguments.get(index), method, parameter, index, validationErrors); } } // Check the veto if (!validationErrors.isEmpty()) { message.put(FaultListener.class.getName(), new NoOpFaultListener()); throw new ConstraintViolationException(validationErrors); } }
@Test public void testNestedPropertyNotNull() { ProjectData data = new ProjectData(); data.setValue(null); // violation Project project = new Project(); project.setId(1L); project.setName("test"); project.setData(data); try { projectRepo.create(project); } catch (ConstraintViolationException e) { Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); Assert.assertEquals(1, violations.size()); ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next(); Assert.assertEquals("{javax.validation.constraints.NotNull.message}", violation.getMessageTemplate()); Assert.assertEquals("data.value", violation.getPropertyPath().toString()); Assert.assertEquals("/data/attributes/data/value", violation.getErrorData().getSourcePointer()); } }
public List<Account> getAccounts() { final Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); final ObjectMapper mapper = new ObjectMapper() .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); List<Account> accounts = null; try { accounts = mapper.readValue(rulesFile, new TypeReference<List<Account>>() {}); if (accounts != null) { accounts.forEach((account) -> { final Set<ConstraintViolation<Account>> accountViolations = validator.validate(account); if (accountViolations.size() > 0) { throw new AccountValidationException(accountViolations); } account.getRules().sort((o1, o2) -> o1.getType().compareTo(o2.getType())); }); } } catch (IOException ex) { Logger.getLogger(AccountService.class.getName()).log(Level.SEVERE, null, ex); } return accounts; }
@Test public void validateMapKeyContainerElementConstraint() { //tag::validateMapKeyContainerElementConstraint[] Car car = new Car(); car.setFuelConsumption( null, 5 ); Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car ); assertEquals( 1, constraintViolations.size() ); ConstraintViolation<Car> constraintViolation = constraintViolations.iterator().next(); assertEquals( "must not be null", constraintViolation.getMessage() ); assertEquals( "fuelConsumption<K>[].<map key>", constraintViolation.getPropertyPath().toString() ); //end::validateMapKeyContainerElementConstraint[] }
/** * The exception handler is trigger if a JSR303 {@link ConstraintViolationException} * is being raised. * * Log the exception message at warn level and stack trace as trace level. * Return response status HttpStatus.BAD_REQUEST (400). */ @ExceptionHandler({ConstraintViolationException.class}) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public VndErrors onConstraintViolationException(ConstraintViolationException e) { String logref = logWarnLevelExceptionMessage(e); if (logger.isTraceEnabled()) { logTraceLevelStrackTrace(e); } final StringBuilder errorMessage = new StringBuilder(); boolean first = true; for (ConstraintViolation<?> violation : e.getConstraintViolations()) { if (!first) { errorMessage.append("; "); } errorMessage.append(violation.getMessage()); first = false; } return new VndErrors(logref, errorMessage.toString()); }
@Test public void testRelationProperty() { Task task = new Task(); task.setId(1L); task.setName("test"); taskRepo.create(task); task.setName(ComplexValidator.INVALID_NAME); Project project = new Project(); project.setName("test"); project.setTask(task); try { projectRepo.create(project); } catch (ConstraintViolationException e) { Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); Assert.assertEquals(1, violations.size()); ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next(); Assert.assertEquals("{complex.message}", violation.getMessageTemplate()); Assert.assertEquals("task", violation.getPropertyPath().toString()); Assert.assertEquals("/data/relationships/task", violation.getErrorData().getSourcePointer()); } }
/** * Validates the {@code request} based on its type and returns it or throws a {@code ValidationException} * if any {@link ConstraintViolation} is found. * * @param request the request object to validate * @param <T> request type param * @return The validated request(the same object passed as {@code request}) * @throws ValidationException if any {@link ConstraintViolation} is found */ public static <T extends SafechargeBaseRequest> T validate(T request) throws ValidationException { Set<ConstraintViolation<T>> constraintViolations = validator.validate(request); if (constraintViolations != null && !constraintViolations.isEmpty()) { StringBuilder sb = new StringBuilder(); for (ConstraintViolation<T> constraintViolation : constraintViolations) { sb.append(constraintViolation.getMessage()) .append(" "); } String errorMessage = sb.toString(); if (logger.isDebugEnabled()) { logger.debug(errorMessage); } throw new ConstraintViolationException(constraintViolations); } return request; }
/** * Check not valid parameter operation failed. */ @Test public void objectNull() { final SystemUser userDto = null; try { validationInInterceptor.handleValidation(MESSAGE, INSTANCE, fromName("object"), Arrays.asList(userDto)); Assert.fail("Expected validation errors"); } catch (final ConstraintViolationException cve) { // Check all expected errors are there. final Set<ConstraintViolation<?>> constraintViolations = cve.getConstraintViolations(); Assert.assertNotNull(constraintViolations); Assert.assertEquals(1, constraintViolations.size()); // Check expected errors final ConstraintViolation<?> error1 = constraintViolations.iterator().next(); Assert.assertEquals(NotNull.class, error1.getConstraintDescriptor().getAnnotation().annotationType()); Assert.assertEquals("object.param", error1.getPropertyPath().toString()); } }
public static <T> ValidationResult validateProperty(T obj, String propertyName) { ValidationResult result = new ValidationResult(); Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, Default.class); if (CollectionUtils.isNotEmpty(set)) { result.setHasErrors(true); Map<String, String> errorMsg = Maps.newHashMap(); for (ConstraintViolation<T> cv : set) { errorMsg.put(propertyName, cv.getMessage()); } result.setErrorMsg(errorMsg); } return result; }
protected void validate() { // Clear all validation errors propertyToBindingMap.values().stream().forEach(e -> e.clearValidationError()); // Validate and set validation errors if (getBean() != null) { constraintViolations = validator.validate(getBean(), groups); constraintViolations.stream().forEach(e -> handleConstraintViolations(e, f -> f.getMessage())); } else { constraintViolations = new HashSet<ConstraintViolation<BEAN>>(); } List<BindingValidationStatus<?>> binRes = getBindings().stream().map(e -> e.validate(false)).collect(Collectors.toList()); List<ValidationResult> valRes = constraintViolations.stream() .filter(e -> e.getPropertyPath().toString().isEmpty()) .map(e -> ValidationResult.error(e.getMessage())) .collect(Collectors.toList()); status = new BasicBinderValidationStatus<BEAN>(this, binRes, valRes); getValidationStatusHandler().statusChange(status); }
/** Valide un bean d'individu * @param ind * @throws CustomException */ public void validateIndividuBean(Individu ind) throws CustomException{ ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Individu>> constraintViolations = validator.validate(ind); if (constraintViolations!=null && constraintViolations.size() > 0) { String erreur = ""; for (ConstraintViolation<?> violation : constraintViolations) { erreur += (" *** "+ violation.getPropertyPath().toString() + " : " + violation.getMessage()); } throw new CustomException(applicationContext.getMessage("droitprofil.individu.error", null, UI.getCurrent().getLocale())+" : "+erreur); } }
@Test public void testRequestValidationFails() { Set<ConstraintViolation<GrantFactAccessRequest>> violations = getValidator().validate(new GrantFactAccessRequest()); assertEquals(2, violations.size()); assertPropertyInvalid(violations, "fact"); assertPropertyInvalid(violations, "subject"); }
@Test public void emptyHiveMetastoreUris() { replicaCatalog.setHiveMetastoreUris(""); Set<ConstraintViolation<ReplicaCatalog>> violations = validator.validate(replicaCatalog); assertThat(violations.size(), is(1)); }
private static String prepareMessage(ConstraintViolation property) { if (!StringUtils.isEmpty(property.getPropertyPath().toString())) { return property.getPropertyPath() + " : " + property.getMessage(); } return property.getMessage(); }
@Test public void deleteMessageByAge() { Rule rule = new Rule(); rule.setType("delete"); rule.setOlderThan(30); final Set<ConstraintViolation<Rule>> violations = validator.validate(rule); Assert.assertTrue(violations.isEmpty()); }
@Test public void nullDatabasePrefix() { metaStore.setDatabasePrefix(null); Set<ConstraintViolation<FederatedMetaStore>> violations = validator.validate(metaStore); assertThat(violations.size(), is(0)); assertThat("name_", is(metaStore.getDatabasePrefix())); }
/** * 处理validation异常 * * @param req * @param e * @return * @throws Exception */ @ExceptionHandler(value = ConstraintViolationException.class) @ResponseBody public ResultBean<String> validationExceptionHandler(HttpServletRequest req, ConstraintViolationException e) throws Exception { Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); StringBuilder strBuilder = new StringBuilder(); for (ConstraintViolation<?> violation : violations) { strBuilder.append(violation.getMessage() + ","); } LOGGER.error(strBuilder.toString(), e); ResultBean<String> r = new ResultBean(strBuilder.toString()); r.setData(req.getRequestURI()); return r; }
/** * 辅助方法, 转换Set(ConstraintViolation)为List(message). * @param constraintViolations 约束 * @return 异常消息集合 */ @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; }
/** * 辅助方法, 转换Set(ConstraintViolation)为Map(property, message). * @param constraintViolations 约束 * @return 异常消息集合 */ @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; }
/** * validate the input * @param o the object to validate */ public void validate(Object o) throws ClientErrorException { Set<ConstraintViolation<Object>> errors = validator.validate(o); if (errors != null && errors.size() != 0) { ValidationErrorMessages messages = new ValidationErrorMessages(); StringBuilder message = new StringBuilder("Invalid input "); for (ConstraintViolation<Object> constraintViolation : errors) { String field = constraintViolation.getPropertyPath().toString(); messages.addFieldError(field, constraintViolation.getMessage()); message.append("\n" + field + ": " + constraintViolation.getMessage()); } throw new ClientErrorException(message.toString(), messages); } }
private boolean doValidate(Object obj) { final Set<ConstraintViolation<Object>> constraintViolations = VALIDATOR.validate(obj); if (constraintViolations.size() > 0) { for (ConstraintViolation<Object> violation : constraintViolations) { final String msg = String.format(Locale.getDefault(), "%s (%s)", violation.getMessage(), violation.getPropertyPath().toString()); errors.add(new ConfigurationError(msg)); } return false; } return true; }
@Test public void testConstraintViolationException() { final Wine bean = new Wine(); final Set<ConstraintViolation<?>> violations = new LinkedHashSet<>(); final ConstraintHelper helper = new ConstraintHelper(); final ConstraintDescriptor<NotEmpty> notEmptyNameDescriptor = new ConstraintDescriptorImpl<>(helper, (Member) null, getAnnotation("name", NotEmpty.class), ElementType.FIELD); final ConstraintDescriptor<NotEmpty> notEmptyGrapesDescriptor = new ConstraintDescriptorImpl<>(helper, (Member) null, getAnnotation("grapes", NotEmpty.class), ElementType.FIELD); final ConstraintDescriptor<Length> lengthNameDescriptor = new ConstraintDescriptorImpl<>(helper, (Member) null, getAnnotation("name", Length.class), ElementType.FIELD); violations.add(ConstraintViolationImpl.<Wine> forBeanValidation("name-Empty", null, null, "interpolated", Wine.class, bean, new Object(), "value", PathImpl.createPathFromString("name"), notEmptyNameDescriptor, ElementType.FIELD, null)); violations.add(ConstraintViolationImpl.<Wine> forBeanValidation("name-length", null, null, "interpolated", Wine.class, bean, new Object(), "value", PathImpl.createPathFromString("name"), lengthNameDescriptor, ElementType.FIELD, null)); violations.add(ConstraintViolationImpl.<Wine> forBeanValidation("grapes-Empty", null, null, "interpolated", Wine.class, bean, new Object(), "value", PathImpl.createPathFromString("grapes"), notEmptyGrapesDescriptor, ElementType.FIELD, null)); final ConstraintViolationException violationException = Mockito.mock(ConstraintViolationException.class); Mockito.when(violationException.getConstraintViolations()).thenReturn(violations); final ValidationJsonException validationJsonException = new ValidationJsonException(violationException); Assert.assertFalse(validationJsonException.getErrors().isEmpty()); Assert.assertEquals("{name=[{rule=name-Empty}, {rule=name-length, parameters={min=0, max=50}}], grapes=[{rule=grapes-Empty}]}", validationJsonException.getErrors().toString()); }
@Test public void testRequestValidationFailsOnEmpty() { Set<ConstraintViolation<TraverseByObjectIdRequest>> violations = getValidator().validate(new TraverseByObjectIdRequest() .setId(UUID.randomUUID()) .setQuery("") ); assertEquals(1, violations.size()); assertPropertyInvalid(violations, "query"); }
@Test public void testTagTypeKeyValidationIsNotValid() { XmEntity entity = new XmEntity().key("TYPE1.SUBTYPE1-1").typeKey("TYPE1.SUBTYPE1").name("Entity name") .startDate(Instant.now()).updateDate(Instant.now()).stateKey("STATE1") .addTags(new Tag().typeKey("TAG2").name("Tag").startDate(Instant.now())); Set<ConstraintViolation<XmEntity>> constraintViolations = validator.validate(entity); assertEquals(1, constraintViolations.size()); }
public ExceptionPresentation(String className, Set<ConstraintViolation<?>> violations) { this.error = new ErrorPresentation(className, null); this.information = null; this.violations = violations.stream() .map(ConstraintPresentation::new) .collect(Collectors.toSet()); }
@Override public ErrorResponse toErrorResponse(ConstraintViolationException cve) { LOGGER.warn("a ConstraintViolationException occured", cve); List<ErrorData> errors = new ArrayList<>(); for (ConstraintViolation<?> violation : cve.getConstraintViolations()) { ErrorDataBuilder builder = ErrorData.builder(); builder = builder.addMetaField(META_TYPE_KEY, META_TYPE_VALUE); builder = builder.setStatus(String.valueOf(HttpStatus.UNPROCESSABLE_ENTITY_422)); builder = builder.setDetail(violation.getMessage()); builder = builder.setCode(toCode(violation)); if (violation.getMessageTemplate() != null) { builder = builder.addMetaField(META_MESSAGE_TEMPLATE, violation.getMessageTemplate()); } // for now we just provide root resource validation information // depending on bulk update spec, we might also provide the leaf information in the future if (violation.getRootBean() != null) { ResourceRef resourceRef = resolvePath(violation); builder = builder.addMetaField(META_RESOURCE_ID, resourceRef.getRootResourceId()); builder = builder.addMetaField(META_RESOURCE_TYPE, resourceRef.getRootResourceType()); builder = builder.setSourcePointer(resourceRef.getRootSourcePointer()); } ErrorData error = builder.build(); errors.add(error); } return ErrorResponse.builder().setStatus(HttpStatus.UNPROCESSABLE_ENTITY_422).setErrorData(errors).build(); }
@Test public void nullName() { sourceCatalog.setName(null); Set<ConstraintViolation<SourceCatalog>> violations = validator.validate(sourceCatalog); assertThat(violations.size(), is(1)); }
@Test public void shouldValidateExpensiveConstraintIfDefaultValid() throws Exception { // given ExpensiveValidationModel givenModel = new ExpensiveValidationModel("", null); // when Set<ConstraintViolation<ExpensiveValidationModel>> actual = validator.validate(givenModel, ExpensiveSequence.class); // then then(actual).extracting(cv -> cv.getPropertyPath().toString()) .containsExactly("expensiveString"); }
public <P extends ParaObject> Map<String, String> validate(P pobj) { HashMap<String, String> error = new HashMap<String, String>(); if (pobj != null) { Set<ConstraintViolation<P>> errors = ValidationUtils.getValidator().validate(pobj); for (ConstraintViolation<P> err : errors) { error.put(err.getPropertyPath().toString(), err.getMessage()); } } return error; }
@Test public void failsWhenFailingConstraint() { Example example = new Example(); example.three = Option.of(2); Set<ConstraintViolation<Example>> violations = validator.validate(example); assertThat(violations).hasSize(1); }
@Test public void manufacturerIsNull() { Car car = new Car( null, "DD-AB-123", 4 ); Set<ConstraintViolation<Car>> constraintViolations = validator.validate( car ); assertEquals( 1, constraintViolations.size() ); assertEquals( "must not be null", constraintViolations.iterator().next().getMessage() ); }
@Test public void shouldValidateForNameUniqueness() { UniqnenessValidator.VALID.set(true); final Set<ConstraintViolation<Integration>> violations = validator.validate(new Integration.Builder().build(), UniquenessRequired.class); assertThat(violations).isEmpty(); }
@Test public void testType() { UpperCaseBeanType upperCaseBeanType = new UpperCaseBeanType(); Set<ConstraintViolation<UpperCaseBeanType>> violations = validator.validate(upperCaseBeanType); Assert.assertEquals(0, violations.size()); }
@Test public void notBlankFailsWhenPresentButBlank() { Example example = new Example(); example.notBlank = Option.of("\t"); Set<ConstraintViolation<Example>> violations = validator.validate(example); assertThat(violations).hasSize(1); }
/** * serialize a violation from Hibernate validation * * @param error * validation error * @return serialized error */ private Map<String, Serializable> serializeHibernateValidationError(final ConstraintViolation<?> violation) { final Map<String, Serializable> error = new HashMap<>(); final Map<String, Serializable> parameters = new HashMap<>(); for (final Map.Entry<String, Object> entry : violation.getConstraintDescriptor().getAttributes().entrySet()) { // ignore some parameters if (!IGNORED_PARAMETERS.contains(entry.getKey())) { parameters.put(entry.getKey(), (Serializable) entry.getValue()); error.put("parameters", (Serializable) parameters); } } error.put("rule", ClassUtils.getShortClassName( StringUtils.removeEnd(StringUtils.removeEnd(StringUtils.removeStart(violation.getMessageTemplate(), "{"), "}"), ".message"))); return error; }