/**
 * Copyright (c) cn-fanya All rights reserved.
 */

package org.security.common.validator;

import org.security.common.exception.RenException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * hibernate-validator校验工具类
 * 参考文档：http://docs.jboss.org/hibernate/validator/6.0/reference/en-US/html_single/
 *
 * @author zj
 * @since 1.0.0
 */
public class ValidatorUtils {
	private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

	/**
	 * 校验对象
	 * @param object        待校验对象
	 * @param groups        待校验的组
	 */
	public static void validateEntity(Object object, Class<?>... groups)
		throws RenException {
		Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
		if (!constraintViolations.isEmpty()) {
			ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
			throw new RenException(constraint.getMessage());
		}
	}
}
