Java Code Examples for javax.validation.Path#Node

The following examples show how to use javax.validation.Path#Node . 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: 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 2
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 3
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 4
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 5
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 6
Source File: ConstraintViolationExceptionMapper.java    From microservices-springboot with MIT License 5 votes vote down vote up
/**
 * Handle an invalid property. Can be:
 * <p>
 * 1. Invalid request parameter (annotated bean param field or annotated resource class field)
 * 2. Invalid request entity property (annotated bean param field)
 *
 * @param constraintViolation
 */
private ValidationError handleInvalidProperty(ConstraintViolation constraintViolation) {

    Path.Node leafNode = getLeafNode(constraintViolation.getPropertyPath()).get();
    Class<?> beanClass = constraintViolation.getLeafBean().getClass();

    // Can be an invalid request parameter (annotated bean param field or annotated resource class field)
    Optional<Field> optionalField = getField(leafNode.getName(), beanClass);
    if (optionalField.isPresent()) {
        Optional<ParameterDetails> optionalParameterDetails = getParameterDetails(optionalField.get().getAnnotations());
        if (optionalParameterDetails.isPresent()) {
            return createErrorForParameter(optionalParameterDetails.get(), constraintViolation);
        }
    }

    // Get Jackson ObjectMapper
    ContextResolver<ObjectMapper> resolver = providers.getContextResolver(ObjectMapper.class, MediaType.WILDCARD_TYPE);
    ObjectMapper mapper = resolver.getContext(ObjectMapper.class);

    // Can be an invalid request entity property (annotated bean param field)
    Optional<String> optionalJsonProperty = getJsonPropertyName(mapper, beanClass, leafNode.getName());
    if (optionalJsonProperty.isPresent()) {
        ValidationError error = new ValidationError();
        error.setType(REQUEST_ENTITY_PROPERTY);
        error.setName(optionalJsonProperty.get());
        error.setMessage(constraintViolation.getMessage());
        return error;
    }

    return handleUnknownSource(constraintViolation);
}
 
Example 7
Source File: HibernateTraversableResolver.java    From lams with GNU General Public License v2.0 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 8
Source File: HibernateTraversableResolver.java    From lams with GNU General Public License v2.0 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 9
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 10
Source File: IronJacamarTraversableResolver.java    From ironjacamar with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean isReachable(Object traversableObject, Path.Node traversableProperty,
                           Class<?> rootBeanType, Path pathToTraversableObject,
                           ElementType elementType)
{
   return true;
}
 
Example 11
Source File: ConstraintViolationMapper.java    From act-platform with ISC License 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 12
Source File: ValidationMethodInterceptor.java    From guice-validator with MIT License 5 votes vote down vote up
private String getMessage(final Member member, final Object[] args,
                          final Set<? extends ConstraintViolation<?>> violations) {
    final StringBuilder message = new StringBuilder(200)
            .append(violations.size())
            .append(" constraint violation(s) occurred during method validation.")
            .append("\nConstructor or Method: ").append(member)
            .append("\nArgument values: ").append(Arrays.toString(args))
            .append("\nConstraint violations: ");
    int i = 1;
    for (ConstraintViolation<?> constraintViolation : violations) {
        final Path.Node leafNode = getLeafNode(constraintViolation);
        message.append("\n (")
                .append(i++)
                .append(") Kind: ")
                .append(leafNode.getKind());
        if (leafNode.getKind() == ElementKind.PARAMETER) {
            message.append("\n parameter index: ")
                    .append(leafNode.as(Path.ParameterNode.class).getParameterIndex());
        }
        message.append("\n message: ").append(constraintViolation.getMessage())
                .append("\n root bean: ").append(constraintViolation.getRootBean())
                .append("\n property path: ").append(constraintViolation.getPropertyPath())
                .append("\n constraint: ").append(constraintViolation.getConstraintDescriptor().getAnnotation());
    }

    return message.toString();
}
 
Example 13
Source File: BeanValidationInterceptor.java    From portals-pluto with Apache License 2.0 4 votes vote down vote up
@AroundInvoke
public Object validateMethodInvocation(InvocationContext invocationContext) throws Exception {

	Validator validator = validatorFactory.getValidator();

	if (validator == null) {
		return invocationContext.proceed();
	}

	Set<ConstraintViolation<Object>> constraintViolations = validator.validate(invocationContext.getTarget());

	for (ConstraintViolation<Object> constraintViolation : constraintViolations) {

		Path propertyPath = constraintViolation.getPropertyPath();

		Path.Node lastPathNode = null;

		for (Path.Node pathNode : propertyPath) {
			lastPathNode = pathNode;
		}

		if ((lastPathNode != null) && (lastPathNode.getKind() == ElementKind.PROPERTY)) {

			Object leafBean = constraintViolation.getLeafBean();
			Class<?> leafBeanClass = leafBean.getClass();

			BeanInfo beanInfo = Introspector.getBeanInfo(leafBean.getClass());

			PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

			for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
				String propertyDescriptorName = propertyDescriptor.getName();

				if (propertyDescriptorName.equals("targetClass")) {
					Method readMethod = propertyDescriptor.getReadMethod();
					leafBeanClass = (Class<?>) readMethod.invoke(leafBean);
				}
			}

			Field leafBeanField = leafBeanClass.getDeclaredField(lastPathNode.getName());

			String paramName = null;

			Annotation[] annotations = leafBeanField.getAnnotations();

			for (Annotation annotation : annotations) {

				if (annotation instanceof CookieParam) {
					CookieParam cookieParam = (CookieParam) annotation;
					paramName = cookieParam.value();

					break;
				}
				else if (annotation instanceof FormParam) {
					FormParam formParam = (FormParam) annotation;
					paramName = formParam.value();

					break;
				}
				else if (annotation instanceof HeaderParam) {
					HeaderParam headerParam = (HeaderParam) annotation;
					paramName = headerParam.value();

					break;
				}
				else if (annotation instanceof QueryParam) {
					QueryParam queryParam = (QueryParam) annotation;
					paramName = queryParam.value();
				}
			}

			String interpolatedMessage = constraintViolation.getMessage();

			if (messageInterpolator != null) {
				interpolatedMessage = messageInterpolator.interpolate(constraintViolation.getMessageTemplate(),
						new MessageInterpolatorContextImpl(constraintViolation), mvcContext.getLocale());
			}

			mutableBindingResult.addValidationError(new ValidationErrorImpl(paramName, interpolatedMessage,
					constraintViolation));
		}

	}

	return invocationContext.proceed();
}
 
Example 14
Source File: ConstraintException.java    From rest.vertx with Apache License 2.0 4 votes vote down vote up
/**
 * Tries to produce some sensible message to make some informed decision
 *
 * @param definition           route definition to get parameter information
 * @param constraintViolations list of violations
 * @return message describing violation
 */
private static String createMessage(RouteDefinition definition, Set<? extends ConstraintViolation<?>> constraintViolations) {

	List<String> messages = new ArrayList<>();
	for (ConstraintViolation<?> violation : constraintViolations) {

		StringBuilder message = new StringBuilder();
		for (Path.Node next : violation.getPropertyPath()) {

			if (next instanceof Path.ParameterNode &&
			    next.getKind().equals(ElementKind.PARAMETER)) {

				Path.ParameterNode paramNode = (Path.ParameterNode) next;
				int index = paramNode.getParameterIndex();
				if (index < definition.getParameters().size()) {
					MethodParameter param = definition.getParameters().get(index);
					switch (param.getType()) {
						case body:
							message.append(param.toString());
							message.append(" ").append(param.getDataType().getSimpleName());
							break;

						default:
							message.append(param.toString());
							break;
					}

				}
			}

			if (next instanceof Path.PropertyNode &&
			    next.getKind().equals(ElementKind.PROPERTY)) {

				Path.PropertyNode propertyNode = (Path.PropertyNode) next;
				message.append(".").append(propertyNode.getName());
			}
		}

		message.append(": ").append(violation.getMessage());

		messages.add(message.toString());
	}

	return StringUtils.join(messages, ", ");
}
 
Example 15
Source File: CubaValidationTraversableResolver.java    From cuba with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isCascadable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType,
                            Path pathToTraversableObject, ElementType elementType) {
    // return true as org.hibernate.validator.internal.engine.resolver.JPATraversableResolver does
    return true;
}
 
Example 16
Source File: EmptyTraversableResolver.java    From onetwo with Apache License 2.0 4 votes vote down vote up
public final boolean isReachable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
	return true;
}
 
Example 17
Source File: EmptyTraversableResolver.java    From onetwo with Apache License 2.0 4 votes vote down vote up
public final boolean isCascadable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
	return true;
}
 
Example 18
Source File: ValidationExceptionMapper.java    From seed with Mozilla Public License 2.0 4 votes vote down vote up
private boolean addErrorsToList(ConstraintViolationException exception,
        List<ValidationExceptionRepresentation.ValidationError> validationErrors) {
    boolean responseError = false;
    Class<?> resourceClass = ProxyUtils.cleanProxy(resourceInfo.getResourceClass());

    for (ConstraintViolation<?> constraintViolation : exception.getConstraintViolations()) {
        ValidationExceptionRepresentation.ValidationError validationError =
                new ValidationExceptionRepresentation.ValidationError();

        boolean appendToPath = false;
        StringBuilder path = new StringBuilder();
        Method method = null;
        for (Path.Node node : constraintViolation.getPropertyPath()) {
            switch (node.getKind()) {
                case METHOD:
                    method = resolveMethod(resourceClass, node.as(Path.MethodNode.class));
                    continue;
                case RETURN_VALUE:
                    validationError.setLocation(Location.RESPONSE_BODY.toString());
                    responseError = true;
                    appendToPath = true;
                    continue;
                case PARAMETER:
                    ParameterInfo parameterInfo = resolveParameterInfo(
                            node.as(Path.ParameterNode.class),
                            method);
                    validationError.setLocation(parameterInfo.getLocation().toString());
                    if (!parameterInfo.isBody()) {
                        path.append(parameterInfo.getName()).append(".");
                    }
                    appendToPath = true;
                    continue;
                default:
                    break;
            }
            if (appendToPath) {
                path.append(node.getName()).append(".");
            }
        }

        if (path.length() > 0) {
            validationError.setPath(path.substring(0, path.length() - 1));
        }

        validationError.setMessage(constraintViolation.getMessage());

        Object invalidValue = constraintViolation.getInvalidValue();
        if (invalidValue != null) {
            validationError.setInvalidValue(String.valueOf(invalidValue));
        }

        validationErrors.add(validationError);
    }

    return responseError;
}
 
Example 19
Source File: JPATraversableResolver.java    From micronaut-sql with Apache License 2.0 4 votes vote down vote up
@Override
public final boolean isCascadable(Object traversableObject, Path.Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) {
    return true;
}
 
Example 20
Source File: ConstraintViolations.java    From ozark with Apache License 2.0 3 votes vote down vote up
private static Annotation[] getAnnotations(ConstraintViolation<?> violation) {


        // create a simple list of nodes from the path
        List<Path.Node> nodes = new ArrayList<>();
        for (Path.Node node : violation.getPropertyPath()) {
            nodes.add(node);
        }
        Path.Node lastNode = nodes.get(nodes.size() - 1);

        // the path refers to some property of the leaf bean
        if (lastNode.getKind() == ElementKind.PROPERTY) {

            Path.PropertyNode propertyNode = lastNode.as(Path.PropertyNode.class);
            return getPropertyAnnotations(violation, propertyNode);

        }

        // The path refers to a method parameter
        else if (lastNode.getKind() == ElementKind.PARAMETER && nodes.size() == 2) {

            Path.MethodNode methodNode = nodes.get(0).as(Path.MethodNode.class);
            Path.ParameterNode parameterNode = nodes.get(1).as(Path.ParameterNode.class);

            return getParameterAnnotations(violation, methodNode, parameterNode);

        }


        log.warning("Could not read annotations for path: " + violation.getPropertyPath().toString());
        return new Annotation[0];

    }