重新设计 API,重写内容。
parent
7eeb10ff94
commit
5cad71ed34
35
pom.xml
35
pom.xml
|
@ -1,6 +1,7 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
|
@ -9,8 +10,7 @@
|
|||
<version>0.0.1-SNAPSHOT</version>
|
||||
|
||||
<name>plusone-validator</name>
|
||||
<!-- FIXME change it to the project's website -->
|
||||
<url>http://www.example.com</url>
|
||||
<url>http://www.zhouxy.xyz</url>
|
||||
|
||||
<properties>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
|
@ -20,27 +20,37 @@
|
|||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>xyz.zhouxy.plusone</groupId>
|
||||
<artifactId>plusone-commons</artifactId>
|
||||
<version>0.0.1-SNAPSHOT</version>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>32.0.1-jre</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>junit</groupId>
|
||||
<artifactId>junit</artifactId>
|
||||
<version>4.11</version>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.13.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>xyz.zhouxy.plusone</groupId>
|
||||
<artifactId>plusone-commons</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter-api</artifactId>
|
||||
<version>5.9.2</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
|
||||
<plugin>
|
||||
<artifactId>maven-clean-plugin</artifactId>
|
||||
<version>3.1.0</version>
|
||||
</plugin>
|
||||
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
|
||||
<plugin>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<version>3.0.2</version>
|
||||
|
@ -65,7 +75,6 @@
|
|||
<artifactId>maven-deploy-plugin</artifactId>
|
||||
<version>2.8.2</version>
|
||||
</plugin>
|
||||
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
|
||||
<plugin>
|
||||
<artifactId>maven-site-plugin</artifactId>
|
||||
<version>3.7.1</version>
|
||||
|
|
|
@ -1,86 +0,0 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* 校验器
|
||||
*
|
||||
* <p>
|
||||
* 可以使用以下方式初始化一个校验器:
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* BaseValidator<Integer> validator = new BaseValidator<>() {
|
||||
* {
|
||||
* withRule(value -> Objects.nonNull(value), "value 不能为空");
|
||||
* withRule(value -> (value >= 0 && value <= 500), "value 应在 [0, 500] 内");
|
||||
* }
|
||||
* };
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* 也可以通过继承本类,定义一个校验器(可使用单例模式)。
|
||||
* </p>
|
||||
*
|
||||
* <p>
|
||||
* 然后通过校验器的 {@link #validate} 方法,或
|
||||
* {@link ValidateUtil#validate(Object, Validator)} 对指定对象进行校验。
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* ValidateUtil.validate(255, validator);
|
||||
* </pre>
|
||||
*
|
||||
* <pre>
|
||||
* validator.validate(666);
|
||||
* </pre>
|
||||
* </p>
|
||||
*
|
||||
* @author <a href="https://gitee.com/zhouxy108">ZhouXY</a>
|
||||
* @see IValidateRequired
|
||||
* @see ValidateUtil
|
||||
* @see Validator
|
||||
*/
|
||||
public abstract class BaseValidator<T> {
|
||||
|
||||
private final List<RuleInfo<T, ?>> rules = new ArrayList<>();
|
||||
|
||||
protected BaseValidator() {
|
||||
}
|
||||
|
||||
protected final void withRule(Predicate<T> rule, String errorMessage) {
|
||||
withRule(rule, () -> new InvalidInputException(errorMessage));
|
||||
}
|
||||
|
||||
protected final <E extends RuntimeException> void withRule(Predicate<T> rule, Supplier<E> exceptionCreator) {
|
||||
withRule(rule, value -> exceptionCreator.get());
|
||||
}
|
||||
|
||||
protected final <E extends RuntimeException> void withRule(Predicate<T> rule, Function<T, E> exceptionCreator) {
|
||||
this.rules.add(new RuleInfo<>(rule, exceptionCreator));
|
||||
}
|
||||
|
||||
public void validate(T obj) {
|
||||
this.rules.forEach(ruleInfo -> ruleInfo.validate(obj));
|
||||
}
|
||||
|
||||
protected static class RuleInfo<T, E extends RuntimeException> {
|
||||
private final Predicate<T> rule;
|
||||
private final Function<T, E> exceptionCreator;
|
||||
|
||||
private RuleInfo(Predicate<T> rule, Function<T, E> exceptionCreator) {
|
||||
this.rule = rule;
|
||||
this.exceptionCreator = exceptionCreator;
|
||||
}
|
||||
|
||||
private void validate(T obj) {
|
||||
if (!rule.test(obj)) {
|
||||
throw exceptionCreator.apply(obj);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,53 +0,0 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
import xyz.zhouxy.plusone.exception.PlusoneException;
|
||||
|
||||
/**
|
||||
* 4040200 - 无效的用户输入
|
||||
*
|
||||
* @author <a href="https://gitee.com/zhouxy108">ZhouXY</a>
|
||||
*/
|
||||
public class InvalidInputException extends PlusoneException {
|
||||
|
||||
private static final long serialVersionUID = 7956661913360059670L;
|
||||
|
||||
public static final int ERROR_CODE = 4040200;
|
||||
|
||||
private InvalidInputException(int code, String msg) {
|
||||
super(code, msg);
|
||||
}
|
||||
|
||||
private InvalidInputException(int code, Throwable cause) {
|
||||
super(code, cause);
|
||||
}
|
||||
|
||||
private InvalidInputException(int code, String msg, Throwable cause) {
|
||||
super(code, msg, cause);
|
||||
}
|
||||
|
||||
public InvalidInputException(String msg) {
|
||||
this(ERROR_CODE, msg);
|
||||
}
|
||||
|
||||
public InvalidInputException(Throwable cause) {
|
||||
this(ERROR_CODE, cause);
|
||||
}
|
||||
|
||||
public InvalidInputException(String msg, Throwable cause) {
|
||||
this(ERROR_CODE, msg, cause);
|
||||
}
|
||||
|
||||
/**
|
||||
* 不支持的 Principal 类型出现时抛出的异常
|
||||
*/
|
||||
public static InvalidInputException unsupportedPrincipalTypeException() {
|
||||
return unsupportedPrincipalTypeException("不支持的 PrincipalType");
|
||||
}
|
||||
|
||||
/**
|
||||
* 不支持的 Principal 类型出现时抛出的异常
|
||||
*/
|
||||
public static InvalidInputException unsupportedPrincipalTypeException(String message) {
|
||||
return new InvalidInputException(4040201, message);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,125 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public abstract class MapValidator<K, V> {
|
||||
|
||||
private final List<Consumer<Map<K, V>>> consumers = new LinkedList<>();
|
||||
|
||||
private final Set<K> keys;
|
||||
|
||||
protected MapValidator(K[] keys) {
|
||||
this(Arrays.asList(keys));
|
||||
}
|
||||
|
||||
protected MapValidator(Collection<K> keys) {
|
||||
this.keys = keys.stream().collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
public final Map<K, V> validateAndCopy(Map<K, V> obj) {
|
||||
return validateAndCopyInternal(obj, this.keys);
|
||||
}
|
||||
|
||||
public final Map<K, V> validateAndCopy(Map<K, V> obj, Collection<K> keys) {
|
||||
return validateAndCopyInternal(obj, keys);
|
||||
}
|
||||
|
||||
@SafeVarargs
|
||||
public final Map<K, V> validateAndCopy(Map<K, V> obj, K... keys) {
|
||||
return validateAndCopyInternal(obj, Arrays.asList(keys));
|
||||
}
|
||||
|
||||
private final Map<K, V> validateAndCopyInternal(Map<K, V> obj, Collection<K> keys) {
|
||||
validate(obj);
|
||||
return obj.entrySet().stream()
|
||||
.filter(kv -> keys.contains(kv.getKey()))
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
}
|
||||
|
||||
public final void validate(Map<K, V> obj) {
|
||||
this.consumers.forEach(consumer -> consumer.accept(obj));
|
||||
}
|
||||
|
||||
@SuppressWarnings("unused")
|
||||
protected final <VV extends V> PropertyValidator<K, VV> checkProperty(K key, Class<VV> clazz) {
|
||||
return checkProperty(key);
|
||||
}
|
||||
|
||||
protected final <VV extends V> PropertyValidator<K, VV> checkProperty(K key) {
|
||||
PropertyValidator<K, VV> validator = new PropertyValidator<>(key);
|
||||
this.consumers.add(validator::validate);
|
||||
return validator;
|
||||
}
|
||||
|
||||
protected final void withRule(Predicate<Map<K, V>> rule, String errMsg) {
|
||||
withRule(rule, map -> new IllegalArgumentException(errMsg));
|
||||
}
|
||||
|
||||
protected final void withRule(Predicate<Map<K, V>> rule, String errMsgFormat, Object... args) {
|
||||
withRule(rule, map -> new IllegalArgumentException(String.format(errMsgFormat, args)));
|
||||
}
|
||||
|
||||
protected final <E extends RuntimeException> void withRule(Predicate<Map<K, V>> rule, Supplier<E> e) {
|
||||
withRule(rule, map -> e.get());
|
||||
}
|
||||
|
||||
protected final <E extends RuntimeException> void withRule(Predicate<Map<K, V>> rule, Function<Map<K, V>, E> e) {
|
||||
this.consumers.add(map -> {
|
||||
if (!rule.test(map)) {
|
||||
throw e.apply(map);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class PropertyValidator<K, V> {
|
||||
|
||||
private final K key;
|
||||
|
||||
public PropertyValidator(K key) {
|
||||
this.key = key;
|
||||
}
|
||||
|
||||
private final List<Consumer<V>> consumers = new LinkedList<>();
|
||||
|
||||
public final PropertyValidator<K, V> withRules(Predicate<? super V> rule) {
|
||||
return withRules(rule, v -> new IllegalArgumentException(key.toString()));
|
||||
}
|
||||
|
||||
public final PropertyValidator<K, V> withRules(Predicate<? super V> rule, String errorMsg) {
|
||||
return withRules(rule, v -> new IllegalArgumentException(errorMsg));
|
||||
}
|
||||
|
||||
public final <E extends RuntimeException> PropertyValidator<K, V> withRules(Predicate<? super V> rule,
|
||||
Supplier<E> e) {
|
||||
return withRules(rule, v -> e.get());
|
||||
}
|
||||
|
||||
public final <E extends RuntimeException> PropertyValidator<K, V> withRules(Predicate<? super V> rule,
|
||||
Function<V, E> e) {
|
||||
this.consumers.add(v -> {
|
||||
if (!rule.test(v)) {
|
||||
throw e.apply(v);
|
||||
}
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
public final void validate(Map<K, ? super V> map) {
|
||||
for (Consumer<V> consumer : consumers) {
|
||||
@SuppressWarnings("unchecked")
|
||||
V v = (V) map.get(this.key);
|
||||
consumer.accept(v);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,86 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class PredicateTools {
|
||||
|
||||
private PredicateTools() {
|
||||
throw new IllegalStateException("Utility class");
|
||||
}
|
||||
|
||||
public static <T> Predicate<T> asPredicate(Predicate<T> predicate) {
|
||||
return predicate;
|
||||
}
|
||||
|
||||
public static <T> Predicate<T> notNull() {
|
||||
return obj -> obj != null;
|
||||
}
|
||||
|
||||
public static int length(CharSequence cs) {
|
||||
return cs == null ? 0 : cs.length();
|
||||
}
|
||||
|
||||
public static boolean isNotBlank(CharSequence cs) {
|
||||
return !isBlank(cs);
|
||||
}
|
||||
|
||||
public static Predicate<CharSequence> isNotBlank() {
|
||||
return PredicateTools::isNotBlank;
|
||||
}
|
||||
|
||||
public static boolean isBlank(CharSequence cs) {
|
||||
final int strLen = length(cs);
|
||||
if (strLen == 0) {
|
||||
return true;
|
||||
}
|
||||
for (int i = 0; i < strLen; i++) {
|
||||
if (!Character.isWhitespace(cs.charAt(i))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static Predicate<CharSequence> isBlank() {
|
||||
return PredicateTools::isBlank;
|
||||
}
|
||||
|
||||
public static Predicate<CharSequence> matches(Pattern pattern) {
|
||||
return str -> pattern.matcher(str).matches();
|
||||
}
|
||||
|
||||
public static Predicate<CharSequence> matchesAll(Pattern... patterns) {
|
||||
return str -> {
|
||||
for (Pattern pattern : patterns) {
|
||||
if (!pattern.matcher(str).matches()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
public static Predicate<CharSequence> matchesOne(Pattern... patterns) {
|
||||
return str -> {
|
||||
for (Pattern pattern : patterns) {
|
||||
if (pattern.matcher(str).matches()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
}
|
||||
|
||||
public static <T> Predicate<Collection<T>> forAllItems(Predicate<T> predicate) {
|
||||
return c -> {
|
||||
for (T t : c) {
|
||||
if (!predicate.test(t)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
}
|
||||
}
|
|
@ -1,23 +0,0 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
/**
|
||||
* 校验工具类
|
||||
* <p>
|
||||
* 对 {@link IValidateRequired} 的实现类对象进行校验
|
||||
* </p>
|
||||
*
|
||||
* @author <a href="https://gitee.com/zhouxy108">ZhouXY</a>
|
||||
*
|
||||
* @see BaseValidator
|
||||
* @see Validator
|
||||
* @see IValidateRequired
|
||||
*/
|
||||
public class ValidateUtil {
|
||||
private ValidateUtil() {
|
||||
throw new IllegalStateException("Utility class");
|
||||
}
|
||||
|
||||
public static <T> void validate(T obj, BaseValidator<T> validator) {
|
||||
validator.validate(obj);
|
||||
}
|
||||
}
|
|
@ -1,42 +0,0 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* 校验器
|
||||
*
|
||||
* <p>
|
||||
* 可以使用以下方式初始化一个校验器:
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* var validator = new Validator<Integer>()
|
||||
* .addRule(value -> Objects.nonNull(value), "value 不能为空")
|
||||
* .addRule(value -> (value >= 0 && value <= 500), "value 应在 [0, 500] 内");
|
||||
* </pre>
|
||||
*
|
||||
* <p>
|
||||
* 然后通过校验器的 {@link #validate} 方法,或
|
||||
* {@link ValidateUtil#validate(Object, Validator)} 对指定对象进行校验。
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* validator.validate(666);
|
||||
* </pre>
|
||||
*
|
||||
* <pre>
|
||||
* ValidateUtil.validate(255, validator);
|
||||
* </pre>
|
||||
* </p>
|
||||
*
|
||||
* @author <a href="https://gitee.com/zhouxy108">ZhouXY</a>
|
||||
* @see IValidateRequired
|
||||
* @see ValidateUtil
|
||||
* @see BaseValidator
|
||||
*/
|
||||
public final class Validator<T> extends BaseValidator<T> {
|
||||
public final Validator<T> addRule(final Predicate<T> rule, final String errorMessage) {
|
||||
withRule(rule, errorMessage);
|
||||
return this;
|
||||
}
|
||||
}
|
|
@ -1,22 +0,0 @@
|
|||
package xyz.zhouxy.plusone.validator.validator2;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
|
||||
public abstract class BaseValidator2<T> {
|
||||
|
||||
private List<ValueValidator<T, ?>> valueValidators = new ArrayList<>();
|
||||
|
||||
protected final <R> ValueValidator<T, R> ruleFor(Function<T, R> getter) {
|
||||
ValueValidator<T, R> validValueHolder = new ValueValidator<>(getter);
|
||||
valueValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
}
|
||||
|
||||
public void validate(T obj) {
|
||||
for (ValueValidator<T, ?> valueValidator : this.valueValidators) {
|
||||
valueValidator.validateProperty(obj);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,379 +0,0 @@
|
|||
package xyz.zhouxy.plusone.validator.validator2;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import xyz.zhouxy.plusone.constant.RegexConsts;
|
||||
import xyz.zhouxy.plusone.util.RegexUtil;
|
||||
import xyz.zhouxy.plusone.validator.InvalidInputException;
|
||||
|
||||
public class ValueValidator<DTO, PROPERTY> {
|
||||
Function<DTO, PROPERTY> getter;
|
||||
List<Consumer<PROPERTY>> rules = new ArrayList<>();
|
||||
|
||||
public ValueValidator(Function<DTO, PROPERTY> getter) {
|
||||
this.getter = getter;
|
||||
}
|
||||
|
||||
private <E extends RuntimeException> void withRule(Predicate<PROPERTY> condition,
|
||||
Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(value -> {
|
||||
if (!condition.test(value)) {
|
||||
throw exceptionCreator.apply(value);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private <E extends RuntimeException> void withRule(Consumer<PROPERTY> rule) {
|
||||
this.rules.add(rule);
|
||||
}
|
||||
|
||||
// ====================
|
||||
// ====== Object ======
|
||||
// ====================
|
||||
|
||||
// ====== notNull =====
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> notNull() {
|
||||
return notNull("Value could not be null.");
|
||||
}
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> notNull(String errMsg) {
|
||||
return notNull(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> notNull(Supplier<E> exceptionCreator) {
|
||||
return notNull(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> notNull(Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(Objects::nonNull, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ====== isNull =====
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> isNull(String errMsg) {
|
||||
return isNull(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isNull(Supplier<E> exceptionCreator) {
|
||||
return isNull(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isNull(Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(Objects::isNull, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ===== equals =====
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> equalsThat(Object that) {
|
||||
return equalsThat(that, value -> new InvalidInputException(String.format("(%s) 必须与 (%s) 相等", value, that)));
|
||||
}
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> equalsThat(Object that, String errMsg) {
|
||||
return equalsThat(that, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> equalsThat(
|
||||
Object that, Supplier<E> exceptionCreator) {
|
||||
return equalsThat(that, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> equalsThat(
|
||||
Object that, Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(value -> Objects.equals(value, that), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ===== state =====
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> state(Predicate<PROPERTY> condition) {
|
||||
return state(condition, "无效的用户输入");
|
||||
}
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> state(Predicate<PROPERTY> condition, String errMsg) {
|
||||
return state(condition, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> state(
|
||||
Predicate<PROPERTY> condition,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return state(condition, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> state(
|
||||
Predicate<PROPERTY> condition,
|
||||
Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(condition, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// =================
|
||||
// ====== int ======
|
||||
// =================
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> between(int min, int max) {
|
||||
return between(min, max, String.format("数值不在 %s 和 %s 之间", String.valueOf(min), String.valueOf(max)));
|
||||
}
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> between(int min, int max, String errMsg) {
|
||||
return between(min, max, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> between(int min, int max,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return between(min, max, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> between(int min, int max,
|
||||
Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(value -> ((int) value >= min && (int) value < max), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ====================
|
||||
// ====== double ======
|
||||
// ====================
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> between(double min, double max) {
|
||||
return between(min, max, String.format("数值不在 %s 和 %s 之间", String.valueOf(min), String.valueOf(max)));
|
||||
}
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> between(double min, double max, String errMsg) {
|
||||
return between(min, max, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> between(double min, double max,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return between(min, max, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> between(double min, double max,
|
||||
Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(value -> ((double) value >= min && (double) value < max), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ================================
|
||||
// ====== Collection, String ======
|
||||
// ================================
|
||||
|
||||
// ====== notEmpty =====
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> notEmpty(String errMsg) {
|
||||
return notEmpty(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> notEmpty(Supplier<E> exceptionCreator) {
|
||||
return notEmpty(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> notEmpty(Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(value -> {
|
||||
if (value == null) {
|
||||
return false;
|
||||
}
|
||||
if (value instanceof Collection) {
|
||||
return !((Collection<?>) value).isEmpty();
|
||||
}
|
||||
if (value instanceof String) {
|
||||
return !((String) value).isEmpty();
|
||||
}
|
||||
return false;
|
||||
}, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ====== isEmpty =====
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> isEmpty(String errMsg) {
|
||||
return isEmpty(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isEmpty(Supplier<E> exceptionCreator) {
|
||||
return isEmpty(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isEmpty(Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(value -> {
|
||||
if (value == null) {
|
||||
return false;
|
||||
}
|
||||
if (value instanceof Collection) {
|
||||
return ((Collection<?>) value).isEmpty();
|
||||
}
|
||||
if (value instanceof String) {
|
||||
return ((String) value).isEmpty();
|
||||
}
|
||||
return false;
|
||||
}, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// =====================
|
||||
// ====== boolean ======
|
||||
// =====================
|
||||
|
||||
// ====== isTrue ======
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> isTrue() {
|
||||
return isTrue("The value must be true.");
|
||||
}
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> isTrue(String errMsg) {
|
||||
return isTrue(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isTrue(Supplier<E> exceptionCreator) {
|
||||
return isTrue(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isTrue(Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(Boolean.TRUE::equals, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ====== isFalse ======
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> isFalse() {
|
||||
return isFalse("The value must be false.");
|
||||
}
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> isFalse(String errMsg) {
|
||||
return isFalse(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isFalse(Supplier<E> exceptionCreator) {
|
||||
return isFalse(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> isFalse(Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(Boolean.FALSE::equals, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ====================
|
||||
// ====== String ======
|
||||
// ====================
|
||||
|
||||
// ===== matches =====
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> matches(String regex, String errMsg) {
|
||||
return matches(regex, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> matches(
|
||||
String regex,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return matches(regex, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> matches(
|
||||
String regex,
|
||||
Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(input -> RegexUtil.matches((String) input, regex), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ===== matchesOr =====
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> matchesOr(String[] regexs, String errMsg) {
|
||||
return matchesOr(regexs, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> matchesOr(
|
||||
String[] regexs,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return matchesOr(regexs, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> matchesOr(
|
||||
String[] regexs,
|
||||
Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(input -> RegexUtil.matchesOr((String) input, regexs), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ===== matchesAnd =====
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> matchesAnd(String[] regexs, String errMsg) {
|
||||
return matchesAnd(regexs, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> matchesAnd(
|
||||
String[] regexs,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return matchesAnd(regexs, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> matchesAnd(
|
||||
String[] regexs,
|
||||
Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(input -> RegexUtil.matchesAnd((String) input, regexs), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ===== notBlank =====
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> notBlank() {
|
||||
return notBlank("This String argument must have text; it must not be null, empty, or blank");
|
||||
}
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> notBlank(String errMsg) {
|
||||
return notBlank(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> notBlank(Supplier<E> exceptionCreator) {
|
||||
return notBlank(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> notBlank(Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(input -> StrUtil.isNotBlank((String) input), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ===== email =====
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> email() {
|
||||
return email("The value is not an email address.");
|
||||
}
|
||||
|
||||
public ValueValidator<DTO, PROPERTY> email(String errMsg) {
|
||||
return email(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> email(Supplier<E> exceptionCreator) {
|
||||
return email(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> ValueValidator<DTO, PROPERTY> email(Function<PROPERTY, E> exceptionCreator) {
|
||||
return matches(RegexConsts.EMAIL, exceptionCreator);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
|
||||
void validateProperty(DTO obj) {
|
||||
PROPERTY value = this.getter.apply(obj);
|
||||
for (Consumer<PROPERTY> rule : this.rules) {
|
||||
rule.accept(value);
|
||||
}
|
||||
}
|
||||
|
||||
private static <V> Function<V, InvalidInputException> convertExceptionCreator(String errMsg) {
|
||||
return convertExceptionCreator(errMsg);
|
||||
}
|
||||
|
||||
private static <V, E extends RuntimeException> Function<V, E> convertExceptionCreator(
|
||||
Supplier<E> exceptionSupplier) {
|
||||
return value -> exceptionSupplier.get();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,75 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import xyz.zhouxy.plusone.commons.constant.PatternConsts;
|
||||
|
||||
class MapValidatorTests {
|
||||
|
||||
private static final String USERNAME = "username";
|
||||
private static final String ACCOUNT = "account";
|
||||
private static final String PASSWORD = "password";
|
||||
private static final String PASSWORD2 = "password2";
|
||||
private static final String AGE = "age";
|
||||
private static final String BOOLEAN = "boolean";
|
||||
private static final String ROLE_LIST = "roleList";
|
||||
|
||||
private static final MapValidator<String, Object> validator = new MapValidator<String, Object>(
|
||||
new String[] { USERNAME, ACCOUNT, PASSWORD, AGE, BOOLEAN, ROLE_LIST }) {
|
||||
{
|
||||
checkProperty(USERNAME, String.class)
|
||||
.withRules(StringUtils::isNotEmpty)
|
||||
.withRules(PredicateTools.matches(PatternConsts.USERNAME),
|
||||
username -> new IllegalArgumentException(String.format("用户名【%s】不符合规范", username)));
|
||||
|
||||
checkProperty(ACCOUNT, String.class)
|
||||
.withRules(StringUtils::isNotEmpty)
|
||||
.withRules(PredicateTools.matchesOne(PatternConsts.EMAIL, PatternConsts.MOBILE_PHONE),
|
||||
"请输入正确的邮箱地址或手机号");
|
||||
|
||||
checkProperty(PASSWORD, String.class)
|
||||
.withRules(StringUtils::isNotEmpty)
|
||||
.withRules(PredicateTools.matches(PatternConsts.PASSWORD), "密码不符合规范");
|
||||
|
||||
withRule(m -> Objects.equals(m.get(PASSWORD), m.get(PASSWORD2)),
|
||||
"两次输入的密码不一样!");
|
||||
|
||||
checkProperty(AGE, Integer.class)
|
||||
.withRules(Objects::nonNull)
|
||||
.withRules(age -> (18 <= age && 60 >= age));
|
||||
|
||||
checkProperty(BOOLEAN, Boolean.class)
|
||||
.withRules(PredicateTools.notNull(), "Boolean property could not be null.")
|
||||
.withRules(b -> b, "Boolean property must be true.");
|
||||
|
||||
this.<Collection<String>>checkProperty(ROLE_LIST)
|
||||
.withRules(c -> c != null && !c.isEmpty(), "角色列表不能为空!")
|
||||
.withRules(PredicateTools.forAllItems(Objects::nonNull), () -> new NullPointerException(ROLE_LIST));
|
||||
}
|
||||
};
|
||||
|
||||
@Test
|
||||
void test() {
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("username", "ZhouXY");
|
||||
params.put("account", "zhouxy@code108.cn");
|
||||
params.put("password", "99Code108");
|
||||
params.put("password2", "99Code108");
|
||||
params.put("age", 18);
|
||||
params.put("boolean", true);
|
||||
params.put("roleList", Arrays.asList("admin", ""));
|
||||
|
||||
Map<String, Object> validedParams = validator.validateAndCopy(params);
|
||||
System.out.println(validedParams);
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue