package com.mandi.common;
|
|
import java.util.HashSet;
|
import java.util.Iterator;
|
import java.util.Set;
|
|
import javax.validation.ConstraintViolation;
|
import javax.validation.Validation;
|
import javax.validation.Validator;
|
import javax.validation.ValidatorFactory;
|
|
import com.mandi.dao.common.ObjectResult;
|
|
/**
|
* @author mengly
|
* @version 创建时间:2016年6月3日 下午1:18:57
|
* 类说明 :hibernate validator
|
*/
|
|
public class ValidatorUtils {
|
private static Validator validator=null;
|
public static Validator getValidator()
|
{
|
if(validator==null)
|
{
|
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
|
validator=factory.getValidator();
|
}
|
return validator;
|
}
|
public static <T> Set<ConstraintViolation<T>> checkCTS(T t)
|
{
|
Validator v=ValidatorUtils.getValidator();
|
Set<ConstraintViolation<T>> cts=v.validate(t);
|
return cts;
|
}
|
public static <T> ObjectResult<T> checkForMsgs(T t)
|
{
|
ObjectResult<T> objr=new ObjectResult<T>();
|
if(t==null)
|
{
|
objr.setCode(1);
|
objr.setHint("对象为空!");
|
objr.setErrmsg("对象为空!");
|
return objr;
|
}
|
Validator v=ValidatorUtils.getValidator();
|
Set<ConstraintViolation<T>> cts=v.validate(t);
|
if(cts.size()>0)
|
{
|
objr.setCode(1);
|
Iterator<ConstraintViolation<T>> it=cts.iterator();
|
StringBuffer sb=new StringBuffer();
|
while(it.hasNext())
|
{
|
ConstraintViolation<T> ct=it.next();
|
sb.append(ct.getMessage()+";");
|
}
|
objr.setHint(sb.toString());
|
objr.setErrmsg(sb.toString());
|
}else{
|
objr.setCode(0);
|
}
|
return objr;
|
}
|
public <T> boolean check(T t)
|
{
|
|
Set<ConstraintViolation<T>> cts=checkCTS(t);
|
if(cts.size()>0)
|
{
|
return false;
|
}else{
|
return true;
|
}
|
}
|
|
public static <T> ObjectResult<T> checkPro(T t,String[] Pros)
|
{
|
ObjectResult<T> objr=new ObjectResult<T>();
|
if(t==null)
|
{
|
objr.setCode(1);
|
objr.setHint("对象为空!");
|
objr.setErrmsg("对象为空!");
|
return objr;
|
}
|
Validator v=ValidatorUtils.getValidator();
|
StringBuffer sb=new StringBuffer();
|
Set<ConstraintViolation<T>> cts=new HashSet<ConstraintViolation<T>>();
|
for (String pro:Pros) {
|
cts=v.validateProperty(t,pro);
|
if(cts.size()>0)
|
{
|
Iterator<ConstraintViolation<T>> it=cts.iterator();
|
while(it.hasNext())
|
{
|
ConstraintViolation<T> ct=it.next();
|
sb.append(ct.getMessage()+";");
|
}
|
}
|
}
|
if(sb.length()>0)
|
{
|
objr.setCode(1);
|
objr.setErrmsg(sb.toString());
|
}else
|
objr.setCode(0);
|
return objr;
|
}
|
}
|