/** * @param ex {@link ConstraintViolationException} * @return Returns an object with a list of incorrect parameters. */ @ExceptionHandler(ConstraintViolationException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public ValidationErrorDTO processValidationError(final ConstraintViolationException ex) { final ValidationErrorDTO validationErrorDTO = new ValidationErrorDTO(); final Set<ConstraintViolation<?>> set = ex.getConstraintViolations(); for (Iterator<ConstraintViolation<?>> iterator = set.iterator();iterator.hasNext(); ) { ConstraintViolation<?> next = iterator.next(); validationErrorDTO.getFieldErrors() .add(new ErrorFieldDTO(((PathImpl)next.getPropertyPath()).getLeafNode().getName(), next.getMessage())); } return validationErrorDTO; }
/** * Validate a bean of given declared class. * * @param bean * the bean to validate. * @param parameter * the runtime annotations of this parameter. * @param validationErrors * the errors list to fill. */ private void validate(final Object bean, final Method method, final Parameter parameter, final int index, final Set<ConstraintViolation<?>> validationErrors) { if (bean == null) { // Parameter is null, is it manually checked of managed by CXF for // multipart? // All non-body parameters are required by default final PathImpl propertyPath = PathImpl.createPathFromString(method.getName()); propertyPath.addParameterNode(parameter.getName(), index); validationErrors.add(ConstraintViolationImpl.forParameterValidation(NotNull.class.getName(), null, null, "interpolated", null, null, null, null, propertyPath, NOT_NULL_DESCRIPTOR, null, null, null)); return; } final Class<?> clazz = bean.getClass(); if (Collection.class.isAssignableFrom(clazz)) { validate((Collection<?>) bean, validationErrors); } else if (clazz.isArray()) { validate((Object[]) bean, validationErrors); } else { validateSimpleBean(bean, validationErrors); } }
@Test public void testConstraintViolationExceptionParameter() { 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); PathImpl path = PathImpl.createPathFromString("name"); violations.add(ConstraintViolationImpl.<Wine> forParameterValidation("name-Empty", null, null, "interpolated", Wine.class, bean, new Object(), "value", path, notEmptyNameDescriptor, ElementType.PARAMETER, null, null)); path.addParameterNode("parameter1", 0); 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("{parameter1=[{rule=name-Empty}]}", validationJsonException.getErrors().toString()); }
/** * Return the property path from the given validation error. */ private String getPropertyPath(final ConstraintViolation<?> error) { if (((PathImpl) error.getPropertyPath()).getLeafNode().getKind() == ElementKind.PARAMETER) { // JSR-349 - Parameter, drop parent context return ((PathImpl) error.getPropertyPath()).getLeafNode().getName(); } // JSR-303 - Bean violation return error.getPropertyPath().toString(); }
@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()); }
/** * Utility method for adding error of ConstraintViolation. Usually when a @Validated validation fails. * * @param cv the ConstraintViolation */ private void addValidationError(ConstraintViolation<?> cv) { this.addValidationError( cv.getRootBeanClass().getSimpleName(), ((PathImpl) cv.getPropertyPath()).getLeafNode().asString(), cv.getInvalidValue(), cv.getMessage()); }
/** * constructor. * * @param parent ConstraintViolationBuilderImpl which is parent * @param messageTemplate message template * @param path path of the element */ public NodeBuilderCustomizableContextImpl(final ConstraintViolationBuilderImpl parent, final String messageTemplate, final PathImpl path) { super(); this.parent = parent; this.messageTemplate = messageTemplate; this.path = path; }
/** * constructor. * * @param parent ConstraintViolationBuilderImpl which is parent * @param messageTemplate message template * @param path path of the element */ public NodeContextBuilderImpl(final PathImpl path, final String messageTemplate, final ConstraintViolationBuilderImpl parent) { super(); this.path = path; this.messageTemplate = messageTemplate; this.parent = parent; }
/** * constructor. * * @param path path of the element * @param descriptor constraint descriptor */ public ConstraintValidatorContextImpl(final PathImpl path, final ConstraintDescriptor<A> descriptor) { super(); this.basePath = path; this.descriptor = descriptor; }
/** * Append a node named name to the path.. * * @return the new GwtValidationContext. */ public GwtValidationContext<T> append(final String name) { final GwtValidationContext<T> temp = new GwtValidationContext<>(this.rootBeanClass, this.rootBean, this.beanDescriptor, this.messageInterpolator, this.traversableResolver, this.validator, this.validatedObjects); temp.path = PathImpl.createCopy(this.path); temp.path.addPropertyNode(name); return temp; }
/** * Append an indexed node to the path. * * @return the new GwtValidationContext. */ public GwtValidationContext<T> appendIndex(final String name, final int index) { final GwtValidationContext<T> temp = new GwtValidationContext<>(this.rootBeanClass, this.rootBean, this.beanDescriptor, this.messageInterpolator, this.traversableResolver, this.validator, this.validatedObjects); temp.path = PathImpl.createCopy(this.path); temp.path.addParameterNode(name, index); temp.path.makeLeafNodeIterable(); temp.path.makeLeafNodeIterableAndSetIndex(index); return temp; }
/** * Append an iterable node to the path. * * @return the new GwtValidationContext. */ public GwtValidationContext<T> appendIterable(final String name) { final GwtValidationContext<T> temp = new GwtValidationContext<>(this.rootBeanClass, this.rootBean, this.beanDescriptor, this.messageInterpolator, this.traversableResolver, this.validator, this.validatedObjects); temp.path = PathImpl.createCopy(this.path); temp.path.addPropertyNode(name); temp.path.makeLeafNodeIterable(); return temp; }
/** * Append a keyed node to the path. * * @return the new GwtValidationContext. */ public GwtValidationContext<T> appendKey(final String name, final Object key) { final GwtValidationContext<T> temp = new GwtValidationContext<>(this.rootBeanClass, this.rootBean, this.beanDescriptor, this.messageInterpolator, this.traversableResolver, this.validator, this.validatedObjects); temp.path = PathImpl.createCopy(this.path); temp.path.addPropertyNode(name); NodeImpl.makeIterableAndSetMapKey(temp.path.getLeafNode(), key); return temp; }
/** * constructor. */ public ConstraintViolationCreationContext(final String message, final PathImpl property, final Map<String, Object> messageParameters, final Map<String, Object> expressionVariables, final Object dynamicPayload) { this.message = message; this.propertyPath = property; this.messageParameters = toImmutableMap(messageParameters); this.expressionVariables = toImmutableMap(expressionVariables); this.dynamicPayload = dynamicPayload; }
@Override protected void compose(final ClassSourceFileComposerFactory composerFactory) { this.addImports(composerFactory, Annotation.class, ConstraintViolation.class, GWT.class, ValidationGroupsMetadata.class, Group.class, GroupChain.class, PathImpl.class, Node.class, GroupChainGenerator.class, GwtBeanDescriptor.class, BeanMetadata.class, GwtValidationContext.class, ArrayList.class, HashSet.class, IllegalArgumentException.class, Set.class, Collection.class, Iterator.class, List.class, ValidationException.class); composerFactory.setSuperclass(AbstractGwtSpecificValidator.class.getCanonicalName() + "<" + this.beanType.getQualifiedSourceName() + ">"); composerFactory.addImplementedInterface(this.validatorType.getName()); }
ConstraintViolationBuilder getConstraintViolationBuilder() { return new ConstraintValidatorContextImpl( Collections.emptyList(), null, PathImpl.createRootPath(), new DummyConstraintDescriptor() ).buildConstraintViolationWithTemplate("dummytemplate"); }
@Before public void setUp() { underTest = new UpdateStackRequestValidator(); constraintValidatorContext = new ConstraintValidatorContextImpl( new ArrayList<>(), null, PathImpl.createRootPath(), new DummyConstraintDescriptor() ); }
@Override public Path getPropertyPath() { return PathImpl.createPathFromString(propertyPath); }
@Before public void setup() { validator = new PointLocationValidator(); context = new ConstraintValidatorContextImpl(null, null, PathImpl.createPathFromString("WOW"), null); }
/** * Utility method for adding error of ConstraintViolation. Usually when a @Validated * validation fails. * @param cv the ConstraintViolation */ private void addValidationError(ConstraintViolation<?> cv) { this.addValidationError(cv.getRootBeanClass().getSimpleName(), ((PathImpl) cv.getPropertyPath()).getLeafNode().asString(), cv.getInvalidValue(), cv.getMessage()); }
@Override public Path getPropertyPath() { return PathImpl.createPathFromString(this.propertyPath); }
@Override public ConstraintViolationBuilder buildConstraintViolationWithTemplate( final String messageTemplate) { return new ConstraintViolationBuilderImpl(new ConstraintValidatorContextImpl<A, T>( PathImpl.createCopy(this.basePath), this.descriptor), messageTemplate); }
public PathImpl getPath() { return this.path; }
public ConstraintViolationCreationContext(final String message, final PathImpl property) { this(message, property, Collections.<String, Object>emptyMap(), Collections.<String, Object>emptyMap(), null); }
public final PathImpl getPath() { return this.propertyPath; }
public static void deserialize(final SerializationStreamReader streamReader, final PathImpl instance) throws SerializationException { // no fields }
public static void serialize(final SerializationStreamWriter streamWriter, final PathImpl instance) throws SerializationException { streamWriter.writeString(instance.toString()); }
@Override public void deserializeInstance(final SerializationStreamReader streamReader, final PathImpl instance) throws SerializationException { deserialize(streamReader, instance); }
@Override public PathImpl instantiateInstance(final SerializationStreamReader streamReader) throws SerializationException { return instantiate(streamReader); }
@Override public void serializeInstance(final SerializationStreamWriter streamWriter, final PathImpl instance) throws SerializationException { serialize(streamWriter, instance); }
public ConstraintValidatorContextImpl(final PathImpl ppath, final ConstraintDescriptor<A> pdescriptor) { super(ppath, pdescriptor); }
/** * BeanValidationの検証結果をSheet用のエラーに変換する * @param violations BeanValidationの検証結果 * @param errors シートのエラー */ protected void processConstraintViolation(final Set<ConstraintViolation<Object>> violations, final SheetBindingErrors errors) { for(ConstraintViolation<Object> violation : violations) { final String fieldName = violation.getPropertyPath().toString(); final FieldError fieldError = errors.getFirstFieldError(fieldName); if(fieldError != null && fieldError.isTypeBindFailure()) { // 型変換エラーが既存のエラーにある場合は、処理をスキップする。 continue; } final ConstraintDescriptor<?> cd = violation.getConstraintDescriptor(); final String errorCode = cd.getAnnotation().annotationType().getSimpleName(); final Map<String, Object> errorVars = createVariableForConstraint(cd); final String nestedPath = errors.buildFieldPath(fieldName); if(Utils.isEmpty(nestedPath)) { // オブジェクトエラーの場合 errors.rejectSheet(errorCode, errorVars, violation.getMessage()); } else { // フィールドエラーの場合 // 親のオブジェクトから、セルの座標を取得する final Object parentObj = violation.getLeafBean(); final Path path = violation.getPropertyPath(); Point cellAddress = null; String label = null; if(path instanceof PathImpl) { final PathImpl pathImpl = (PathImpl) path; cellAddress = Utils.getPosition(parentObj, pathImpl.getLeafNode().getName()); label = Utils.getLabel(parentObj, pathImpl.getLeafNode().getName()); } // 実際の値を取得する final Object fieldValue = violation.getInvalidValue(); if(!errorVars.containsKey("validatedValue")) { errorVars.put("validatedValue", fieldValue); } Class<?> fieldType = fieldValue != null ? fieldValue.getClass() : null; errors.addError(FieldErrorBuilder.create() .objectName(errors.getObjectName()).fieldPath(errors.buildFieldPath(fieldName)) .codes(errors.generateMessageCodes(errorCode, fieldName, fieldType), errorVars) .sheetName(errors.getSheetName()).cellAddress(cellAddress) .label(label) .defaultMessage(violation.getMessage()) .fieldValue(fieldValue) .build()); } } }
/** * constructor. * * @param parent ConstraintViolationBuilderImpl which is parent * @param messageTemplate message template * @param path path of the element */ public NodeBuilderDefinedContextImpl(final ConstraintViolationBuilderImpl parent, final String messageTemplate, final PathImpl path) { this.parent = parent; this.messageTemplate = messageTemplate; this.path = path; }
/** * instantiate a path implementation. * * @param streamReader serialization stream reader * @return path implementation * @throws SerializationException when deserialization fails */ public static PathImpl instantiate(final SerializationStreamReader streamReader) throws SerializationException { final String propertyPath = streamReader.readString(); return PathImpl.createPathFromString(propertyPath); }
/** * create constraint validator context. * * @param descriptor constraint descriptor * @return constraint validator context implementation */ public <A extends Annotation, V> ConstraintValidatorContextImpl<A, V> // createConstraintValidatorContext(final ConstraintDescriptor<A> descriptor) { return new ConstraintValidatorContextImpl<>(PathImpl.createCopy(this.path), descriptor); }