Java Code Examples for javax.validation.Path

The following are top voted examples for showing how to use javax.validation.Path. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: lams   File: HibernateTraversableResolver.java   View source code 6 votes vote down vote up
private String getStringBasedPath(Path.Node traversableProperty, Path pathToTraversableObject) {
	StringBuilder path = new StringBuilder( );
	for ( Path.Node node : pathToTraversableObject ) {
		if (node.getName() != null) {
			path.append( node.getName() ).append( "." );
		}
	}
	if ( traversableProperty.getName() == null ) {
		throw new AssertionFailure(
				"TraversableResolver being passed a traversableProperty with null name. pathToTraversableObject: "
						+ path.toString() );
	}
	path.append( traversableProperty.getName() );

	return path.toString();
}
 
Example 2
Project: backstopper   File: ClientDataValidationErrorHandlerListenerTest.java   View source code 6 votes vote down vote up
private ConstraintViolation<Object> setupConstraintViolation(Class offendingObjectClass, String path, Class<? extends Annotation> annotationClass, String message) {
    ConstraintViolation<Object> mockConstraintViolation = mock(ConstraintViolation.class);

    Path mockPath = mock(Path.class);
    doReturn(path).when(mockPath).toString();

    Annotation mockAnnotation = mock(Annotation.class);
    doReturn(annotationClass).when(mockAnnotation).annotationType();

    ConstraintDescriptor<?> mockConstraintDescriptor = mock(ConstraintDescriptor.class);
    doReturn(mockAnnotation).when(mockConstraintDescriptor).getAnnotation();

    when(mockConstraintViolation.getPropertyPath()).thenReturn(mockPath);
    doReturn(mockConstraintDescriptor).when(mockConstraintViolation).getConstraintDescriptor();
    when(mockConstraintViolation.getMessage()).thenReturn(message);

    doReturn(offendingObjectClass).when(mockConstraintViolation).getRootBeanClass();

    return mockConstraintViolation;
}
 
Example 3
Project: backstopper   File: ServersideValidationErrorHandlerListenerTest.java   View source code 6 votes vote down vote up
private ConstraintViolation<Object> setupConstraintViolation(String path, Class<? extends Annotation> annotationClass, String message) {
    ConstraintViolation<Object> mockConstraintViolation = mock(ConstraintViolation.class);

    Path mockPath = mock(Path.class);
    doReturn(path).when(mockPath).toString();

    Annotation mockAnnotation = mock(Annotation.class);
    doReturn(annotationClass).when(mockAnnotation).annotationType();

    ConstraintDescriptor<?> mockConstraintDescriptor = mock(ConstraintDescriptor.class);
    doReturn(mockAnnotation).when(mockConstraintDescriptor).getAnnotation();

    when(mockConstraintViolation.getPropertyPath()).thenReturn(mockPath);
    doReturn(mockConstraintDescriptor).when(mockConstraintViolation).getConstraintDescriptor();
    when(mockConstraintViolation.getMessage()).thenReturn(message);

    return mockConstraintViolation;
}
 
Example 4
Project: continuous-delivery-demo   File: GlobalControllerExceptionHandler.java   View source code 6 votes vote down vote up
private List<ValidationMessage> getValidationErrorResponse(ConstraintViolationException constraintViolationException) {
    final List<ValidationMessage> validationErrors = new ArrayList<>();
    LOG.error("Got validation errors", constraintViolationException);
    for (ConstraintViolation<?> violationSet : constraintViolationException.getConstraintViolations()) {
        List<String> propertyList = new ArrayList<>();
        Iterator<Path.Node> propertyIterator = violationSet
                .getPropertyPath().iterator();
        while (propertyIterator.hasNext()) {
            propertyList.add(propertyIterator.next().getName());
        }
        // add violations errors in response
        validationErrors.add(ValidationMessage.builder()
                .entity(violationSet.getRootBeanClass().getName())
                        // remove { and }
                .messageTemplate(violationSet.getMessageTemplate().replaceAll("^[{]|[}]$", ""))
                .propertyList(propertyList).build());
    }
    return validationErrors;
}
 
Example 5
Project: cuba   File: EditorWindowDelegate.java   View source code 6 votes vote down vote up
public void validateAdditionalRules(ValidationErrors errors) {
    // all previous validations return no errors
    if (crossFieldValidate && errors.isEmpty()) {
        BeanValidation beanValidation = AppBeans.get(BeanValidation.NAME);

        Validator validator = beanValidation.getValidator();
        Set<ConstraintViolation<Entity>> violations = validator.validate(getItem(), UiCrossFieldChecks.class);

        violations.stream()
                .filter(violation -> {
                    Path propertyPath = violation.getPropertyPath();

                    Path.Node lastNode = Iterables.getLast(propertyPath);
                    return lastNode.getKind() == ElementKind.BEAN;
                })
                .forEach(violation -> errors.add(violation.getMessage()));
    }
}
 
Example 6
Project: angular-spring-boot-sample   File: GlobalControllerExceptionHandler.java   View source code 6 votes vote down vote up
private List<ValidationMessage> getValidationErrorResponse(ConstraintViolationException constraintViolationException) {
    final List<ValidationMessage> validationErrors = new ArrayList<>();
    LOG.error("Got validation errors", constraintViolationException);
    for (ConstraintViolation<?> violationSet : constraintViolationException.getConstraintViolations()) {
        List<String> propertyList = new ArrayList<>();
        Iterator<Path.Node> propertyIterator = violationSet
                .getPropertyPath().iterator();
        while (propertyIterator.hasNext()) {
            propertyList.add(propertyIterator.next().getName());
        }
        // add violations errors in response
        validationErrors.add(ValidationMessage.builder()
                .entity(violationSet.getRootBeanClass().getName())
                        // remove { and }
                .messageTemplate(violationSet.getMessageTemplate().replaceAll("^[{]|[}]$", ""))
                .propertyList(propertyList).build());
    }
    return validationErrors;
}
 
Example 7
Project: packagedrone   File: JavaValidator.java   View source code 6 votes vote down vote up
private String makePath ( final ConstraintViolation<Object> entry )
{
    final StringBuilder sb = new StringBuilder ();

    final Path p = entry.getPropertyPath ();
    for ( final Node n : p )
    {
        if ( sb.length () > 0 )
        {
            sb.append ( '.' );
        }
        sb.append ( n.getName () );
    }

    return sb.toString ();
}
 
Example 8
Project: hql-builder   File: JavaxValidationConverter.java   View source code 6 votes vote down vote up
/**
 * @see org.tools.hqlbuilder.common.interfaces.ValidationExceptionConverter#convert(java.lang.Exception)
 */
@Override
public ValidationException convert(Exception e) {
    javax.validation.ConstraintViolationException ex = (ConstraintViolationException) e;
    List<org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue> ivs = new ArrayList<org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue>();
    for (javax.validation.ConstraintViolation<?> iv : ex.getConstraintViolations()) {
        Object bean = iv.getLeafBean();
        Class<?> beanClass = iv.getRootBeanClass();
        String message = iv.getMessage();
        Path path = iv.getPropertyPath();
        Iterator<javax.validation.Path.Node> it = path.iterator();
        Path.Node node = it.next();
        while (it.hasNext()) {
            node = it.next();
        }
        String propertyName = String.valueOf(node);
        String propertyPath = String.valueOf(path);
        Object rootBean = iv.getRootBean();
        Object value = iv.getInvalidValue();
        org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue tmp = new org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue(
                bean, beanClass, message, propertyName, propertyPath, rootBean, value);
        ivs.add(tmp);
    }
    return new ValidationException(ex.getMessage(), ivs);
}
 
Example 9
Project: hql-builder   File: JavaxValidationConverter.java   View source code 6 votes vote down vote up
/**
 * @see org.tools.hqlbuilder.common.interfaces.ValidationExceptionConverter#convert(java.lang.Exception)
 */
@Override
public ValidationException convert(Exception e) {
    javax.validation.ConstraintViolationException ex = (ConstraintViolationException) e;
    List<org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue> ivs = new ArrayList<org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue>();
    for (javax.validation.ConstraintViolation<?> iv : ex.getConstraintViolations()) {
        Object bean = iv.getLeafBean();
        Class<?> beanClass = iv.getRootBeanClass();
        String message = iv.getMessage();
        Path path = iv.getPropertyPath();
        Iterator<javax.validation.Path.Node> it = path.iterator();
        Path.Node node = it.next();
        while (it.hasNext()) {
            node = it.next();
        }
        String propertyName = String.valueOf(node);
        String propertyPath = String.valueOf(path);
        Object rootBean = iv.getRootBean();
        Object value = iv.getInvalidValue();
        org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue tmp = new org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue(
                bean, beanClass, message, propertyName, propertyPath, rootBean, value);
        ivs.add(tmp);
    }
    return new ValidationException(ex.getMessage(), ivs);
}
 
Example 10
Project: hql-builder   File: JavaxValidationConverter.java   View source code 6 votes vote down vote up
/**
 * @see org.tools.hqlbuilder.common.interfaces.ValidationExceptionConverter#convert(java.lang.Exception)
 */
@Override
public ValidationException convert(Exception e) {
    javax.validation.ConstraintViolationException ex = (ConstraintViolationException) e;
    List<org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue> ivs = new ArrayList<org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue>();
    for (javax.validation.ConstraintViolation<?> iv : ex.getConstraintViolations()) {
        Object bean = iv.getLeafBean();
        Class<?> beanClass = iv.getRootBeanClass();
        String message = iv.getMessage();
        Path path = iv.getPropertyPath();
        Iterator<javax.validation.Path.Node> it = path.iterator();
        Path.Node node = it.next();
        while (it.hasNext()) {
            node = it.next();
        }
        String propertyName = String.valueOf(node);
        String propertyPath = String.valueOf(path);
        Object rootBean = iv.getRootBean();
        Object value = iv.getInvalidValue();
        org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue tmp = new org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue(
                bean, beanClass, message, propertyName, propertyPath, rootBean, value);
        ivs.add(tmp);
    }
    return new ValidationException(ex.getMessage(), ivs);
}
 
Example 11
Project: hql-builder   File: JavaxValidationConverter.java   View source code 6 votes vote down vote up
/**
 * @see org.tools.hqlbuilder.common.interfaces.ValidationExceptionConverter#convert(java.lang.Exception)
 */
@Override
public ValidationException convert(Exception e) {
    javax.validation.ConstraintViolationException ex = (ConstraintViolationException) e;
    List<org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue> ivs = new ArrayList<org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue>();
    for (javax.validation.ConstraintViolation<?> iv : ex.getConstraintViolations()) {
        Object bean = iv.getLeafBean();
        Class<?> beanClass = iv.getRootBeanClass();
        String message = iv.getMessage();
        Path path = iv.getPropertyPath();
        Iterator<javax.validation.Path.Node> it = path.iterator();
        Path.Node node = it.next();
        while (it.hasNext()) {
            node = it.next();
        }
        String propertyName = String.valueOf(node);
        String propertyPath = String.valueOf(path);
        Object rootBean = iv.getRootBean();
        Object value = iv.getInvalidValue();
        org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue tmp = new org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue(
                bean, beanClass, message, propertyName, propertyPath, rootBean, value);
        ivs.add(tmp);
    }
    return new ValidationException(ex.getMessage(), ivs);
}
 
Example 12
Project: hql-builder   File: JavaxValidationConverter.java   View source code 6 votes vote down vote up
/**
 * @see org.tools.hqlbuilder.common.interfaces.ValidationExceptionConverter#convert(java.lang.Exception)
 */
@Override
public ValidationException convert(Exception e) {
    javax.validation.ConstraintViolationException ex = (ConstraintViolationException) e;
    List<org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue> ivs = new ArrayList<org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue>();
    for (javax.validation.ConstraintViolation<?> iv : ex.getConstraintViolations()) {
        Object bean = iv.getLeafBean();
        Class<?> beanClass = iv.getRootBeanClass();
        String message = iv.getMessage();
        Path path = iv.getPropertyPath();
        Iterator<javax.validation.Path.Node> it = path.iterator();
        Path.Node node = it.next();
        while (it.hasNext()) {
            node = it.next();
        }
        String propertyName = String.valueOf(node);
        String propertyPath = String.valueOf(path);
        Object rootBean = iv.getRootBean();
        Object value = iv.getInvalidValue();
        org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue tmp = new org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue(
                bean, beanClass, message, propertyName, propertyPath, rootBean, value);
        ivs.add(tmp);
    }
    return new ValidationException(ex.getMessage(), ivs);
}
 
Example 13
Project: hql-builder   File: JavaxValidationConverter.java   View source code 6 votes vote down vote up
/**
 * @see org.tools.hqlbuilder.common.interfaces.ValidationExceptionConverter#convert(java.lang.Exception)
 */
@Override
public ValidationException convert(Exception e) {
    javax.validation.ConstraintViolationException ex = (ConstraintViolationException) e;
    List<org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue> ivs = new ArrayList<>();
    for (javax.validation.ConstraintViolation<?> iv : ex.getConstraintViolations()) {
        Object bean = iv.getLeafBean();
        Class<?> beanClass = iv.getRootBeanClass();
        String message = iv.getMessage();
        Path path = iv.getPropertyPath();
        Iterator<javax.validation.Path.Node> it = path.iterator();
        Path.Node node = it.next();
        while (it.hasNext()) {
            node = it.next();
        }
        String propertyName = String.valueOf(node);
        String propertyPath = String.valueOf(path);
        Object rootBean = iv.getRootBean();
        Object value = iv.getInvalidValue();
        org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue tmp = new org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue(
                bean, beanClass, message, propertyName, propertyPath, rootBean, value);
        ivs.add(tmp);
    }
    return new ValidationException(ex.getMessage(), ivs);
}
 
Example 14
Project: hql-builder   File: JavaxValidationConverter.java   View source code 6 votes vote down vote up
/**
 * @see org.tools.hqlbuilder.common.interfaces.ValidationExceptionConverter#convert(java.lang.Exception)
 */
@Override
public ValidationException convert(Exception e) {
    javax.validation.ConstraintViolationException ex = (ConstraintViolationException) e;
    List<org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue> ivs = new ArrayList<org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue>();
    for (javax.validation.ConstraintViolation<?> iv : ex.getConstraintViolations()) {
        Object bean = iv.getLeafBean();
        Class<?> beanClass = iv.getRootBeanClass();
        String message = iv.getMessage();
        Path path = iv.getPropertyPath();
        Iterator<javax.validation.Path.Node> it = path.iterator();
        Path.Node node = it.next();
        while (it.hasNext()) {
            node = it.next();
        }
        String propertyName = String.valueOf(node);
        String propertyPath = String.valueOf(path);
        Object rootBean = iv.getRootBean();
        Object value = iv.getInvalidValue();
        org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue tmp = new org.tools.hqlbuilder.common.exceptions.ValidationException.InvalidValue(
                bean, beanClass, message, propertyName, propertyPath, rootBean, value);
        ivs.add(tmp);
    }
    return new ValidationException(ex.getMessage(), ivs);
}
 
Example 15
Project: ocelot   File: ConstraintServicesTest.java   View source code 6 votes vote down vote up
/**
 * Test of extractViolationInfoFromNode method, of class ConstraintServices.
 */
@Test
public void testExtractViolationInfoFromNode() {
	System.out.println("extractViolationInfoFromNode");
	Path.Node node = mock(Path.Node.class);
	when(node.getKind()).thenReturn(ElementKind.METHOD).thenReturn(ElementKind.PARAMETER).thenReturn(ElementKind.PROPERTY);
	when(node.getName()).thenReturn("arg0").thenReturn("prop");
	doReturn(5).when(instance).getIndexFromArgname(anyString());

	ConstraintViolation cv = new ConstraintViolation();
	instance.extractViolationInfoFromNode(node, cv);
	assertThat(cv.getMessage()).isNull();
	assertThat(cv.getIndex()).isEqualTo(0);
	assertThat(cv.getProp()).isNull();
	cv = new ConstraintViolation();
	instance.extractViolationInfoFromNode(node, cv);
	assertThat(cv.getMessage()).isNull();
	assertThat(cv.getIndex()).isEqualTo(5);
	assertThat(cv.getProp()).isNull();
	cv = new ConstraintViolation();
	instance.extractViolationInfoFromNode(node, cv);
	assertThat(cv.getMessage()).isNull();
	assertThat(cv.getIndex()).isEqualTo(0);
	assertThat(cv.getProp()).isEqualTo("prop");
}
 
Example 16
Project: gwt-bean-validators   File: ConstraintViolationImpl_CustomFieldSerializer.java   View source code 6 votes vote down vote up
/**
 * instantiate a ConstraintViolationImpl.
 *
 * @param streamReader serialized stream reader to take data from
 * @return ConstraintViolationImpl
 * @throws SerializationException if deserialization fails
 */
public static ConstraintViolationImpl<Object> instantiate(
    final SerializationStreamReader streamReader) throws SerializationException {

  final String messageTemplate = null;
  final String interpolatedMessage = streamReader.readString();
  final Class<Object> rootBeanClass = null;
  final Object rootBean = null;
  final Object leafBeanInstance = null;
  final Object value = null;
  final Path propertyPath = (Path) streamReader.readObject();
  final ConstraintDescriptor<?> constraintDescriptor = null;
  final ElementType elementType = null;
  final Map<String, Object> messageParameters = new HashMap<>();
  final Map<String, Object> expressionVariables = new HashMap<>();
  return (ConstraintViolationImpl<Object>) ConstraintViolationImpl.forBeanValidation(
      messageTemplate, messageParameters, expressionVariables, interpolatedMessage, rootBeanClass,
      rootBean, leafBeanInstance, value, propertyPath, constraintDescriptor, elementType, null);
}
 
Example 17
Project: gwt-bean-validators   File: ConstraintViolationImpl.java   View source code 6 votes vote down vote up
private ConstraintViolationImpl(final String messageTemplate,
    final Map<String, Object> messageParameters, final Map<String, Object> expressionVariables,
    final String interpolatedMessage, final Class<T> rootBeanClass, final T rootBean,
    final Object leafBeanInstance, final Object value, final Path propertyPath,
    final ConstraintDescriptor<?> constraintDescriptor, final ElementType elementType,
    final Object[] executableParameters, final Object executableReturnValue,
    final Object dynamicPayload) {
  this.messageTemplate = messageTemplate;
  this.messageParameters = messageParameters;
  this.expressionVariables = expressionVariables;
  this.interpolatedMessage = interpolatedMessage;
  this.rootBean = rootBean;
  this.value = value;
  this.propertyPath = propertyPath;
  this.leafBeanInstance = leafBeanInstance;
  this.constraintDescriptor = constraintDescriptor;
  this.rootBeanClass = rootBeanClass;
  this.elementType = elementType;
  this.executableParameters = executableParameters;
  this.executableReturnValue = executableReturnValue;
  this.dynamicPayload = dynamicPayload;
  // pre-calculate hash code, the class is immutable and hashCode is needed often
  this.hashCodeValue = this.createHashCode();
}
 
Example 18
Project: gwt-bean-validators   File: NodeImpl.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T extends Path.Node> T as(final Class<T> nodeType) throws ClassCastException { // NOPMD
  if (this.kind == ElementKind.BEAN && nodeType == BeanNode.class
      || this.kind == ElementKind.CONSTRUCTOR && nodeType == ConstructorNode.class
      || this.kind == ElementKind.CROSS_PARAMETER && nodeType == CrossParameterNode.class
      || this.kind == ElementKind.METHOD && nodeType == MethodNode.class
      || this.kind == ElementKind.PARAMETER && nodeType == ParameterNode.class
      || this.kind == ElementKind.PROPERTY && (nodeType == PropertyNode.class
          || nodeType == org.hibernate.validator.path.PropertyNode.class)
      || this.kind == ElementKind.RETURN_VALUE && nodeType == ReturnValueNode.class
      || this.kind == ElementKind.CONTAINER_ELEMENT && (nodeType == ContainerElementNode.class
          || nodeType == org.hibernate.validator.path.ContainerElementNode.class)) {
    return (T) this;
  }

  throw LOG.getUnableToNarrowNodeTypeException(this.getClass(), this.kind, nodeType);
}
 
Example 19
Project: Introspect-Framework   File: ConstrainViolationFactory.java   View source code 6 votes vote down vote up
private static ConstraintViolation<Object> createConstraintViolations(
		LanguageProvider languageProvider, ClassInfo classInfo,
		Object domainObject, ValidationViolation validationViolation) {
	String messageTemplateKey = validationViolation.getMessageTemplateKey();
	String messageTemplateDefault = validationViolation
			.getMessageTemplateInEnglish();
	String messageTemplate = languageProvider.getText(messageTemplateKey,
			messageTemplateDefault);
	Object invalidValue = validationViolation.getInvalidValue();
	String message = String.format(messageTemplate, invalidValue);
	Path path = PathImpl.create(classInfo.getSimpleName());
	@SuppressWarnings("unchecked")
	Class<Object> rootBeanClass = (Class<Object>) domainObject.getClass();
	ConstraintDescriptor<?> constraintDescriptor = null;
	ElementType elementType = null;
	ConstraintViolationImpl<Object> constraintViolation = new ConstraintViolationImpl<Object>(
			messageTemplate, message, domainObject, domainObject, path,
			domainObject, constraintDescriptor, rootBeanClass, elementType);
	return constraintViolation;
}
 
Example 20
Project: budgetapp   File: ConstraintViolationExceptionMapper.java   View source code 6 votes vote down vote up
@Override
public Response toResponse(ConstraintViolationException exception) {

    LOGGER.debug("Validation constraint violation {}", exception.getConstraintViolations());

    ValidationMessage validationMessage = new ValidationMessage();
    Set<ConstraintViolation<?>> violations = exception.getConstraintViolations();
    Multimap<String, String> errors = ArrayListMultimap.create();
    for (ConstraintViolation<?> cv : violations) {
        String name = StreamSupport.stream(cv.getPropertyPath().spliterator(), false)
                .map(Path.Node::getName)
                .reduce((first, second) -> second)
                .orElseGet(() -> cv.getPropertyPath().toString());
        errors.put(name, cv.getMessage());
    }

    validationMessage.setErrors(errors.asMap());

    return Response.status(Response.Status.BAD_REQUEST)
            .entity(validationMessage)
            .build();
}
 
Example 21
Project: package-drone   File: JavaValidator.java   View source code 6 votes vote down vote up
private String makePath ( final ConstraintViolation<Object> entry )
{
    final StringBuilder sb = new StringBuilder ();

    final Path p = entry.getPropertyPath ();
    for ( final Node n : p )
    {
        if ( sb.length () > 0 )
        {
            sb.append ( '.' );
        }
        sb.append ( n.getName () );
    }

    return sb.toString ();
}
 
Example 22
Project: ameba   File: ValidationHelper.java   View source code 6 votes vote down vote up
/**
 * Determine the response status (400 or 500) from the given BV exception.
 *
 * @param violation BV exception.
 * @return response status (400 or 500).
 */
public static Response.Status getResponseStatus(final ConstraintViolationException violation) {
    final Iterator<ConstraintViolation<?>> iterator = violation.getConstraintViolations().iterator();

    if (iterator.hasNext()) {
        for (final Path.Node node : iterator.next().getPropertyPath()) {
            final ElementKind kind = node.getKind();

            if (ElementKind.RETURN_VALUE.equals(kind)) {
                return Response.Status.INTERNAL_SERVER_ERROR;
            }
        }
    }

    return Response.Status.BAD_REQUEST;
}
 
Example 23
Project: mycollab   File: AbstractBeanFieldGroupFieldFactory.java   View source code 6 votes vote down vote up
@Override
public void postCommit(FieldGroup.CommitEvent commitEvent) throws FieldGroup.CommitException {
    Set<ConstraintViolation<B>> violations = validation.validate(attachForm.getBean());
    if (violations.size() > 0) {
        StringBuilder errorMsg = new StringBuilder();

        for (ConstraintViolation violation : violations) {
            errorMsg.append(violation.getMessage()).append("<br/>");
            Path propertyPath = violation.getPropertyPath();
            if (propertyPath != null && !propertyPath.toString().equals("")) {
                fieldGroup.getField(propertyPath.toString()).addStyleName("errorField");
            } else {
                Annotation validateAnno = violation.getConstraintDescriptor().getAnnotation();
                if (validateAnno instanceof DateComparison) {
                    String firstDateField = ((DateComparison) validateAnno).firstDateField();
                    String lastDateField = ((DateComparison) validateAnno).lastDateField();

                    fieldGroup.getField(firstDateField).addStyleName("errorField");
                    fieldGroup.getField(lastDateField).addStyleName("errorField");
                }
            }

        }
        throw new FieldGroup.CommitException(errorMsg.toString());
    }
}
 
Example 24
Project: minnal   File: ConstraintViolationExceptionHandlerTest.java   View source code 6 votes vote down vote up
@Test
public void shouldHandleException() {
	ConstraintViolation<?> violation = mock(ConstraintViolation.class);
	Path path = mock(Path.class);
	when(path.toString()).thenReturn("dummyField");
	when(violation.getPropertyPath()).thenReturn(path);
	when(violation.getMessage()).thenReturn("dummy message");
	when(violation.getInvalidValue()).thenReturn("dummy");
	ConstraintViolationException exception = new ConstraintViolationException(Sets.newHashSet(violation));
	ConstraintViolationExceptionHandler handler = new ConstraintViolationExceptionHandler();
	Response response = handler.toResponse(exception);
	Map<String, List<FieldError>> message = new HashMap<String, List<FieldError>>();
	message.put("fieldErrors", Arrays.asList(new FieldError("dummy_field", "dummy message", "dummy")));
	assertEquals(response.getEntity(), message);
	assertEquals(response.getStatus(), 422);
}
 
Example 25
Project: mapr-music   File: ConstraintViolationExceptionMapper.java   View source code 5 votes vote down vote up
@Override
public Response toResponse(ConstraintViolationException e) {

    List<String> errors = e.getConstraintViolations().stream()
            .map(constraintViolation -> {
                Path path = constraintViolation.getPropertyPath();
                String message = constraintViolation.getMessage();
                return String.format("'%s' %s", path, message);
            })
            .collect(Collectors.toList());

    return Response.status(Response.Status.BAD_REQUEST)
            .entity(new ErrorDto(Response.Status.BAD_REQUEST.getStatusCode(), e.getMessage(), errors))
            .build();
}
 
Example 26
Project: act-platform   File: ConstraintViolationMapper.java   View source code 5 votes vote down vote up
private String printPropertyPath(Path path) {
  if (path == null) return "UNKNOWN";

  String propertyPath = "";
  Path.Node parameterNode = null;
  // Construct string representation of property path.
  // This will strip away any other nodes added by RESTEasy (method, parameter, ...).
  for (Path.Node node : path) {
    if (node.getKind() == ElementKind.PARAMETER) {
      parameterNode = node;
    }

    if (node.getKind() == ElementKind.PROPERTY) {
      if (!propertyPath.isEmpty()) {
        propertyPath += ".";
      }

      propertyPath += node;
    }
  }

  if (propertyPath.isEmpty() && parameterNode != null) {
    // No property path constructed, assume this is a validation failure on a request parameter.
    propertyPath = parameterNode.toString();
  }

  return propertyPath;
}
 
Example 27
Project: lams   File: HibernateTraversableResolver.java   View source code 5 votes vote down vote up
public boolean isReachable(Object traversableObject,
						   Path.Node traversableProperty,
						   Class<?> rootBeanType,
						   Path pathToTraversableObject,
						   ElementType elementType) {
	//lazy, don't load
	return Hibernate.isInitialized( traversableObject )
			&& Hibernate.isPropertyInitialized( traversableObject, traversableProperty.getName() );
}
 
Example 28
Project: lams   File: HibernateTraversableResolver.java   View source code 5 votes vote down vote up
public boolean isCascadable(Object traversableObject,
					  Path.Node traversableProperty,
					  Class<?> rootBeanType,
					  Path pathToTraversableObject,
					  ElementType elementType) {
	String path = getStringBasedPath( traversableProperty, pathToTraversableObject );
	return ! associations.contains(path);
}
 
Example 29
Project: Pedidex   File: ConstraintViolationMapper.java   View source code 5 votes vote down vote up
private String printPropertyPath(Path path) {
    if (path == null) {
        return "UNKNOWN";
    }

    String propertyPath = "";
    Path.Node parameterNode = null;
    // Construct string representation of property path.
    // This will strip away any other nodes added by RESTEasy (method, parameter, ...).
    for (Path.Node node : path) {
        if (node.getKind() == ElementKind.PARAMETER) {
            parameterNode = node;
        }

        if (node.getKind() == ElementKind.PROPERTY) {
            if (!propertyPath.isEmpty()) {
                propertyPath += ".";
            }
            propertyPath += node;
        }
    }

    if (propertyPath.isEmpty() && parameterNode != null) {
        // No property path constructed, assume this is a validation failure on a request parameter.
        propertyPath = parameterNode.toString();
    }
    return propertyPath;
}
 
Example 30
Project: gitplex-mit   File: ValuePath.java   View source code 5 votes vote down vote up
public ValuePath(Path validationPath) {
	for (Path.Node node: validationPath) {
		if (node.getIndex() != null) 
			elements.add(new PathSegment.Element(node.getIndex()));
		if (node.getName() != null)
			elements.add(new PathSegment.Property(node.getName()));
	}
}
 
Example 31
Project: minijax   File: MinijaxConstraintViolation.java   View source code 5 votes vote down vote up
public MinijaxConstraintViolation(
        final T rootBean,
        final Path propertyPath,
        final Object invalidValue,
        final ConstraintDescriptor<?> constraintDescriptor) {

    this.rootBean = rootBean;
    this.propertyPath = propertyPath;
    this.invalidValue = invalidValue;
    this.constraintDescriptor = constraintDescriptor;
    message = MinijaxMessageInterpolator.generateMessage(
            constraintDescriptor.getMessageTemplate(),
            constraintDescriptor.getAnnotation(),
            invalidValue);
}
 
Example 32
Project: excel-util4j   File: ValidateKit.java   View source code 5 votes vote down vote up
/**
 * 通过根类和hibernate validator错误信息获取当前验证失败的field对象
 *
 * @param rootClass pojo根类, 如:User.class类包含属性info:Info.class,User即rootClass
 * @param cv        hibernate validator验证结果对象{@link ConstraintViolation}
 * @return 当前失败的field对象
 */
static Field getConstraintViolationField(Class<?> rootClass, ConstraintViolation<Object> cv) {

    try {
        Field field = null;
        for (Path.Node node : cv.getPropertyPath()) {
            String fieldName = node.getName();
            field = rootClass.getDeclaredField(fieldName);
            rootClass = field.getType();
        }
        return field;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 33
Project: servicebuilder   File: ConstraintViolationExceptionMapperTest.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    ExceptionUtil exceptionUtil = new ExceptionUtil(null, null, null);
    exceptionMapper = new ConstraintViolationExceptionMapper(exceptionUtil);
    when(constraintViolation.getConstraintDescriptor()).thenReturn(constraintDescriptor);
    when(constraintViolation.getPropertyPath()).thenReturn(mock(Path.class));
    when(constraintViolation.getMessage()).thenReturn("Validation error message");
    when(constraintViolation.getInvalidValue()).thenReturn(VERDI_SOM_FEILER_VALIDERING);
    when(constraintViolationException.getConstraintViolations())
            .thenReturn(Collections.singleton(constraintViolation));
}
 
Example 34
Project: rest-jersey-utils   File: ValidationError.java   View source code 5 votes vote down vote up
private static String constructJsonPath(Path path) {
    StringBuilder jsonPath = new StringBuilder("#");
    path.forEach(pathComponent -> {
        if (pathComponent.getKind() == ElementKind.PROPERTY) {
            jsonPath.append("/").append(pathComponent.getName());
        }
    });
    return jsonPath.toString();
}
 
Example 35
Project: nifi-registry   File: ConstraintViolationExceptionMapper.java   View source code 5 votes vote down vote up
@Override
public Response toResponse(ConstraintViolationException exception) {
    logger.info(String.format("%s. Returning %s response.", exception, Response.Status.BAD_REQUEST));

    if (logger.isDebugEnabled()) {
        logger.debug(StringUtils.EMPTY, exception);
    }

    // start with the overall message which will be something like "Cannot create xyz"
    final StringBuilder errorMessage = new StringBuilder(exception.getMessage()).append(" - ");

    boolean first = true;
    for (final ConstraintViolation violation : exception.getConstraintViolations()) {
        if (!first) {
            errorMessage.append(", ");
        }
        first = false;

        // lastNode should end up as the field that failed validation
        Path.Node lastNode = null;
        for (final Path.Node node : violation.getPropertyPath()) {
            lastNode = node;
        }

        // append something like "xyz must not be..."
        errorMessage.append(lastNode.getName()).append(" ").append(violation.getMessage());
    }

    return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage.toString()).type("text/plain").build();
}
 
Example 36
Project: crudlet   File: RestValidationConstraintErrorBuilder.java   View source code 5 votes vote down vote up
private static String readPropertyName(ConstraintViolation violation) {
    Iterator<Path.Node> i = violation.getPropertyPath().iterator();
    Path.Node current = i.next();
    while (i.hasNext()) {
        current = i.next();
    }
    // Use '.' as the key if the entire object is erroneous
    if ("arg0".equals(current.getName())) {
        return ".";
    }
    else {
        return violation.getPropertyPath().toString();
    }
}
 
Example 37
Project: cuba   File: CubaValidationTraversableResolver.java   View source code 5 votes vote down vote up
@Override
public final boolean isReachable(Object traversableObject,
                                 Path.Node traversableProperty,
                                 Class<?> rootBeanType,
                                 Path pathToTraversableObject,
                                 ElementType elementType) {
    log.trace("Calling isReachable on object {} with node name {}", traversableObject, traversableProperty.getName());

    if (traversableObject == null
            || metadata.getClass(traversableObject.getClass()) == null) {
        return true;
    }

    return entityStates.isLoaded(traversableObject, traversableProperty.getName());
}
 
Example 38
Project: nexus-public   File: ConstraintViolationExceptionMapper.java   View source code 5 votes vote down vote up
private Status getResponseStatus(final ConstraintViolation<?> violation) {
  for (Path.Node node : violation.getPropertyPath()) {
    ElementKind kind = node.getKind();

    if (ElementKind.RETURN_VALUE.equals(kind)) {
      return Status.INTERNAL_SERVER_ERROR;
    }
  }

  return Status.BAD_REQUEST;
}
 
Example 39
Project: nexus-public   File: AlwaysTraversableResolver.java   View source code 5 votes vote down vote up
/**
 * return {@code true}
 */
public boolean isCascadable(final Object traversableObject,
                            final Node traversableProperty,
                            final Class<?> rootBeanType,
                            final Path pathToTraversableObject,
                            final ElementType elementType)
{
  return true;
}
 
Example 40
Project: nexus-public   File: AlwaysTraversableResolver.java   View source code 5 votes vote down vote up
/**
 * return {@code true}
 */
public boolean isReachable(final Object traversableObject,
                           final Node traversableProperty,
                           final Class<?> rootBeanType,
                           final Path pathToTraversableObject,
                           final ElementType elementType)
{
  return true;
}