package com.iamberry.wechat.tools;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

/**
 * @description 通过hibernate组件效验对象
 * @author 欧阳明
 * @date 2016-4-21
 */
public class ValidationUtils {

	private static Validator validator =  Validation.buildDefaultValidatorFactory().getValidator();
	  
	  public static <T> ValidationResult validateEntity(T obj){
	    ValidationResult result = new ValidationResult();
	    List<String> errorList=new ArrayList<String>();
	     Set<ConstraintViolation<T>> set = validator.validate(obj,Default.class);
	     if( set.size()>0 ){
	       result.setHasErrors(true);
	       Map<String,String> errorMsg = new HashMap<String,String>();
	       for(ConstraintViolation<T> cv : set){
	         errorMsg.put(cv.getPropertyPath().toString(), cv.getMessage());
	         errorList.add(cv.getMessage());
	       }
	       result.setErrorMsg(errorMsg);
	       result.setErrorMsgList(errorList);
	     }
	     return result;
	  }
	  
	  public static <T> ValidationResult validateProperty(T obj,String propertyName){
	    ValidationResult result = new ValidationResult();
	     Set<ConstraintViolation<T>> set = validator.validateProperty(obj,propertyName,Default.class);
	     if(set.size()>0){
	       result.setHasErrors(true);
	       Map<String,String> errorMsg = new HashMap<String,String>();
	       for(ConstraintViolation<T> cv : set){
	         errorMsg.put(propertyName, cv.getMessage());
	       }
	       result.setErrorMsg(errorMsg);
	     }
	     return result;
	  }
}
