Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out whether a ConstraintViolation is from a JSON property or from a URL parameter?

I have a code that gets data from the user and validates rather it's valid or not.

The validation is for the data from the URL and the data from the JSON.

The problem is that in case of URL the path field contains arg0 and that it requires me to take it from the message:

@ValidId (message = "The field is invalid")
private Long field;

annotation of the field.

In case of JSON, I simply can get the field from the path.substring(path.lastIndexOf('.') + 1).

i.e.

protected String buildErrorMessage(ConstraintViolation<?> violation) {
    String path = violation.getPropertyPath().toString();
    String field = path.substring(path.lastIndexOf('.') + 1);
    //field = `arg0` in case of url
    //field = `field` in case of JSON
}

If I'm facing a ConstraintViolation - how can I find out if the violation is from JSON or GET?


EDIT

This is where I call the buildErrorMessage from -

public class ValidationExceptionMapper implements ExceptionMapper<ValidationException> {

    @Override
    public Response toResponse(ValidationException exception) {

        if (exception instanceof ConstraintViolationException) {

            final ConstraintViolationException constraint = (ConstraintViolationException) exception;

            for (final ConstraintViolation<?> violation : constraint.getConstraintViolations()) {
                String message = buildErrorMessage(violation); //HERE
            }
}
like image 447
Dvir Avatar asked May 08 '18 11:05

Dvir


1 Answers

Here are some steps that can be helpful when implementing an ExceptionMapper to check whether the ConstraintViolation is related to an invalid parameter sent in the URL or related to an invalid property sent in the JSON payload:

  • Retrieve the property Path from the ConstraintViolation using the getPropertyPath() method;
  • Find the leaf Node from the property Path;
  • Check the Node kind using the getKind() method.
  • Handle it accordingly.

Bear in mind that parameter annotations such as @QueryParam, @PathParam and @MatrixParam can be placed in method parameter, resource class field, or resource class bean property.


I would recommend you to look at my implementation of ExceptionMapper for ConstraintViolationException available in GitHub.

like image 166
cassiomolin Avatar answered Sep 24 '22 05:09

cassiomolin