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


Implementation


Bean Class

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

public class UserDTO {
  @NotNull
  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
  validateBean(userDTO);

  //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 =
  validator.validate(object);
  //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());
  }
}




No comments:

Post a Comment