package com.mmall.util;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mmall.exception.ParamException;
import org.apache.commons.collections.MapUtils;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public class BeanValidator {
private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
//检查一个object对象
public static Map validate(T t, Class... groups) {
Validator validator = validatorFactory.getValidator();
Set validateResult = validator.validate(t, groups);
if (validateResult.isEmpty()) {
return Collections.emptyMap();
} else {
LinkedHashMap errors = Maps.newLinkedHashMap();
Iterator iterator = validateResult.iterator();
while (iterator.hasNext()) {
ConstraintViolation violation = (ConstraintViolation)iterator.next();
errors.put(violation.getPropertyPath().toString(), violation.getMessage());
}
return errors;
}
}
//检查一个list对象
public static Map validateList(Collection> collection) {
Preconditions.checkNotNull(collection);
Iterator iterator = collection.iterator();
Map errors;
do {
if (!iterator.hasNext()) {
return Collections.emptyMap();
}
Object object = iterator.next();
errors = validate(object, new Class[0]);
} while (errors.isEmpty());
return errors;
}
//用一个方法来封装上面的两个方法。我们可以选择用这个方法,然后到map,把map的错误信息记录到日志,再抛异常
public static Map validateObject(Object first, Object... objects) {
if (objects != null && objects.length > 0) {
return validateList(Lists.asList(first, objects));
} else {
return validate(first, new Class[0]);
}
}
//我们也可以选择用这个方法,直接抛异常
public static void check(Object param) throws ParamException {
Map map = BeanValidator.validateObject(param);
if (MapUtils.isNotEmpty(map)) {
throw new ParamException(map.toString());
}
}
}