DropWizard @ValidationMethod Change property name

1k Views Asked by At

I have a Representation in Dropwizard which has methods with the annotation @ValidationMethod.

Dropwizard example:

@ValidationMethod(message="may not be Coda")
public boolean isNotCoda() {
return !("Coda".equals(name));
}

Please note that the method must begin with "is". This is a limitation of Hibernate Validator.

My Example:

@NotBlank(message = REQUIRED)
private String password;


@JsonIgnore
@ValidationMethod(message = "the password fields must match")
public boolean isPasswordEqualRepeatedPassword() {
    
}

@JsonIgnore
@ValidationMethod(message = "the password must not contain or be equal to the username")
public boolean isNotEqualOrContainUsername(){

}

Current Response:

"field" : "PasswordEqualRepeatedPassword", "message" = "the password fields must match"

"field" : "NotEqualOrContainUsername", "message" = "the password must not contain or be equal to the username"

I want the field to be equal to password like the class attribute. The problem is that i can not name the methods to isPassword() to get the following response:

"field" : "password", "message" = "the password fields must match"

"field" : "password", "message" = "the password must not contain or be equal to the username"

Is there a way to do this?

1

There are 1 best solutions below

0
On

This is doable, unfortunately, by reimplementing a lot of what dropwizard has implemented. We needed to return custom objects on error and also there were other shortcomings so went into some reflection rabbit hole. We implemented it long ago though, so it might be easier now, so I'll just share the relevant bits to accomplish this.

For this specific issue, we did a workaround by adding a custom string format to validation messages.

  @ValidationMethod(message = "[password]the password fields must match")

And then when we parse the message, we grab the "password" field.

First, we handle validation errors ourselves by implementing an exception mapper.

public class UnprocessableEntityExceptionMapper implements ExceptionMapper<ConstraintViolationException> {

  @Override
  public Response toResponse(ConstraintViolationException exception) {
    return Response
        .status(422)
        .entity(doMagic(exception))
        .type(MediaType.APPLICATION_JSON_TYPE)
        .build();
  }
}

doMagic is the potential rabbit hole but I recommend trying things out and debugging there and then return an object which will represent your error in JSON. Relevant bits:

  • exception.getConstraintViolations() will return a list of violations to work on.
  • constraintViolation.getConstraintDescriptor().getAnnotation() instanceof ValidationMethod is how you know it's a dropwizard ValidationMethod.
  • constraintViolation.getMessage() will return "[password]the password fields must match" in this example.