package com.sy.coinage.core.util;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import com.sy.coinage.core.exception.RetException;

/**
 * -hibernate-validator验证工具类
 */
public class ValidatorUtils {

    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * -验证读取表格数据，返回第几条数据问题
     *
     * @param rows 条数
     * @param object
     * @param groups
     * @author lug
     */
    public static void validateEntity(Integer rows, Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            ConstraintViolation<Object> constraint =
                            (ConstraintViolation<Object>) constraintViolations.iterator().next();
            throw new RetException("第" + (rows + 1) + "行" + constraint.getMessage() + "={"
                            + constraint.getInvalidValue() + "}");
        }
    }

    public static void validateEntity(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            ConstraintViolation<Object> constraint =
                            (ConstraintViolation<Object>) constraintViolations.iterator().next();
            throw new RetException(constraint.getMessage() + "={" + constraint.getInvalidValue() + "}");
        }
    }

}
