Java Code Examples for javax.validation.ElementKind#PROPERTY

The following examples show how to use javax.validation.ElementKind#PROPERTY . 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: ConstraintViolationExceptionHandler.java    From spring-rest-exception-handler with Apache License 2.0 6 votes vote down vote up
@Override
public ValidationErrorMessage createBody(ConstraintViolationException ex, HttpServletRequest req) {

    ErrorMessage tmpl = super.createBody(ex, req);
    ValidationErrorMessage msg = new ValidationErrorMessage(tmpl);

    for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
        Node pathNode = findLastNonEmptyPathNode(violation.getPropertyPath());

        // path is probably useful only for properties (fields)
        if (pathNode != null && pathNode.getKind() == ElementKind.PROPERTY) {
            msg.addError(pathNode.getName(), convertToString(violation.getInvalidValue()), violation.getMessage());

        // type level constraints etc.
        } else {
            msg.addError(violation.getMessage());
        }
    }
    return msg;
}
 
Example 3
Source File: ReferenceValidatorImpl.java    From cm_ext with Apache License 2.0 6 votes vote down vote up
private void callReferenceConstraints(Object obj, DescriptorPath path) {
  DescriptorNode node = path.getHeadNode();
  for (ReferenceConstraint<T> constraint : constraints) {
    if (node.getClass().isAssignableFrom(constraint.getNodeType()))  {
      continue;
    }

    Annotation annotation;
    Class<? extends  Annotation> annClass = constraint.getAnnotationType();
    if (node.getKind() == ElementKind.BEAN) {
      annotation = ReflectionHelper.findAnnotation(obj.getClass(), annClass);
    } else if (node.getKind() == ElementKind.PROPERTY) {
      Method method = node.as(PropertyNode.class).getMethod();
      annotation = ReflectionHelper.findAnnotation(method, annClass);
    } else {
      throw new IllegalStateException(node.getKind() + " is an unsupported type.");
    }

    if (annotation == null) {
      continue;
    }

    this.violations.addAll(constraint.checkConstraint(annotation, obj, path, allowedRefs));
  }
}
 
Example 4
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 5
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 6
Source File: ConstraintViolationImpl.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Override
public ElementKind getKind() {
	if (path == null) {
		return ElementKind.BEAN;
	} else {
		return ElementKind.PROPERTY;
	}
}
 
Example 7
Source File: ValidationResponse.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public ValidationResponse(final ConstraintViolationException cause) {
  super(false, new ArrayList<>());
  //noinspection ThrowableResultOfMethodCallIgnored
  checkNotNull(cause);
  Set<ConstraintViolation<?>> violations = cause.getConstraintViolations();
  if (violations != null && !violations.isEmpty()) {
    for (ConstraintViolation<?> violation : violations) {
      List<String> entries = new ArrayList<>();
      // iterate path to get the full path
      Iterator<Node> it = violation.getPropertyPath().iterator();
      while (it.hasNext()) {
        Node node = it.next();
        if (ElementKind.PROPERTY == node.getKind() || (ElementKind.PARAMETER == node.getKind() && !it.hasNext())) {
          if (node.getKey() != null) {
            entries.add(node.getKey().toString());
          }
          entries.add(node.getName());
        }
      }
      if (entries.isEmpty()) {
        if (messages == null) {
          messages = new ArrayList<>();
        }
        messages.add(violation.getMessage());
      }
      else {
        if (errors == null) {
          errors = new HashMap<>();
        }
        errors.put(Joiner.on('.').join(entries), violation.getMessage());
      }
    }
  }
  else if (cause.getMessage() != null) {
    messages = new ArrayList<>();
    messages.add(cause.getMessage());
  }
}
 
Example 8
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 9
Source File: DescriptorPathImpl.java    From cm_ext with Apache License 2.0 5 votes vote down vote up
public PropertyNode(String name,
                    boolean iterable,
                    Integer index,
                    Method method) {
  super(name, iterable, index, null, ElementKind.PROPERTY);
  this.method = method;
}
 
Example 10
Source File: ConstraintViolationExceptionMapper.java    From crnk-framework with Apache License 2.0 4 votes vote down vote up
public Object visitProperty(Object nodeObject, Node node) {
	ResourceRegistry resourceRegistry = context.getResourceRegistry();
	Class nodeClass = nodeObject.getClass();
	ResourceInformation resourceInformation = null;
	if (resourceRegistry.hasEntry(nodeClass)) {
		RegistryEntry entry = resourceRegistry.getEntry(nodeClass);
		resourceInformation = entry.getResourceInformation();
	}

	String name = node.getName();

	Object next;
	if (node.getKind() == ElementKind.PROPERTY) {
		if (resourceRegistry.hasEntry(nodeClass)) {
			ResourceFieldAccessor accessor = resourceInformation.getAccessor(name);
			if (accessor != null) {
				next = accessor.getValue(nodeObject);
			} else {
				next = PropertyUtils.getProperty(nodeObject, name);
			}
		} else {
			next = PropertyUtils.getProperty(nodeObject, name);
		}
	} else if (node.getKind() == ElementKind.BEAN) {
		next = nodeObject;
	} else {
		throw new UnsupportedOperationException("unknown node: " + node);
	}

	if (name != null) {
		ResourceField resourceField =
				resourceInformation != null ? resourceInformation.findFieldByUnderlyingName(name) : null;

		String mappedName = name;
		if (resourceField != null) {
			// in case of @JsonApiRelationId it will be mapped to original name
			resourceField = resourceInformation.findFieldByUnderlyingName(resourceField.getUnderlyingName());
			mappedName = resourceField.getJsonName();
		}

		appendSeparator();
		if (resourceField == null || resourceField.getResourceFieldType() == ResourceFieldType.ID) {
			// continue along attributes path or primary key on root
			appendSourcePointer(mappedName);
		} else if (resourceField != null && resourceField.getResourceFieldType() == ResourceFieldType.RELATIONSHIP) {
			appendSourcePointer("/data/relationships/");
			appendSourcePointer(mappedName);
		} else {

			appendSourcePointer("/data/attributes/");
			appendSourcePointer(mappedName);
		}
	}
	return next;
}
 
Example 11
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 12
Source File: ConstraintViolations.java    From krazo 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];

    }
 
Example 13
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];

    }