com.github.bootfastconfig.springtool.ValidatorUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of boot-fast-spring-tool Show documentation
Show all versions of boot-fast-spring-tool Show documentation
Parent pom providing dependency and plugin management for applications
built with Maven
package com.github.bootfastconfig.springtool;
import com.github.bootfastconfig.abnormal.ServiceRuntimeException;
import com.github.bootfastconfig.result.DefaultResultCode;
import com.github.bootfastconfig.result.ResultCode;
import com.github.bootfastconfig.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
@Slf4j
public class ValidatorUtil extends ValidationUtils {
private static LocalValidatorFactoryBean globalValidator;
private static Object lock = new Object();
private static void initMessageSource() {
if (globalValidator == null) {
synchronized (lock) {
if (globalValidator == null) {
globalValidator = SpringBeanUtil.getBean(LocalValidatorFactoryBean.class);
}
}
}
}
public static Set> anotValidator(T object, Class>... groups) {
initMessageSource();
Validator validator = globalValidator.getValidator();
return validator.validate(object, groups);
}
public static void dismantlingBindingResult(BindingResult bindingResult) throws ServiceRuntimeException {
dismantlingBindingResult(bindingResult, ResultCodeEnum.VALIDATOR);
}
public static void validatorIsNotNull(Object o, ResultCode resultCode) throws ServiceRuntimeException {
validator(o, ObjectUtil::isEmpty, resultCode);
}
public static void validator(T o, Predicate predicate, ResultCode resultCode) throws ServiceRuntimeException {
if (predicate.test(o)) {
throw new ServiceRuntimeException(resultCode);
}
}
public static void dismantlingBindingResult(BindingResult bindingResult, ResultCode resultCode) throws ServiceRuntimeException {
if (bindingResult.hasErrors()) {
List errorList = bindingResult.getAllErrors();
if (errorList != null && !errorList.isEmpty()) {
String collect = errorList.stream().map(ObjectError::getDefaultMessage).collect(Collectors.joining(",", "[", "]"));
throw new ServiceRuntimeException(new DefaultResultCode(resultCode.getCode(), collect));
}
}
}
public static void onException(Object object, Class>... groups) throws ServiceRuntimeException {
ServiceRuntimeException exception = (ServiceRuntimeException) ValidatorUtil.validatorException(object, o -> {
for (ConstraintViolation