Is a common code practice in our microservices to have a lot of If’s blocks to validate if some values are null, or if the have the right size, the dates are correct, etc. then the developer needs to inform the user that something went wrong and 50% of our code are those validations.

Fortunately within the JavaEE/JakartaEE API’s there is Bean Validation that allows the developer to reduce all of that validation code in a declarative way using annotations and can be used along with MicroProfile to write better microservices that not only informs the users that something went wrong but also let them know how to fix it.

All the code used in this post can be found at this repository:

https://github.com/Motojo/MicroProfile-BeanValidation

Integrating Bean Validation in our project

To integrate Bean Validation in our project is enough to add the dependency to all the JavaEE/JakartaEE APi’s or just the Bean Validation one.

  1. dependencies {
  2. /*--- Full JavaEE dependency or just javax.validation dependency ---*/
  3. /* providedCompile group: 'javax', name: 'javaee-api', version: '8.0' */
  4. providedCompile group: 'javax.validation', name: 'validation-api', version: '2.0.1.Final'
  5. providedCompile group: 'org.eclipse.microprofile', name: 'microprofile', version: '2.1'
  6. }

Example using Gradle

Then the developer can start using the Bean Validation annotations on any POJO, for example:

  • @NotNull: Verifies that the value is not null.
  • @AssertTrue: Verifies that the value is true.
  • @Size: Verifies that the size of the value is between the min and max specified, can be used with Strings, Maps, Collections and Arrays. 
  • @Min:  Verifies that the numeric value is equal or greater than the specified value.
  • @Max: Verifies that the numeric value is equal or lower than the specified value..
  • @Email: Verifies that the value is a valid email.
  • @NotEmpty:Verifies that the value is not empu, applies to Strings, Collections, Maps and Arrays.
  • @NotBlank:Verifies that the text is not whitespaces.
  • @Positive / @PositiveOrZero: Verifies that the numeric value is positive including or not the zero.
  • @Negative / @NegativeOrZero: Verifies that the numeric value is negative including or not the zero.
  • @Past / @PastOrPresent:  Verifies that the date is in the past including or not the present.
  • @Future / @FutureOrPresent:  Verifies that the date is in the future including or not the present.

And can be used like this:

  1. public class Book
  2. {
  3. private Long id;
  4.  
  5. @NotNull
  6. @Size(min = 6)
  7. private String name;
  8.  
  9. @NotNull
  10. private String author;
  11.  
  12. @Min(6)
  13. @Max(200)
  14. @NotNull
  15. private Integer pages;
  16. }

Example of annotated POJO with validations

Integrating Bean Validation with JAX-RS

When Bean Validation is integrated in the project and POJOS are annotated is time to tell to JAX-RS endpoints to make or not  the validations using the annotation @Valid like this:

  1. @POST
  2. public Book createBook(@Valid Book book)
  3. {
  4. //Do something like saving to DB and then return the book with a new ID
  5. book.setId(20L);
  6. return book;
  7. }

Example of JAX-RS endpoint annotated  to validate the Book Object

When calling the service all the validation on the Book objects will be executed and an error will be returned if something went wrong or if everything is ok the service code will be executed.

 

Web Service executed successfully

Web Service with error (name not sent)

Better error management

As can be seen in the previous image, when there is an error the service code was not executed and the standard error response of the server is sent, but this is not very useful at all and can be a cause of more errors if the client expects that all the responses will be returned in JSON format.

To improve the error responses and let the user know what happened an interceptor of type ExceptionMapper<ConstraintViolationException> can be written to transform the standard response into JSON and add more useful information to it.

  1. @Provider
  2. public class ValidationExceptionMapper implements ExceptionMapper<ConstraintViolationException>
  3. {
  4. private String getPropertyName(Path path)
  5. {
  6. //The path has the form of com.package.class.property
  7. //Split the path by the dot (.) and take the last segment.
  8. String[] split = path.toString().split("\\.");
  9. return split[split.length - 1];
  10. }
  11.  
  12. @Override
  13. public Response toResponse(ConstraintViolationException exception)
  14. {
  15. Map<String, String> errors = exception.getConstraintViolations().stream()
  16. .collect(Collectors.toMap(v -> getPropertyName(v.getPropertyPath()), ConstraintViolation::getMessage));
  17.  
  18. return Response.status(Response.Status.BAD_REQUEST)
  19. .entity(errors).type(MediaType.APPLICATION_JSON)
  20. .build();
  21. }
  22. }

Exception mapper to transform the error response.

Once the exception mapper is registered using the @Provider annotation and calling the service if there is an error a response like this will be returned:

WebService with a JSON  error report with details

Query, Path and Header Params

Bean Validation is not limited to be used in request objects, also can be used on Query, Path and Header params like this:

  1. @GET
  2. public Book getBook(@Valid @NotNull @QueryParam("id") Long id)
  3. {
  4. //Just build a dummy book to return
  5. Book book = new Book();
  6. book.setId(id);
  7. book.setAuthor("Jorge Cajas");
  8. book.setPages(100);
  9.  
  10. return book;
  11. }

But calling this service, at the error response we can be note that the ExceptionMapper previously written is not useful at all because the parameter name was not resolved.

The id parameter name was not resolved

To fix this Bean Validation must be configured in a way it knows how to resolve the JAX-RS method’s parameter names.

The validation.xml is used to configure various aspects of Bean Validation and must be placed at resources/META-INF directory. On this file we will use the <parameter-name-provider> property with a reference to a class that will be responsible to resolve the JAX-RS parameter names.

  1. <validation-config xmlns="http://jboss.org/xml/ns/javax/validation/configuration" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration validation-configuration-1.1.xsd" version="1.1">
  3.  
  4. <parameter-name-provider>com.demo.validations.CustomParameterNameProvider</parameter-name-provider>
  5.  
  6. </validation-config>

resources/META-INF/validation.xml

 

The class CustomParameterNameProvider will inspect the JAX-RS methods and from the annotations of Query, Path or Header params will complete the necessary information in order to resolve correctly the parameter names on the Exception Mapper previously written.

  1. public class CustomParameterNameProvider implements ParameterNameProvider
  2. {
  3. @Override
  4. public List<String> getParameterNames(Constructor<?> constructor){
  5. return lookupParameterNames(constructor.getParameterAnnotations());
  6. }
  7.  
  8. @Override
  9. public List<String> getParameterNames(Method method) {
  10. return lookupParameterNames(method.getParameterAnnotations());
  11. }
  12.  
  13. private List<String> lookupParameterNames(Annotation[][] annotations) {
  14. final List<String> names = new ArrayList<>();
  15. if (annotations != null) {
  16. for (Annotation[] annotation : annotations) {
  17. String annotationValue = null;
  18. for (Annotation ann : annotation) {
  19. annotationValue = getAnnotationValue(ann);
  20. if (annotationValue != null) {
  21. break;
  22. }
  23. }
  24. // if no matching annotation, must be the request body
  25. if (annotationValue == null) {
  26. annotationValue = "requestBody";
  27. }
  28. names.add(annotationValue);
  29. }
  30. }
  31. return names;
  32. }
  33.  
  34. private static String getAnnotationValue(Annotation annotation) {
  35. if (annotation instanceof HeaderParam) { return ((HeaderParam) annotation).value(); }
  36. else if (annotation instanceof PathParam) { return ((PathParam) annotation).value(); }
  37. else if (annotation instanceof QueryParam) { return ((QueryParam) annotation).value(); }
  38. return null;
  39. }
  40. }

CustomParameterNameProvider.java

 

Once Bean Validation is configured, a call to the service with error will be like this:

Id query param name resolver correctly

Jorge Cajas

Author Jorge Cajas

More posts by Jorge Cajas

Leave a Reply