简体   繁体   中英

How do I use a custom validator with dropwizard?

I have a REST api written by someone else in which the method that handles the request to a particular url accepts a bunch of parameters that are populated from path parameters.

@POST
@Path("/{classid}/{studentid}/details")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@SuppressWarnings("unchecked")


public Response processFile(@FormDataParam("sourceFile") InputStream aStream, @PathParam("classid") String classId, @PathParam("studentid")  String studentId, @Context HttpServletRequest httpRequest) {

// Code to do stuff and return a response
}

The person who wrote this has used DropWizard and I have no previous experience working on it. I have the task of validating the studentId field by comparing it with values in the db. This would be pretty straightforward but I have been told to do it using a custom validator. I am pretty new to writing annotations but after much digging wrote an annotation like this,

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = StudentIdValidator.StudentIdValidation.class)

public @interface StudentIdValidator {

    String message() default "{Invalid Id}";

      Class<?>[] groups() default {};

      Class<? extends Payload>[] payload() default {};


      class StudentIdValidation implements ConstraintValidator<StudentIdValidator, String> {

        @Override
        public void initialize(StudentIdValidator constraintAnnotation) {
            System.out.println("Annotation initialize !!!!!!!!!");
        }


        @Override
        public boolean isValid(String value, ConstraintValidatorContext context)                                                                            {
                // TODO Auto-generated method stub
                System.out.println("Annotation called");
                return false;
            }
        }
    }

After this I added the annotation to the field I wanted to run the validation on like this,

public Response processFile(@FormDataParam("sourceFile") InputStream     aStream, @PathParam("classid") String classId, @StudentIdValidator     @PathParam("studentid")  String studentId, @Context HttpServletRequest     httpRequest)

Now the problem is that, when the I run/debug the code...this validator is not being called, also I have no idea how to get the value of studentId inside the studentId validation class. So I dug some more and added this to the application file

class MyApplication extends Application<MyConfiguration> {
    ........

    @Override
   public void run(MyConfiguration myConfiguration, Environment                     currentEnvironment) {

     currentEnvironment.jersey().register(StudentIdValidator.class);

    }

I am literally at the end of my wits. Any help will be very VERY appreciated. Sorry about the poor formatting.

this is pretty straight forward. I will paste my example here since I had it written up and I am lazy and don't want to take your fun experience away :)

Edit: I think your issue is that you didn't annotate your resource with @Valid

so here we go:

You are on the right track with the validator. These are mine:

public class CustomValidator implements ConstraintValidator<CustomValidation, String> {

    @Override
    public void initialize(CustomValidation constraintAnnotation) {

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {

        System.out.println("Validation called");

        return false;
    }

}

And this is the Annotation:

@Constraint(validatedBy = {CustomValidator.class})
@Target({ElementType.FIELD, ElementType.PARAMETER})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface CustomValidation {


      String message() default "Some message";

      Class<?>[] groups() default {};
      Class<? extends Payload>[] payload() default {};
}

The application:

public class Application extends io.dropwizard.Application<Configuration>{

    @Override
    public void run(Configuration configuration, Environment environment) throws Exception {
        MetricRegistry metrics = environment.metrics();
        environment.jersey().register(new HelloResource(metrics));

    }

    public static void main(String[] args) throws Exception {
        new Application().run("server", "/home/artur/dev/repo/sandbox/src/main/resources/config/test.yaml");
    }
}

And the resource:

@Path("/test")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class HelloResource {

    private MetricRegistry service;

    public HelloResource(MetricRegistry service) {
        this.service = service;
    }

    @GET
    public String hello() {

        Timer timer = service.timer("test");

        try(Context t = timer.time()) {
            return "Hello World";
        }

    }


    @GET
    @Path("/test2")
    public void test(@Valid @CustomValidation @QueryParam("arg") String test) {
        System.out.println(test);
    }
}

Don't mind the metrics, they have nothing to do with it. The important part is that you need to tell DW what you want to have validated.

In the resource, see the test method. I annotate the argument I need with @Valid (tells DW to validate) @CustomValidation (tells DW what validator to use).

This is not actually a Dropwizard feature, but rather a hibernate validator implementation.

The way it works under the hood is that hibernate creates the Validator class on the fly when requested by invoking the constructor. Now this works very fine if you have simple validation (like say comparing a string). If you need dependencies, then it gets slightly more tricky. I have an example for that as well, that you can read up on here:

With dropwizard validation, can I access the DB to insert a record

This example uses guice, but it demonstrates how you can hook your own creation mechanism into validation. That way you can control your validator creation and inject or initialise them with a datasource to access your database.

I hope that answers your questions,

Artur

Custom valdation in drop wizard are same as hibernate custom validators.

Follow the link : hibernate validator-customconstraints

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM