javax.validation.ElementKind Java Examples

The following examples show how to use javax.validation.ElementKind. 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: 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 #3
Source File: ReferenceValidatorImpl.java    From cm_ext with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeNode(Object obj, DescriptorPath path) {
  if (path.getHeadNode().getKind() != ElementKind.BEAN) {
    return;
  }
  BeanDescriptorNode node = path.getHeadNode().as(BeanDescriptorNode.class);
  Named named = ReflectionHelper.findAnnotation(node.getBean().getClass(), Named.class);
  Referenced referenced = ReflectionHelper.findAnnotation(node.getBean().getClass(), Referenced.class);
  if (referenced != null) {
    if (referenced.as().length == 0 && named == null) {
      throw new IllegalStateException("The @Referenced annotation requires the @Named to also exist.");
    }
    ReferenceType type = referenced.type();
    references.put(type, path.onlyInclude(ElementKind.BEAN));
  }
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
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 #9
Source File: CustomValueExtractorTest.java    From hibernate-demos with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUseCustomValueExtractoe() {
	Customer bean = new Customer();
	bean.emailsByType.put( "work", "[email protected]" );
	bean.emailsByType.put( "work", "not-an-email" );

	Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

	Set<ConstraintViolation<Customer>> violations = validator.validate (bean );
	assertEquals( 1, violations.size() );

	ConstraintViolation<Customer> violation = violations.iterator().next();
	assertEquals( "not-an-email", violation.getInvalidValue() );
	assertEquals( Email.class, violation.getConstraintDescriptor().getAnnotation().annotationType() );

	Iterator<Node> pathNodes = violation.getPropertyPath().iterator();
	assertTrue( pathNodes.hasNext() );

	Node node = pathNodes.next();
	assertEquals( "emailsByType", node.getName() );
	assertEquals( ElementKind.PROPERTY, node.getKind() );

	assertTrue( pathNodes.hasNext() );
	node = pathNodes.next();
	assertEquals( "<multimap value>", node.getName() );
	assertEquals( ElementKind.CONTAINER_ELEMENT, node.getKind() );
	assertEquals( "work", node.getKey() );

	assertFalse( pathNodes.hasNext() );
}
 
Example #10
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 #11
Source File: DescriptorPathImpl.java    From cm_ext with Apache License 2.0 5 votes vote down vote up
@Override
public boolean contains(String name, ElementKind kind) {
   for (DescriptorNodeImpl node : this.list) {
    if (kind.equals(node.getKind()) && node.getName().equals(name)) {
      return true;
    }
  }
  return false;
}
 
Example #12
Source File: DescriptorPathImpl.java    From cm_ext with Apache License 2.0 5 votes vote down vote up
@Override
public DescriptorPathImpl onlyInclude(ElementKind... whitelist) {
  Set<ElementKind> kinds = ImmutableSet.copyOf(whitelist);
  DescriptorPathImpl newPath = new DescriptorPathImpl();
  for (DescriptorNodeImpl node : this.list) {
    if (kinds.contains(node.getKind())) {
      newPath.list.add(node);
    }
  }
  return newPath;
}
 
Example #13
Source File: DescriptorPathImpl.java    From cm_ext with Apache License 2.0 5 votes vote down vote up
public BeanNode(String name,
                Object key,
                Object bean,
                boolean isNamed) {
  super(name, false, null, key, ElementKind.BEAN);
  this.isNamed = isNamed;
  this.bean = bean;
}
 
Example #14
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 #15
Source File: DescriptorPathImpl.java    From cm_ext with Apache License 2.0 5 votes vote down vote up
public DescriptorNodeImpl(String name,
                          boolean iterable,
                          Integer index,
                          Object key,
                          ElementKind kind) {
  this.name = name;
  this.iterable = iterable;
  this.index = index;
  this.key = key;
  this.kind = kind;
}
 
Example #16
Source File: ReferenceValidatorImpl.java    From cm_ext with Apache License 2.0 5 votes vote down vote up
private SetMultimap<ReferenceType, String> getRelatedPaths(Object obj, DescriptorPath path) {
  SetMultimap<ReferenceType, String> refs = LinkedHashMultimap.create();

  String additionalScope = "";
  IncludeAdditionalReferences scope = ReflectionHelper.findAnnotation(obj.getClass(), IncludeAdditionalReferences.class);
  if (scope != null) {
    additionalScope = ReflectionHelper.propertyValueByName(obj, scope.value(), String.class);
  }

  DescriptorPath trimmedPath = path.onlyInclude(ElementKind.BEAN);
  for (Map.Entry<ReferenceType, DescriptorPath> entry : allRefs.entries()) {
    DescriptorPath refPath = entry.getValue();
    DescriptorPath prefix = refPath.removeFromHead();
    if (trimmedPath.equals(prefix) || (refPath.contains(additionalScope, ElementKind.BEAN))) {
      DescriptorNode headNode = refPath.getHeadNode();
      boolean addedNames = false;
      if (ElementKind.BEAN.equals(headNode.getKind())) {
        Referenced referenced = ReflectionHelper.findAnnotation(
            ((BeanNode) headNode).getBean().getClass(), Referenced.class);
        if (null != referenced && referenced.as().length > 0) {
          for (String name : referenced.as()) {
            refs.put(entry.getKey(), name);
          }
          addedNames = true;
        }
      }
      if (!addedNames) {
        refs.put(entry.getKey(), headNode.getName());
      }
    }
  }
  return refs;
}
 
Example #17
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 #18
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 #19
Source File: AbstractMethodValidationInterceptor.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private String getMessage(Member member, Object[] args, Set<? extends ConstraintViolation<?>> violations) {

        StringBuilder message = new StringBuilder();
        message.append(violations.size());
        message.append(" constraint violation(s) occurred during method validation.");
        message.append("\nConstructor or Method: ");
        message.append(member);
        message.append("\nArgument values: ");
        message.append(Arrays.toString(args));
        message.append("\nConstraint violations: ");

        int i = 1;
        for (ConstraintViolation<?> constraintViolation : violations) {
            Path.Node leafNode = getLeafNode(constraintViolation);

            message.append("\n (");
            message.append(i);
            message.append(")");
            message.append(" Kind: ");
            message.append(leafNode.getKind());
            if (leafNode.getKind() == ElementKind.PARAMETER) {
                message.append("\n parameter index: ");
                message.append(leafNode.as(Path.ParameterNode.class).getParameterIndex());
            }
            message.append("\n message: ");
            message.append(constraintViolation.getMessage());
            message.append("\n root bean: ");
            message.append(constraintViolation.getRootBean());
            message.append("\n property path: ");
            message.append(constraintViolation.getPropertyPath());
            message.append("\n constraint: ");
            message.append(constraintViolation.getConstraintDescriptor().getAnnotation());

            i++;
        }

        return message.toString();
    }
 
Example #20
Source File: ConstraintTypeUtil20.java    From quarkus with Apache License 2.0 5 votes vote down vote up
@Override
public ConstraintType.Type getConstraintType(Object o) {
    if (!(o instanceof ConstraintViolation)) {
        throw new RuntimeException(Messages.MESSAGES.unknownObjectPassedAsConstraintViolation(o));
    }
    ConstraintViolation<?> v = ConstraintViolation.class.cast(o);

    Iterator<Node> nodes = v.getPropertyPath().iterator();
    Node firstNode = nodes.next();

    switch (firstNode.getKind()) {
        case BEAN:
            return ConstraintType.Type.CLASS;
        case CONSTRUCTOR:
        case METHOD:
            Node secondNode = nodes.next();

            if (secondNode.getKind() == ElementKind.PARAMETER || secondNode.getKind() == ElementKind.CROSS_PARAMETER) {
                return ConstraintType.Type.PARAMETER;
            } else if (secondNode.getKind() == ElementKind.RETURN_VALUE) {
                return ConstraintType.Type.RETURN_VALUE;
            } else {
                throw new RuntimeException(Messages.MESSAGES.unexpectedPathNodeViolation(secondNode.getKind()));
            }
        case PROPERTY:
            return ConstraintType.Type.PROPERTY;
        case CROSS_PARAMETER:
        case PARAMETER:
        case RETURN_VALUE:
        case CONTAINER_ELEMENT: // we shouldn't encounter these element types at the root
        default:
            throw new RuntimeException(Messages.MESSAGES.unexpectedPathNode(firstNode.getKind()));
    }
}
 
Example #21
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 #22
Source File: ConstraintViolationExceptionMapper.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Translate validated bean and root path into validated resource and
 * resource path. For example, embeddables belonging to an entity document
 * are mapped back to an entity violation and a proper path to the
 * embeddable attribute.
 *
 * @param violation to compute the reference
 * @return computaed reference
 */
private ResourceRef resolvePath(ConstraintViolation<?> violation) {
	Object resource = violation.getRootBean();

	Object nodeObject = resource;
	ResourceRef ref = new ResourceRef(resource);

	Iterator<Node> iterator = violation.getPropertyPath().iterator();
	while (iterator.hasNext()) {
		Node node = iterator.next();

		// ignore methods/parameters
		if (node.getKind() == ElementKind.METHOD) {
			continue;
		}
		if (node.getKind() == ElementKind.PARAMETER) {
			resource = getParameterValue(node);
			nodeObject = resource;
			ref = new ResourceRef(resource);
			assertResource(resource);
			continue;
		}

		// visit list, set, map references
		nodeObject = ref.getNodeReference(nodeObject, node);
		ref.visitNode(nodeObject);

		// visit property
		nodeObject = ref.visitProperty(nodeObject, node);
	}

	return ref;
}
 
Example #23
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 #24
Source File: ConstraintViolationExceptionMapper.java    From microservices-springboot with MIT License 5 votes vote down vote up
/**
 * Handle an invalid parameter. Can be:
 * <p>
 * 1. Invalid request parameter (annotated method parameter)
 * 2. Invalid request entity (annotated method parameter)
 *
 * @param constraintViolation
 */
private ValidationError handleInvalidParameter(ConstraintViolation constraintViolation) {

    List<Path.Node> nodes = new ArrayList<>();
    constraintViolation.getPropertyPath().iterator().forEachRemaining(nodes::add);

    Path.Node parent = nodes.get(nodes.size() - 2);
    Path.Node child = nodes.get(nodes.size() - 1);

    if (ElementKind.METHOD == parent.getKind()) {

        Path.MethodNode methodNode = parent.as(Path.MethodNode.class);
        Path.ParameterNode parameterNode = child.as(Path.ParameterNode.class);

        try {

            // Can be an invalid request parameter (annotated method parameter)
            Class<?> beanClass = constraintViolation.getLeafBean().getClass();
            Method method = beanClass.getMethod(methodNode.getName(), methodNode.getParameterTypes().stream().toArray(Class[]::new));
            Annotation[] annotations = method.getParameterAnnotations()[parameterNode.getParameterIndex()];
            Optional<ParameterDetails> optionalParameterDetails = getParameterDetails(annotations);
            if (optionalParameterDetails.isPresent()) {
                return createErrorForParameter(optionalParameterDetails.get(), constraintViolation);
            }

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }

        // Assumes that the request entity is invalid (annotated method parameter)
        ValidationError error = new ValidationError();
        error.setType(REQUEST_ENTITY);
        error.setMessage(constraintViolation.getMessage());
        return error;
    }

    return handleUnknownSource(constraintViolation);
}
 
Example #25
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 #26
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 #27
Source File: ReferenceConstraintViolation.java    From cm_ext with Apache License 2.0 4 votes vote down vote up
@Override
public Path getPropertyPath() {
  return propertyPath.onlyInclude(ElementKind.PROPERTY);
}
 
Example #28
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 #29
Source File: DescriptorPathImpl.java    From cm_ext with Apache License 2.0 4 votes vote down vote up
@Override
public ElementKind getKind() {
  return this.kind;
}
 
Example #30
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, ", ");
}