8

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
            }
}
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
Dvir
  • 301
  • 1
  • 2
  • 16
  • you can try to call the URL from the web browser first. ensure that the JSON is correct before you start using it in your codes. – Angel Koh May 09 '18 at 04:50
  • Actually, I talking about finding out during an ordinary run. not testing. I want to see how to find out only with the code. – Dvir May 09 '18 at 05:24
  • 1
    Can you please share a bit more of code and tag your question accordingly to the technologies you are using? Is it Spring MVC? JAX-RS? – cassiomolin May 14 '18 at 08:15
  • As Cassio suggests please add more details and proper steps-to-reproduce if you want your question answered. – Mick Mnemonic May 15 '18 at 09:00
  • @CassioMazzochiMolin Done. – Dvir May 16 '18 at 04:47

3 Answers3

7

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:

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.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • Indeed - the `URL` has PARAMETER as a kind and the `JSON` has PROPERTY – Dvir May 17 '18 at 12:59
  • @Dvir As I mentioned in my answer, just be aware that parameter annotations such as `@QueryParam`, `@PathParam` and `@MatrixParam` can be placed in method parameter, resource class field, or resource class bean property. – cassiomolin May 17 '18 at 13:18
0

By GET you mean TEXT, since GET is a Type of HTTP request you send and JSON/TEXT.... is the type/format of data that you are sending to the server.

You can use the below piece of code

 String contentType = request.getContentType();
          if (contentType != null && !contentType.toLowerCase(Locale.US).startsWith(MediaType.APPLICATION_JSON)) {
           //Request is JSON type
          }
    else {
    //Request is TEXT 
    }

It checks the ContentType of the request, if it is JSON or TEXT

rohit thomas
  • 2,302
  • 11
  • 23
0

If you used spring, you can get current request in static method, and check it type.

public static HttpServletRequest getCurrentHttpRequest(){
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes instanceof ServletRequestAttributes) {
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        return request;
    }
    logger.debug("Not called in the context of an HTTP request");
    return null;
}

 if(getCurrentHttpRequest().getMethod().toLowerCase()=='get'){
     // text
 }
ahll
  • 2,329
  • 1
  • 19
  • 22
  • How does it answer the question? – cassiomolin May 17 '18 at 11:31
  • In ValidationExceptionMapper , get CurrentHttpRequest, and check if is http get method. Because the post o put will receive json in body. – ahll May 17 '18 at 12:07
  • Once the OP is using JAX-RS and assuming the application is deployed to a servlet container, they could simply inject the `HttpServletRequest` in the `ExceptionMapper` using `@Context` (see this [answer](https://stackoverflow.com/a/35868654/1426227)). But that's not the point here. The point is to parse the `ConstraintViolation` to check whether there's a validation error in parameter sent in the URL or there's a validation error in a property sent in the JSON payload. See my [answer](https://stackoverflow.com/a/50365829/1426227) for details. – cassiomolin May 17 '18 at 12:13
  • A possible implementation for parsing the `ContraintViolation` is available [here](https://github.com/cassiomolin/tasks-rest-api/blob/908d34e148612f0fed9e07827bf9ae6affc05749/src/main/java/com/cassiomolin/example/common/api/exceptionmapper/ConstraintViolationExceptionMapper.java). – cassiomolin May 17 '18 at 12:17
  • Yes, you are right. If the kind of ContraintViolation is in the exception, wo donot require aditional information. – ahll May 17 '18 at 14:47