/**
 * Copyright 2008-2018. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved.
 * <a>http://www.crunii.com/</a>
 */
package com.crunii.micro.common.utils;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;

/**
 * @author 郭宏飞 create 2019年6月18日下午3:53:32
 *	项目默认加载hibernate Validator
 */
public class BeanValidUtil {
	private static ValidatorFactory validatorFactory;
	static{
		validatorFactory=Validation.buildDefaultValidatorFactory();
	}
	
	public static <T> ValidResult<T> getValidBeanStr(T object){
		return new ValidResult<>(validBean(object));
	}
	
	public static <T> Set<ConstraintViolation<T>> validBean(T object, Class<?>... groups){
		return validatorFactory.getValidator().validate(object, groups);
	}
	
	public static final class ValidResult<T>{
		Set<ConstraintViolation<T>> validResult;
		public ValidResult(Set<ConstraintViolation<T>> validResult){
			this.validResult=validResult;
		}
		public boolean isValidSuccess(){
			return validResult==null||validResult.size()==0?true:false;
		}
		public String getValidMessage(){
			StringBuilder builder=new StringBuilder();
			validResult.stream().forEach((e)->{
				builder.append("property:"+e.getPropertyPath()+",result:"+e.getMessage()+";");
			});
			return builder.toString();
		}
		public Set<ConstraintViolation<T>> getvalidResult(){
			return validResult;
		}
	}
	
}
