Search code examples
javajerseyjax-rsbean-validationhibernate-validator

@ConvertGroup based on parameter


I'm looking to implement bean validation with groups based on parameter. The idea is to have methods with signature like:

@POST
@Path("/id-{id}")
public SomeDTO updateProducer(@PathParam("id") String id, @MatrixParam("update") Class<ConvertGroupTarget> update, @Valid SomeDTO data);

This would serve as an equivalent of explicit ConvertGroup declaration, such as:

@POST
@Path("/id-{id}")
public SomeDTO updateProducer(@PathParam("id") String id, @Valid @ConvertGroup(from=Default.class, to=/*some class that implements ConvertGroupTarget*/) SomeDTO data);

Is this even possible at all? We're using Jersey with hibernate-validator.

EDIT: the purpose of this all. Say I want to validate beans based on some validation group for specific purposes. For example, some bean can have different rules that apply to creating and updating it. So the bean declaration looks like this:

class SomeDTO {
    @NotNull(groups = {Create.class, Update.class})
    private String id;

    @NotNull(groups = {Create.class, Update.class})
    private String name;

    @NotNull(groups = Update.class)
    private String something;

    //getters, setters etc.
}

The classes Create and Update are just some marker classes/interfaces to provide typed declaration of the groups.

Now, say the API user is creating an entity and he does POST /id-X123/;update=create. Here I just want to validate the ID and the name, but don't really care about the something property of the bean. But when API user wants to update the bean, the API should require that he specifies even the something property. This is normally done by converting the validation group - @ConvertGroup(from = Default.class, to = Create.class) for creating and @CovertGroup(from = Default.class, to = Update.class) for updating. However, I'm looking to skip the explicit declaration of a ConvertGroup annotation and do this programatically based on parameter.


Solution

  • ConvertGroup defines static group conversions so you won't have the ability to parameterize them. You define them once and for all.

    I think what you want to do is to call the Validator with a group. I don't use Jersey so I don't know if they have a hook for it but what you should look for is this:

    Set<ConstraintViolation<SomeDTO>> violations =
        validator.validate(someDTO); // validate the default group
    
    Set<ConstraintViolation<SomeDTO>> violations =
        validator.validate(someDTO, Update.class); // validate the Update group