Thursday, October 8, 2015

How to implement Hibernate Bean Validations with Jersey2

When to use??

When we need to validate the properties of a bean class (eg:max length, not null , etc) we can simple use Hibernate Bean Validations


Bean Class

import javax.validation.constraints.Size;
import javax.validation.constraints.NotNull;

public class UserDTO {
  private int userId;
  @Size(min = 1, max=50)
  private String userName;

  public int getUseId() {
    return this.userId;

  public void setUseId(int userId) {
    this.userId = userId;

  public String getUseName() {
    return this. userName;

  public void setUserName(String userName) {
    this.userId = userName;

Service Class

import javax.validation.Valid;

public Response createUser(@Valid UserDTO userDTO) {
  //validate UserDTO bean

  //Rest of the logic goes here

@Valid - This annotation used to specify that we need to validate this bean.

Validation Engine Call

Annotation is not just enough and below code needs to be executed to call to hibernate Validation engine.

public void validateBean(Object object) throws ValidationException {
  if (object == null) {
    throw new ValidationException("Payload cannot be null");
  //contains internal error message
  StringBuilder internalErrMsg = null;
  //validate request payload
  Set<ConstraintViolation<Object>> constraintViolations =
  //check if there are bean validation violations
  if (CollectionUtils.isNotEmpty(constraintViolations)) {
    internalErrMsg = new StringBuilder();
    //check through each property in the bean class for validation violation
    for (ConstraintViolation<Object> violation : constraintViolations) {
      //Appending property name and violated validation
      internalErrMsg.append(violation.getPropertyPath().toString()).append(" ").append(
        violation.getMessage()).append("; ");
    throw new ValidationException(internalErrMsg.toString());

Jersey2 Request Filters

What and Why?

Jersey filter is an interceptor class (mediator) we use to filter the requests before hitting out the end point.
(Caller)  --> Filter  --> (End point)

We can check the Authorization functionality here.
Lets assume we have an end point which returns user permission details.
So if we need to filter only the requests come through a particular client, we can add a filter and allow only the valid requests.



public class AuthorizationFilter implements ContainerRequestFilter { 
    @Override public void filter(ContainerRequestContext request) throws IOException {
            if (!isAuthorized()) {
               // Throw Exception here

    private Boolean isAuthorized() {
        boolean isAuthorized = true;

        //implement the logic here.
        return isAuthorized;