javax.validation.Path Java Examples

The following examples show how to use javax.validation.Path. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HibernateTraversableResolver.java    From lams with GNU General Public License v2.0 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
Source File: JPATraversableResolver.java    From micronaut-sql with Apache License 2.0 6 votes vote down vote up
@Override
public final boolean isReachable(Object traversableObject,
                                 Path.Node traversableProperty,
                                 Class<?> rootBeanType,
                                 Path pathToTraversableObject,
                                 ElementType elementType) {
    if (LOG.isTraceEnabled()) {
        LOG.trace(
                "Calling isReachable on object {} with node name {}.",
                traversableObject,
                traversableProperty.getName()
        );
    }

    if (traversableObject == null) {
        return true;
    }

    return Persistence.getPersistenceUtil().isLoaded(traversableObject, traversableProperty.getName());
}
 
Example #3
Source File: ConstraintViolations.java    From krazo with Apache License 2.0 6 votes vote down vote up
private static Annotation[] getPropertyAnnotations(ConstraintViolation<?> violation, Path.PropertyNode node) {

        Class<?> leafBeanClass = violation.getLeafBean().getClass();
        Set<Annotation> allAnnotations = new HashSet<>();
        try {

            Field field = leafBeanClass.getDeclaredField(node.getName());
            allAnnotations.addAll(Arrays.asList(field.getAnnotations()));

        } catch (NoSuchFieldException e) {
            // ignore for now
        }

        allAnnotations.addAll(readAndWriteMethodAnnotationsForField(leafBeanClass, node.getName()));

        return allAnnotations.toArray(new Annotation[0]);
    }
 
Example #4
Source File: SpringValidatorAdapter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Determine a field for the given constraint violation.
 * <p>The default implementation returns the stringified property path.
 * @param violation the current JSR-303 ConstraintViolation
 * @return the Spring-reported field (for use with {@link Errors})
 * @since 4.2
 * @see javax.validation.ConstraintViolation#getPropertyPath()
 * @see org.springframework.validation.FieldError#getField()
 */
protected String determineField(ConstraintViolation<Object> violation) {
	Path path = violation.getPropertyPath();
	StringBuilder sb = new StringBuilder();
	boolean first = true;
	for (Path.Node node : path) {
		if (node.isInIterable()) {
			sb.append('[');
			Object index = node.getIndex();
			if (index == null) {
				index = node.getKey();
			}
			if (index != null) {
				sb.append(index);
			}
			sb.append(']');
		}
		String name = node.getName();
		if (name != null && node.getKind() == ElementKind.PROPERTY && !name.startsWith("<")) {
			if (!first) {
				sb.append('.');
			}
			first = false;
			sb.append(name);
		}
	}
	return sb.toString();
}
 
Example #5
Source File: ConstraintViolations.java    From ozark with Apache License 2.0 6 votes vote down vote up
private static Annotation[] getPropertyAnnotations(ConstraintViolation<?> violation, Path.PropertyNode node) {

        Class<?> leafBeanClass = violation.getLeafBean().getClass();
        Set<Annotation> allAnnotations = new HashSet<>();
        try {

            Field field = leafBeanClass.getDeclaredField(node.getName());
            allAnnotations.addAll(Arrays.asList(field.getAnnotations()));

        } catch (NoSuchFieldException e) {
            // ignore for now
        }

        allAnnotations.addAll(readAndWriteMethodAnnotationsForField(leafBeanClass, node.getName()));

        return allAnnotations.toArray(new Annotation[0]);
    }
 
Example #6
Source File: ClientDataValidationErrorHandlerListenerTest.java    From backstopper with Apache License 2.0 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 #7
Source File: ServersideValidationErrorHandlerListenerTest.java    From backstopper with Apache License 2.0 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 #8
Source File: CubaValidationTraversableResolver.java    From cuba with Apache License 2.0 6 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 #9
Source File: ScreenValidation.java    From cuba with Apache License 2.0 6 votes vote down vote up
/**
 * Validate cross-field BeanValidation rules.
 *
 * @param origin screen controller
 * @param item   item to validate
 * @return validation errors
 */
public ValidationErrors validateCrossFieldRules(@SuppressWarnings("unused") FrameOwner origin, Entity item) {
    ValidationErrors errors = new ValidationErrors();

    Validator validator = beanValidation.getValidator();
    Set<ConstraintViolation<Entity>> violations = validator.validate(item, 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()));

    return errors;
}
 
Example #10
Source File: AbstractEditor.java    From cuba with Apache License 2.0 6 votes vote down vote up
public void validateAdditionalRules(ValidationErrors errors) {
    // all previous validations return no errors
    if (crossFieldValidate && errors.isEmpty()) {
        BeanValidation beanValidation = getBeanLocator().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 #11
Source File: JavaValidator.java    From packagedrone with Eclipse Public License 1.0 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 #12
Source File: ValidationHelper.java    From ameba with MIT License 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 #13
Source File: ValidationExceptionMapper.java    From seed with Mozilla Public License 2.0 6 votes vote down vote up
private ParameterInfo resolveParameterInfo(Path.ParameterNode node, Method method) {
    if (method != null) {
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        int parameterIndex = node.as(Path.ParameterNode.class).getParameterIndex();
        if (parameterIndex < parameterAnnotations.length) {
            for (Annotation a : parameterAnnotations[parameterIndex]) {
                if (a instanceof QueryParam) {
                    return new ParameterInfo(Location.QUERY_PARAMETER, ((QueryParam) a).value());
                } else if (a instanceof PathParam) {
                    return new ParameterInfo(Location.PATH_PARAMETER, ((PathParam) a).value());
                } else if (a instanceof HeaderParam) {
                    return new ParameterInfo(Location.HEADER_PARAMETER, ((HeaderParam) a).value());
                } else if (a instanceof CookieParam) {
                    return new ParameterInfo(Location.COOKIE_PARAMETER, ((CookieParam) a).value());
                } else if (a instanceof FormParam) {
                    return new ParameterInfo(Location.FORM_PARAMETER, ((FormParam) a).value());
                } else if (a instanceof MatrixParam) {
                    return new ParameterInfo(Location.MATRIX_PARAMETER, ((MatrixParam) a).value());
                }
            }
            return new ParameterInfo(Location.REQUEST_BODY, node.getName());
        }
    }
    return new ParameterInfo(Location.UNKNOWN, node.getName());
}
 
Example #14
Source File: ConstraintViolationExceptionHandlerTest.java    From minnal with Apache License 2.0 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 #15
Source File: ValidationMethodInterceptor.java    From guice-validator with MIT License 5 votes vote down vote up
private Path.Node getLeafNode(final ConstraintViolation<?> constraintViolation) {
    final Iterator<Path.Node> nodes = constraintViolation.getPropertyPath().iterator();
    Path.Node leafNode = null;
    while (nodes.hasNext()) {
        leafNode = nodes.next();
    }
    return leafNode;
}
 
Example #16
Source File: AddSoRPersonFlowTests.java    From openregistry with Apache License 2.0 5 votes vote down vote up
@Test
public void testCriteriaSubmitError() throws ReconciliationException, SorPersonAlreadyExistsException {
    final ReconciliationCriteria criteria = constructReconciliationCriteria(RUDYARD, RUDYARD, "INVALID_SSN", null, PHONE_NUMBER, new Date(0), OR_WEBAPP_IDENTIFIER);
    final ServiceExecutionResult<Person> serviceExecutionResult = mock(ServiceExecutionResult.class, RETURNS_SMART_NULLS);
    final Set<ConstraintViolation> violations = mock(Set.class, RETURNS_SMART_NULLS);
    final Iterator iter = mock(Iterator.class);
    final ConstraintViolation constraintViolation = mock(ConstraintViolation.class, RETURNS_SMART_NULLS);
    final Path path = mock(Path.class);
    final ConstraintDescriptor constraintDescriptor = mock(ConstraintDescriptor.class, RETURNS_SMART_NULLS);
    final Map map = mock(Map.class, RETURNS_SMART_NULLS);

    when(constraintViolation.getMessage()).thenReturn("errorCode");
    when(constraintViolation.getConstraintDescriptor()).thenReturn(constraintDescriptor);
    when(constraintDescriptor.getAttributes()).thenReturn(map);
    when(map.values()).thenReturn(new ArrayList());
    when(constraintDescriptor.getAnnotation()).thenReturn(new TestAnnotation());

    when(iter.next()).thenReturn(constraintViolation);
    when(iter.hasNext()).thenReturn(true).thenReturn(false);
    when(violations.iterator()).thenReturn(iter);
    when(violations.isEmpty()).thenReturn(false);
    when(serviceExecutionResult.succeeded()).thenReturn(false);
    when(serviceExecutionResult.getValidationErrors()).thenReturn(violations);
    when(personService.addPerson(criteria)).thenReturn(serviceExecutionResult);


    setCurrentState("addPerson");
    getFlowScope().put("personSearch", criteria);

    MockExternalContext context = new MockExternalContext();

    //submit with invalid input
    context.setEventId("submitAddPerson");
    resumeFlow(context);
    assertCurrentStateEquals("addPerson");
}
 
Example #17
Source File: MockitoUtils.java    From openregistry with Apache License 2.0 5 votes vote down vote up
public static Set<ConstraintViolation> oneMinimalisticMockConstraintViolation() {

        final ConstraintViolation mockConstraintViolation = Mockito.mock(ConstraintViolation.class, Mockito.RETURNS_SMART_NULLS);
        final Path mockPath = Mockito.mock(Path.class);
        Mockito.when(mockPath.toString()).thenReturn("test.property.path");
        Mockito.when(mockConstraintViolation.getPropertyPath()).thenReturn(mockPath);
        Mockito.when(mockConstraintViolation.getMessage()).thenReturn("mockConstraintViolation: error message");
        Mockito.when(mockConstraintViolation.getInvalidValue()).thenReturn("mockConstraintViolation: invalid value");
        Set<ConstraintViolation> setWithErrors = new HashSet<ConstraintViolation>();
        setWithErrors.add(mockConstraintViolation);
        return setWithErrors;
    }
 
Example #18
Source File: AndroidVariantEndpointTest.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
public Path getPropertyPath() {
    return new Path() {
        @Override
        public Iterator<Node> iterator() {
            return null;
        }

        @Override
        public String toString() {
            return "stub violation path";
        }
    };
}
 
Example #19
Source File: WebPushVariantEndpointTest.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
public Path getPropertyPath() {
    return new Path() {
        @Override
        public Iterator<Node> iterator() {
            return null;
        }

        @Override
        public String toString() {
            return "stub violation path";
        }
    };
}
 
Example #20
Source File: ValidationExceptionMapper.java    From jaxrs-beanvalidation-javaee7 with Apache License 2.0 5 votes vote down vote up
private Response.Status getResponseStatus(final ConstraintViolation<?> constraintViolation) {
    for (final Path.Node node : constraintViolation.getPropertyPath()) {
        final ElementKind kind = node.getKind();

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

    return Response.Status.BAD_REQUEST;
}
 
Example #21
Source File: IronJacamarTraversableResolver.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean isCascadable(Object traversableObject,
                            Path.Node traversableProperty, Class<?> rootBeanType,
                            Path pathToTraversableObject, ElementType elementType)
{
   return true;
}
 
Example #22
Source File: ValidationExceptionMapper.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
private Method resolveMethod(Class<?> resourceClass, Path.MethodNode methodNode) {
    List<Class<?>> parameterTypes = methodNode.getParameterTypes();
    try {
        return resourceClass.getMethod(
                methodNode.getName(),
                parameterTypes.toArray(new Class[parameterTypes.size()])
        );
    } catch (NoSuchMethodException e) {
        return null;
    }
}
 
Example #23
Source File: ValidationHelper.java    From edison-microservice with Apache License 2.0 5 votes vote down vote up
public static <T> List<String> getViolatedFields(T apiRepresentation) {
    Set<ConstraintViolation<T>> violations = validator.validate(apiRepresentation);
    return violations.stream()
            .map(ConstraintViolation::getPropertyPath)
            .map(Path::toString)
            .collect(toList());
}
 
Example #24
Source File: ActionValidator.java    From lastaflute with Apache License 2.0 5 votes vote down vote up
protected String derivePropertyPathByNode(ConstraintViolation<Object> vio) {
    final StringBuilder sb = new StringBuilder();
    final Path path = vio.getPropertyPath();
    int elementCount = 0;
    for (Path.Node node : path) {
        if (node.isInIterable()) { // building e.g. "[0]" of seaList[0]
            Object nodeIndex = node.getIndex();
            if (nodeIndex == null) {
                nodeIndex = node.getKey(); // null if e.g. iterable
            }
            sb.append("[").append(nodeIndex != null ? nodeIndex : "").append("]"); // e.g. [0] or []
        }
        final String nodeName = node.getName();
        if (nodeName != null && node.getKind() == ElementKind.PROPERTY) {
            // _/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/
            // if e.g.
            //  private List<@Required String> seaList;
            // then path is "seaList[0].<list element>" since Hibernate Validator-6.x
            // <list element> part is unneeded for property path of message so skip here
            // _/_/_/_/_/_/_/_/_/_/
            if (!nodeName.startsWith("<")) { // except e.g. <list element>
                if (elementCount > 0) {
                    sb.append(".");
                }
                sb.append(nodeName);
                ++elementCount;
            }
        }
    }
    return sb.toString(); // e.g. sea, sea.hangar, seaList[0], seaList[0].hangar
}
 
Example #25
Source File: AlwaysTraversableResolver.java    From nexus-public with Eclipse Public License 1.0 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;
}
 
Example #26
Source File: AlwaysTraversableResolver.java    From nexus-public with Eclipse Public License 1.0 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 #27
Source File: ConstraintViolationExceptionMapper.java    From nexus-public with Eclipse Public License 1.0 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 #28
Source File: SpringValidatorAdapter.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Determine a field for the given constraint violation.
 * <p>The default implementation returns the stringified property path.
 * @param violation the current JSR-303 ConstraintViolation
 * @return the Spring-reported field (for use with {@link Errors})
 * @since 4.2
 * @see javax.validation.ConstraintViolation#getPropertyPath()
 * @see org.springframework.validation.FieldError#getField()
 */
protected String determineField(ConstraintViolation<Object> violation) {
	Path path = violation.getPropertyPath();
	StringBuilder sb = new StringBuilder();
	boolean first = true;
	for (Path.Node node : path) {
		if (node.isInIterable()) {
			sb.append('[');
			Object index = node.getIndex();
			if (index == null) {
				index = node.getKey();
			}
			if (index != null) {
				sb.append(index);
			}
			sb.append(']');
		}
		String name = node.getName();
		if (name != null && node.getKind() == ElementKind.PROPERTY && !name.startsWith("<")) {
			if (!first) {
				sb.append('.');
			}
			first = false;
			sb.append(name);
		}
	}
	return sb.toString();
}
 
Example #29
Source File: ConstraintViolationExceptionMapper.java    From nifi-registry with Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(ConstraintViolationException 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());
    }

    logger.info(String.format("%s. Returning %s response.", errorMessage, Response.Status.BAD_REQUEST));
    if (logger.isDebugEnabled()) {
        logger.debug(StringUtils.EMPTY, exception);
    }

    return Response.status(Response.Status.BAD_REQUEST).entity(errorMessage.toString()).type("text/plain").build();
}
 
Example #30
Source File: BaseExceptionHandler.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 统一处理请求参数校验(普通传参)
 *
 * @param e ConstraintViolationException
 * @return FebsResponse
 */
@ExceptionHandler(value = ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public FebsResponse handleConstraintViolationException(ConstraintViolationException e) {
    StringBuilder message = new StringBuilder();
    Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
    for (ConstraintViolation<?> violation : violations) {
        Path path = violation.getPropertyPath();
        String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), ".");
        message.append(pathArr[1]).append(violation.getMessage()).append(StringConstant.COMMA);
    }
    message = new StringBuilder(message.substring(0, message.length() - 1));
    log.error(message.toString());
    return new FebsResponse().message(message.toString());
}