loading...

Apache Camel #4 - Bean Validation

djoleb profile image Djordje Bajic ・1 min read

There is a lot of cases where we needed to write validation for data input. This "problem" can be easily solved in Camel by using Bean Validation component.

Imagine we have a JSON input in our route and we want to validate payload.

{
     "name":"Jane Doe",
     "cardNumber":"377198642272436",
     "email":"jane@doe.com",
     "paid":true,
     "price":1.25
}

To do that, we first we must unmarshall that payload to POJO.
But first, we must create a class with the same parameters as JSON and add Hibernate Validation annotations.

 @NotNull
 @Length(min = 1, max = 60)
 private String name;

 @CreditCardNumber
 private String cardNumber;

 @Email
 private String email;

 @NotNull
 private boolean paid;

 @Min(0.1)
 private int price;

And then we add this to our Camel route.

   //define a datasource for the class you want to validate.
   GsonDataSource dataSource = new GsonDatasource(JsonDto.class);

   //unmarshal JSON to POJO
   .unmarshall(dataSource)

   //Validate data
   .to("bean-validator:someLabelHere)

When that unmarshalled data is sent to bean validator, that objects will be validated by annotations we set for JsonDto fields.

Thank you for your attention.

Posted on by:

djoleb profile

Djordje Bajic

@djoleb

Java backend engineer @ Humanity inc.

Discussion

pic
Editor guide