Quarkus - Validation with Hibernate Validator

    • validating the input/output of your REST services;

    • validating the parameters and return values of the methods of your business services.

    To complete this guide, you need:

    • less than 15 minutes

    • an IDE

    • JDK 1.8+ installed with configured appropriately

    • Apache Maven 3.5.3+

    Architecture

    The application built in this guide is quite simple. The user fills a form on a web page.The web page sends the form content to the BookResource as JSON (using Ajax). The BookResource validates the user input and returns theresult as JSON.

    Solution

    We recommend that you follow the instructions in the next sections and create the application step by step.However, you can go right to the completed example.

    Clone the Git repository: git clone https://github.com/quarkusio/quarkus-quickstarts.git, or download an .

    The solution is located in the validation-quickstart directory.

    Creating the Maven project

    First, we need a new project. Create a new project with the following command:

    This command generates a Maven structure importing the RESTEasy/JAX-RS, JSON-B and Hibernate Validator/Bean Validation extensions.

    Edit the org.acme.validation.BookResource class, and inject the Validator object as follows:

    1. @Inject
    2. Validator validator;

    The Validator allows checking constraints on a specific object.

    Constraints

    In this application, we are going to test an elementary object, but we support complicated constraints and can validate graphs of objects.Create the org.acme.validation.Book class with the following content:

    1. package org.acme.validation;
    2. import javax.validation.constraints.*;
    3. public class Book {
    4. @NotBlank(message="Title may not be blank")
    5. public String title;
    6. @NotBlank(message="Author may not be blank")
    7. public String author;
    8. @Min(message="Author has been very lazy", value=1)
    9. public double pages;
    10. }

    Constraints are added on fields, and when an object is validated, the values are checked.The getter and setter methods are also used for JSON mapping.

    JSON mapping and validation

    Yes it does not compile, Result is missing, but we will add it very soon.

    The method parameter (book) is created from the JSON payload automatically.

    The method uses the Validator to check the payload.It returns a set of violations.If this set is empty, it means the object is valid.In case of failures, the messages are concatenated and sent back to the browser.

    Let’s now create the Result class as an inner class:

    1. private class Result {
    2. Result(String message) {
    3. this.success = true;
    4. this.message = message;
    5. Result(Set<? extends ConstraintViolation<?>> violations) {
    6. this.success = false;
    7. this.message = violations.stream()
    8. .map(cv -> cv.getMessage())
    9. .collect(Collectors.joining(", "));
    10. }
    11. private String message;
    12. private boolean success;
    13. public String getMessage() {
    14. return message;
    15. }
    16. public boolean isSuccess() {
    17. return success;
    18. }

    The class is very simple and only contains 2 fields and the associated getters and setters.Because we indicate that we produce JSON, the mapping to JSON is made automatically.

    REST end point validation

    While using the Validator manually might be useful for some advanced usage,if you simply want to validate the parameters or the return value or your REST end point,you can annotate it directly, either with constraints (@NotNull, @Digits…​)or with @Valid (which will cascade the validation to the bean).

    Let’s create an end point validating the Book provided in the request:

    1. @Path("/end-point-method-validation")
    2. @POST
    3. @Produces(MediaType.APPLICATION_JSON)
    4. @Consumes(MediaType.APPLICATION_JSON)
    5. public Result tryMeEndPointMethodValidation(@Valid Book book) {
    6. return new Result("Book is valid! It was validated by end point method validation.");
    7. }

    As you can see, we don’t have to manually validate the provided Book anymore as it is automatically validated.

    If a validation error is triggered, a violation report is generated and serialized as JSON as our end point produces a JSON output.It can be extracted and manipulated to display a proper error message.

    It might not always be handy to have the validation rules declared at the end point level as it could duplicate some business validation.

    The best option is then to annotate a method of your business service with your constraints (or in our particular case with @Valid):

    Calling the service in your rest end point triggers the Book validation automatically:

    1. @Path("/service-method-validation")
    2. @POST
    3. @Produces(MediaType.APPLICATION_JSON)
    4. @Consumes(MediaType.APPLICATION_JSON)
    5. public Result tryMeServiceMethodValidation(Book book) {
    6. try {
    7. bookService.validateBook(book);
    8. return new Result("Book is valid! It was validated by service method validation.");
    9. } catch (ConstraintViolationException e) {
    10. return new Result(e.getConstraintViolations());
    11. }
    12. }

    Note that, if you want to push the validation errors to the frontend, you have to catch the exception and push the information yourselvesas they will not be automatically pushed to the JSON output.

    Keep in mind that you usually don’t want to expose to the public the internals of your services- and especially not the validated value contained in the violation object.

    A frontend

    Now let’s add the simple web page to interact with our BookResource.Quarkus automatically serves static resources contained in the META-INF/resources directory.In the src/main/resources/META-INF/resources directory, replace the index.html file with the content from this index.html file in it.

    Run the application

    Now, let’s see our application in action. Run it with:

    1. ./mvnw compile quarkus:dev

    Then, open your browser to http://localhost:8080/:

    • Enter the book details (valid or invalid)

    Application

    As usual, the application can be packaged using ./mvnw clean package and executed using the -runner.jar file.You can also build the native executable using ./mvnw package -Pnative.

    Going further

    The Hibernate Validator extension is tightly integrated with CDI.

    Configuring the ValidatorFactory

    Sometimes, you might need to configure the behavior of the ValidatorFactory, for instance to use a specific ParameterNameProvider.

    While the ValidatorFactory is instantiated by Quarkus itself,you can very easily tweak it by declaring replacement beans that will be injected in the configuration.

    If you create a bean of the following types in your application, it will automatically be injected into the ValidatorFactory configuration:

    • javax.validation.ClockProvider

    • javax.validation.ConstraintValidator

    • javax.validation.ConstraintValidatorFactory

    • javax.validation.MessageInterpolator

    • javax.validation.ParameterNameProvider

    • javax.validation.TraversableResolver

    • org.hibernate.validator.spi.properties.GetterPropertySelectionStrategy

    You don’t have to wire anything.

    Constraint validators as beans

    You can declare your constraint validators as CDI beans:

    When initializing a constraint validator of a given type,Quarkus will check if a bean of this type is available and, if so, it will use it instead of instantiating one.

    Thus, as demonstrated in our example, you can fully use injection in your constraint validator beans.

    Except in very specific situations, it is recommended to make the said beans @ApplicationScoped.