Search code examples
javajax-rsbean-validationhibernate-validator

Hibernate validator executing JAX-RS REST end point even on constraint violation


I am using Hibernate validator 5.x and javax validation 1.x(due to some reasons, can not upgrade). This scenario works in hibernate validator 6.x and validation 2.x

On constraint violation, Validator kicks in and shows proper error response, But at the same time it executes the REST method body.

REST Endpoint

@POST
    @Path("/book")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response createBook(@Valid Book book) {
        System.out.println("Book "+book);
        return Response.status(Response.Status.OK).entity(book).build();
    }

BOOK

@ValidName
public class Book {

    private String name;
    private Author author;
    private double price;

    public Book() {
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Author getAuthor() {
        return author;
    }
    public void setAuthor( Author author) {
        this.author = author;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }

}

@ValidName

@Constraint(validatedBy = { NameValidator.class })
@Target({ METHOD, FIELD, PARAMETER, TYPE })
@Retention(RUNTIME)
public @interface ValidName {
    String message() default "Author name is mandatory";

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

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

NameValidator

@Provider
public class NameValidator implements ConstraintValidator<ValidName, Book>{

    @Override
    public boolean isValid(Book book, ConstraintValidatorContext context) {
        if(book == null) return true;

        if(book.getName().equals("")) {
            return true;
        }else {
            return !(book.getAuthor().getName().equals(""));
        }
    }
}

console output

12:53:31,971 INFO  [stdout] (default task-1) Book com.arfat.entity.Book@3238e1e1

postman output

{
    "data": {},
    "messages": [
        "1. Author name is mandatory"
    ],
    "status": "ERROR-Bad Request"
}

I am using same scenario for more complex case, where service and DOA layer is involved. Validator not stopping the execution for validation and my back-end is updated with un-clean data before validation

I searched the official docs but not help.


Solution

  • There is a jar in classpath which is handling sessionContext. It has @Stateless annotation on it. For some reason, it is allowing the validation to bypass.I can not remove this jar as it is needed for web app and I am deploying the Reast-easy on same path. So need to find out a work around