All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.swak.frame.validation.ValidatorUtils Maven / Gradle / Ivy

There is a newer version: 2.3.1
Show newest version

package com.swak.frame.validation;

import com.swak.frame.validation.ValidationResult.ErrorMessage;

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

public class ValidatorUtils {

	/**
	 * 默认{@link Validator} 对象
	 */
	private static final Validator validator;

	static {
		validator = Validation.buildDefaultValidatorFactory().getValidator();
	}

	/**
	 * 获取原生{@link Validator} 对象
	 *
	 * @return {@link Validator} 对象
	 */
	public static Validator getValidator() {
		return validator;
	}

	/**
	 * 校验对象
	 *
	 * @param     Bean类型
	 * @param bean   bean
	 * @param groups 校验组
	 * @return {@link Set}
	 */
	public static  Set> validate(T bean, Class... groups) {
		return validator.validate(bean, groups);
	}

	/**
	 * 校验bean的某一个属性
	 *
	 * @param           Bean类型
	 * @param bean         bean
	 * @param propertyName 属性名称
	 * @param groups       验证分组
	 * @return {@link Set}
	 */
	public static  Set> validateProperty(T bean, String propertyName, Class... groups) {
		return validator.validateProperty(bean, propertyName, groups);
	}

	/**
	 * 校验对象
	 *
	 * @param     Bean类型
	 * @param bean   bean
	 * @param groups 校验组
	 * @return {@link ValidationResult}
	 */
	public static  ValidationResult warpValidate(T bean, Class... groups) {
		return warpBeanValidationResult(validate(bean, groups));
	}

	/**
	 * 校验bean的某一个属性
	 *
	 * @param           bean类型
	 * @param bean         bean
	 * @param propertyName 属性名称
	 * @param groups       验证分组
	 * @return {@link ValidationResult}
	 */
	public static  ValidationResult warpValidateProperty(T bean, String propertyName, Class... groups) {
		return warpBeanValidationResult(validateProperty(bean, propertyName, groups));
	}

	/**
	 * 包装校验结果
	 *
	 * @param constraintViolations 校验结果集
	 * @return {@link ValidationResult}
	 */
	private static  ValidationResult warpBeanValidationResult(Set> constraintViolations) {
		ValidationResult result = new ValidationResult(constraintViolations.isEmpty());
		for (ConstraintViolation constraintViolation : constraintViolations) {
			ErrorMessage errorMessage = new ErrorMessage();
			errorMessage.setPropertyName(constraintViolation.getPropertyPath().toString());
			errorMessage.setMessage(constraintViolation.getMessage());
			errorMessage.setValue(constraintViolation.getInvalidValue());
			result.addErrorMessage(errorMessage);
		}
		return result;
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy