All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.opencodes.framework.tools.utils.ValidatorUtils Maven / Gradle / Ivy

There is a newer version: 1.0.4
Show newest version
package cn.opencodes.framework.tools.utils;

import java.util.List;
import java.util.Set;

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

import cn.opencodes.framework.tools.vo.RException;

/**
 * hibernate-validator校验工具类
 * @author HJ
 */
public final class ValidatorUtils {
    private static Validator validator;

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

    /**
     * 校验对象
     * @param object        待校验对象
     * @param groups        待校验的组
     * @throws RException  校验不通过,则报RRException异常
     */
    public static void validateEntity(Object object, Class... groups) {
        Set> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for(ConstraintViolation constraint:  constraintViolations){
                msg.append(constraint.getMessage()).append("
"); } throw new RException(msg.toString(), -1); } } /** * 校验对象 * @param list 待校验对象 * @param groups 待校验的组 */ public static void validateEntitys(List list, Class... groups) { if (list == null || list.size()<1) { throw new RException("参数不能为空", -1); } for (Object obj : list) { validateEntity(obj, groups); } } public static void isNullOrZero(Object obj, String message) { if (obj == null) { throw new RException(message, -1); } if (obj instanceof String && StringUtils.isBlank(obj.toString())) { throw new RException(message, -1); } if (obj instanceof String[] && ((String[])obj).length == 0) { throw new RException(message, -1); } if (obj instanceof Long && ((long)obj) == 0) { throw new RException(message, -1); } if (obj instanceof Long[] && ((Long[])obj).length == 0) { throw new RException(message, -1); } if (obj instanceof Integer && ((int)obj) == 0) { throw new RException(message, -1); } if (obj instanceof Integer[] && ((Integer[])obj).length == 0) { throw new RException(message, -1); } if (obj instanceof Double && ((double)obj) == 0.0) { throw new RException(message, -1); } if (obj instanceof Double[] && ((Double[])obj).length == 0) { throw new RException(message, -1); } } public static void isNullOrZero(Object object) { String message = "参数不能为空"; isNullOrZero(object, message); } }