Wednesday, February 26, 2014

Spring JARX-RS: How to validate PayLoad [ PayLoadValidator ]

Hi all,
- Today, i have a new post . How to validate an object with annotations @NotNull, @Valid, any validations annotations.
- This post will help you understand using spring jersey + validation annotations.

Create Class PayLoadValidator:

package com.sample.common.util;

import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.sample.common.domain.User;
/**
 *
 * validate object has annotation @Valid@NotNull

 *
 * @author HieuNT29
 *
 */

@Component
public class PayloadValidator {
    private javax.validation.Validator validator = null;
    private static final Logger LOGGER = LoggerFactory
            .getLogger(PayloadValidator.class);

    PayloadValidator() {
    };

    @PostConstruct
    public void setup() {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }
    @SuppressWarnings("unchecked")

    public Error validate(List< ? extends User> requestEntries, Error errorResponse) {
        Iterator vIterator = (Iterator) requestEntries.iterator();
        int failureCount = 0;
        while (vIterator.hasNext()) {
            User userReqEntry = vIterator.next();
            Set errorSet = validator.validate(userReqEntry);
            if (errorSet.size() > 0) {
                StringBuffer errorMessage = new StringBuffer();
                for (ConstraintViolation error : errorSet) {
                    System.out.println(error);
                }  
                LOGGER.debug("Error message {}", errorMessage.toString());
                vIterator.remove();
                errorResponse.setFailureCount(++failureCount);
            }
        }
        return errorResponse;
    }
}


Source Code