Compare commits
10 Commits
Author | SHA1 | Date |
---|---|---|
ZhouXY108 | 25ec5577cc | |
ZhouXY108 | 315ff1950f | |
ZhouXY108 | 00b9f16176 | |
ZhouXY108 | cb1ad03b9b | |
ZhouXY108 | b03f978da9 | |
ZhouXY108 | 3cac270574 | |
ZhouXY108 | 49f2c437f5 | |
ZhouXY108 | a71d75029e | |
ZhouXY108 | c1a7bafaf6 | |
ZhouXY108 | 92e142dcf3 |
|
@ -10,6 +10,3 @@ end_of_line = lf
|
|||
charset = utf-8
|
||||
trim_trailing_whitespace = false
|
||||
insert_final_newline = true
|
||||
|
||||
[*.xml]
|
||||
indent_size = 2
|
||||
|
|
37
pom.xml
37
pom.xml
|
@ -1,13 +1,12 @@
|
|||
<?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"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
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>
|
||||
|
||||
<groupId>xyz.zhouxy.plusone</groupId>
|
||||
<artifactId>plusone-validator-for-mfp</artifactId>
|
||||
<version>0.1.3-SNAPSHOT</version>
|
||||
<artifactId>plusone-validator</artifactId>
|
||||
<version>0.1.5-SNAPSHOT</version>
|
||||
|
||||
<name>plusone-validator</name>
|
||||
<url>http://zhouxy.xyz</url>
|
||||
|
@ -16,43 +15,38 @@
|
|||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<commons-lang3.version>3.12.0</commons-lang3.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.google.guava</groupId>
|
||||
<artifactId>guava</artifactId>
|
||||
<version>32.0.1-jre</version>
|
||||
<groupId>xyz.zhouxy.plusone</groupId>
|
||||
<artifactId>plusone-commons</artifactId>
|
||||
<version>0.1.0-SNAPSHOT</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.12.0</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>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>3.14.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-collections4</artifactId>
|
||||
<version>4.4</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<!-- 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>
|
||||
|
@ -77,6 +71,7 @@
|
|||
<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,43 +0,0 @@
|
|||
package xyz.zhouxy.plusone.commons.util;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Function;
|
||||
|
||||
/**
|
||||
* ConcurrentHashMapUtil
|
||||
*
|
||||
* <p>
|
||||
* Java 8 的 {@link ConcurrentHashMap#computeIfAbsent(Object, Function)} 方法有 bug,
|
||||
* 可使用这个工具类的 {@link computeIfAbsentForJava8} 进行替换。
|
||||
*
|
||||
* <p>
|
||||
* <b>NOTE: 方法来自Dubbo,见:issues#2349</b>
|
||||
*
|
||||
* @author ZhouXY
|
||||
* @see ConcurrentHashMap
|
||||
*/
|
||||
public class ConcurrentHashMapUtil {
|
||||
|
||||
public static <K, V> V computeIfAbsentForJava8(ConcurrentHashMap<K, V> map, final K key,
|
||||
final Function<? super K, ? extends V> mappingFunction) {
|
||||
Objects.requireNonNull(key);
|
||||
Objects.requireNonNull(mappingFunction);
|
||||
V v = map.get(key);
|
||||
if (null == v) {
|
||||
v = mappingFunction.apply(key);
|
||||
if (null == v) {
|
||||
return null;
|
||||
}
|
||||
final V res = map.putIfAbsent(key, v);
|
||||
if (null != res) {
|
||||
return res;
|
||||
}
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
private ConcurrentHashMapUtil() {
|
||||
throw new IllegalStateException("Utility class");
|
||||
}
|
||||
}
|
|
@ -1,43 +0,0 @@
|
|||
package xyz.zhouxy.plusone.commons.util;
|
||||
|
||||
import java.util.function.Predicate;
|
||||
|
||||
/**
|
||||
* Predicates
|
||||
*
|
||||
* <p>
|
||||
* {@link Predicate} 相关操作。
|
||||
* </p>
|
||||
*
|
||||
* @author ZhouXY
|
||||
* @see Predicate
|
||||
*/
|
||||
public class Predicates {
|
||||
|
||||
/**
|
||||
* 将 lambda 表达式或者方法引用包装为对应类型的 {@link Predicate} 对象。
|
||||
* 如将 {@code Objects::nonNull} 明确地指定为 {@code Predicate<String>},
|
||||
* 使之可以链式调用 {@link Predicate#and(Predicate)}、{@link Predicate#or(Predicate)}
|
||||
* 等方法,连接其它 {@code Predicate<? super T>} 对象。
|
||||
*
|
||||
* <pre>
|
||||
* Predicate<String> predicate = Predicates.<String>of(Objects::nonNull)
|
||||
* .and(StringUtils::isNotEmpty);
|
||||
* </pre>
|
||||
*
|
||||
* @param <T> 目标类型
|
||||
* @param predicate 原 {@link Predicate} 实例
|
||||
* @return 包装的 {@link Predicate} 实例
|
||||
*/
|
||||
public static <T> Predicate<T> of(Predicate<? super T> predicate) {
|
||||
return predicate::test;
|
||||
}
|
||||
|
||||
public static <T> Predicate<T> not(Predicate<? super T> predicate) {
|
||||
return t -> !predicate.test(t);
|
||||
}
|
||||
|
||||
private Predicates() {
|
||||
throw new IllegalStateException("Utility class");
|
||||
}
|
||||
}
|
|
@ -1,378 +0,0 @@
|
|||
package xyz.zhouxy.plusone.commons.util;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.annotation.Nonnull;
|
||||
import javax.annotation.Nullable;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
/**
|
||||
* 封装一些常用的正则操作,并可以缓存 {@link Pattern} 实例以复用(最多缓存大概 256 个)。
|
||||
*
|
||||
* @author ZhouXY
|
||||
*
|
||||
*/
|
||||
public final class RegexUtil {
|
||||
|
||||
private static final int DEFAULT_CACHE_INITIAL_CAPACITY = 64;
|
||||
private static final int MAX_CACHE_SIZE = 256;
|
||||
private static final ConcurrentHashMap<String, Pattern> PATTERN_CACHE = new ConcurrentHashMap<>(
|
||||
DEFAULT_CACHE_INITIAL_CAPACITY);
|
||||
|
||||
/**
|
||||
* 获取 {@link Pattern} 实例。
|
||||
*
|
||||
* @param pattern 正则表达式
|
||||
* @param cachePattern 是否缓存 {@link Pattern} 实例
|
||||
* @return {@link Pattern} 实例
|
||||
*/
|
||||
public static Pattern getPattern(final String pattern, final boolean cachePattern) {
|
||||
Preconditions.checkNotNull(pattern, "The pattern can not be null.");
|
||||
return cachePattern ? getAndCachePatternInternal(pattern) : getPatternInternal(pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 {@link Pattern} 实例,不缓存。
|
||||
*
|
||||
* @param pattern 正则表达式
|
||||
* @return {@link Pattern} 实例
|
||||
*/
|
||||
public static Pattern getPattern(final String pattern) {
|
||||
Preconditions.checkNotNull(pattern, "The pattern can not be null.");
|
||||
return getPatternInternal(pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将各个正则表达式转为 {@link Pattern} 实例。
|
||||
*
|
||||
* @param patterns 正则表达式
|
||||
* @param cachePattern 是否缓存 {@link Pattern} 实例
|
||||
* @return {@link Pattern} 实例数组
|
||||
*/
|
||||
public static Pattern[] getPatterns(final String[] patterns, final boolean cachePattern) {
|
||||
Preconditions.checkNotNull(patterns, "Patterns can not be null.");
|
||||
Preconditions.checkArgument(allNotNull(patterns), "The pattern can not be null.");
|
||||
return cachePattern
|
||||
? getAndCachePatternsInternal(patterns)
|
||||
: getPatternsInternal(patterns);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将各个正则表达式转为 {@link Pattern} 实例,不缓存。
|
||||
*
|
||||
* @param patterns 正则表达式
|
||||
* @return {@link Pattern} 实例数组
|
||||
*/
|
||||
public static Pattern[] getPatterns(final String[] patterns) {
|
||||
Preconditions.checkNotNull(patterns, "Patterns can not be null.");
|
||||
Preconditions.checkArgument(allNotNull(patterns), "The pattern can not be null.");
|
||||
return getPatternsInternal(patterns);
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动缓存 Pattern 实例。
|
||||
*
|
||||
* @param pattern 要缓存的 {@link Pattern} 实例
|
||||
* @return 缓存的 Pattern 实例。如果缓存已满,则返回 {@code null}。
|
||||
*/
|
||||
public static Pattern cachePattern(final Pattern pattern) {
|
||||
Preconditions.checkNotNull(pattern, "The pattern can not be null.");
|
||||
if (PATTERN_CACHE.size() >= MAX_CACHE_SIZE) {
|
||||
return null;
|
||||
}
|
||||
final String patternStr = pattern.pattern();
|
||||
final Pattern pre = PATTERN_CACHE.putIfAbsent(patternStr, pattern);
|
||||
return pre != null ? pre : pattern;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 {@code input} 是否匹配 {@code pattern}。
|
||||
*
|
||||
* @param input 输入
|
||||
* @param pattern 正则
|
||||
* @return 判断结果
|
||||
*/
|
||||
public static boolean matches(@Nullable final CharSequence input, final Pattern pattern) {
|
||||
Preconditions.checkNotNull(pattern, "The pattern can not be null.");
|
||||
return matchesInternal(input, pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 {@code input} 是否匹配 {@code patterns} 中的一个。
|
||||
*
|
||||
* @param input 输入
|
||||
* @param patterns 正则
|
||||
* @return 判断结果
|
||||
*/
|
||||
public static boolean matchesOne(@Nullable final CharSequence input, final Pattern[] patterns) {
|
||||
Preconditions.checkNotNull(patterns, "Patterns can not be null.");
|
||||
Preconditions.checkArgument(allNotNull(patterns), "The pattern can not be null.");
|
||||
return matchesOneInternal(input, patterns);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 {@code input} 是否匹配全部正则。
|
||||
*
|
||||
* @param input 输入
|
||||
* @param patterns 正则
|
||||
* @return 判断结果
|
||||
*/
|
||||
public static boolean matchesAll(@Nullable final CharSequence input, final Pattern[] patterns) {
|
||||
Preconditions.checkNotNull(patterns, "Patterns can not be null.");
|
||||
Preconditions.checkArgument(allNotNull(patterns), "The pattern can not be null.");
|
||||
return matchesAllInternal(input, patterns);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 {@code input} 是否匹配 {@code pattern}。
|
||||
*
|
||||
* @param input 输入
|
||||
* @param pattern 正则表达式
|
||||
* @param cachePattern 是否缓存 {@link Pattern} 实例
|
||||
* @return 判断结果
|
||||
*/
|
||||
public static boolean matches(@Nullable final CharSequence input, final String pattern,
|
||||
final boolean cachePattern) {
|
||||
Preconditions.checkNotNull(pattern, "The pattern can not be null.");
|
||||
Pattern p = cachePattern
|
||||
? getAndCachePatternInternal(pattern)
|
||||
: getPatternInternal(pattern);
|
||||
return matchesInternal(input, p);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 {@code input} 是否匹配 {@code pattern}。不缓存 {@link Pattern} 实例。
|
||||
*
|
||||
* @param input 输入
|
||||
* @param pattern 正则表达式
|
||||
* @return 判断结果
|
||||
*/
|
||||
public static boolean matches(@Nullable final CharSequence input, final String pattern) {
|
||||
Preconditions.checkNotNull(pattern, "The pattern can not be null.");
|
||||
return matchesInternal(input, getPatternInternal(pattern));
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 {@code input} 是否匹配 {@code patterns} 中的一个。
|
||||
*
|
||||
* @param input 输入
|
||||
* @param patterns 正则表达式
|
||||
* @param cachePattern 是否缓存 {@link Pattern} 实例
|
||||
* @return 判断结果
|
||||
*/
|
||||
public static boolean matchesOne(@Nullable final CharSequence input, final String[] patterns,
|
||||
final boolean cachePattern) {
|
||||
Preconditions.checkNotNull(patterns, "Patterns can not be null.");
|
||||
Preconditions.checkArgument(allNotNull(patterns), "The pattern can not be null.");
|
||||
final Pattern[] patternSet = cachePattern
|
||||
? getAndCachePatternsInternal(patterns)
|
||||
: getPatternsInternal(patterns);
|
||||
return matchesOneInternal(input, patternSet);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 {@code input} 是否匹配 {@code patterns} 中的一个。不缓存 {@link Pattern} 实例。
|
||||
*
|
||||
* @param input 输入
|
||||
* @param patterns 正则表达式
|
||||
* @return 判断结果
|
||||
*/
|
||||
public static boolean matchesOne(@Nullable final CharSequence input, final String[] patterns) {
|
||||
Preconditions.checkNotNull(patterns, "Patterns can not be null.");
|
||||
Preconditions.checkArgument(allNotNull(patterns), "The pattern can not be null.");
|
||||
final Pattern[] patternSet = getPatternsInternal(patterns);
|
||||
return matchesOneInternal(input, patternSet);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 {@code input} 是否匹配全部正则。
|
||||
*
|
||||
* @param input 输入
|
||||
* @param patterns 正则表达式
|
||||
* @param cachePattern 是否缓存 {@link Pattern} 实例
|
||||
* @return 判断结果
|
||||
*/
|
||||
public static boolean matchesAll(@Nullable final CharSequence input, final String[] patterns,
|
||||
final boolean cachePattern) {
|
||||
Preconditions.checkNotNull(patterns, "Patterns can not be null.");
|
||||
Preconditions.checkArgument(allNotNull(patterns), "The pattern can not be null.");
|
||||
final Pattern[] patternSet = cachePattern
|
||||
? getAndCachePatternsInternal(patterns)
|
||||
: getPatternsInternal(patterns);
|
||||
return matchesAllInternal(input, patternSet);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 {@code input} 是否匹配全部正则。不缓存 {@link Pattern} 实例。
|
||||
*
|
||||
* @param input 输入
|
||||
* @param patterns 正则表达式
|
||||
* @return 判断结果
|
||||
*/
|
||||
public static boolean matchesAll(@Nullable final CharSequence input, final String[] patterns) {
|
||||
Preconditions.checkNotNull(patterns, "Patterns can not be null.");
|
||||
Preconditions.checkArgument(allNotNull(patterns), "The pattern can not be null.");
|
||||
final Pattern[] patternSet = getPatternsInternal(patterns);
|
||||
return matchesAllInternal(input, patternSet);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 Matcher。
|
||||
*
|
||||
* @param input 输入
|
||||
* @param pattern 正则
|
||||
* @return 结果
|
||||
*/
|
||||
public static Matcher getMatcher(final CharSequence input, final Pattern pattern) {
|
||||
Preconditions.checkNotNull(input, "The input can not be null.");
|
||||
Preconditions.checkNotNull(pattern, "The pattern can not be null.");
|
||||
return pattern.matcher(input);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 Matcher。
|
||||
*
|
||||
* @param input 输入
|
||||
* @param pattern 正则表达式
|
||||
* @param cachePattern 是否缓存 {@link Pattern} 实例
|
||||
* @return 结果
|
||||
*/
|
||||
public static Matcher getMatcher(final CharSequence input, final String pattern, boolean cachePattern) {
|
||||
Preconditions.checkNotNull(input, "The input can not be null.");
|
||||
Preconditions.checkNotNull(pattern, "The pattern can not be null.");
|
||||
final Pattern p = cachePattern
|
||||
? getAndCachePatternInternal(pattern)
|
||||
: getPatternInternal(pattern);
|
||||
return p.matcher(input);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成 Matcher。不缓存 {@link Pattern} 实例。
|
||||
*
|
||||
* @param input 输入
|
||||
* @param pattern 正则表达式
|
||||
* @return 结果
|
||||
*/
|
||||
public static Matcher getMatcher(final CharSequence input, final String pattern) {
|
||||
Preconditions.checkNotNull(input, "The input can not be null.");
|
||||
Preconditions.checkNotNull(pattern, "The pattern can not be null.");
|
||||
return getPatternInternal(pattern).matcher(input);
|
||||
}
|
||||
|
||||
// ========== internal methods ==========
|
||||
|
||||
/**
|
||||
* 获取 {@link Pattern} 实例。
|
||||
*
|
||||
* @param pattern 正则表达式
|
||||
* @param cachePattern 是否缓存 {@link Pattern} 实例
|
||||
* @return {@link Pattern} 实例
|
||||
*/
|
||||
@SuppressWarnings("null")
|
||||
@Nonnull
|
||||
private static Pattern getAndCachePatternInternal(@Nonnull final String pattern) {
|
||||
if (PATTERN_CACHE.size() < MAX_CACHE_SIZE) {
|
||||
return ConcurrentHashMapUtil.computeIfAbsentForJava8(PATTERN_CACHE, pattern, Pattern::compile);
|
||||
}
|
||||
Pattern result = PATTERN_CACHE.get(pattern);
|
||||
if (result != null) {
|
||||
return result;
|
||||
}
|
||||
return Pattern.compile(pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取 {@link Pattern} 实例,不缓存。
|
||||
*
|
||||
* @param pattern 正则表达式
|
||||
* @return {@link Pattern} 实例
|
||||
*/
|
||||
@SuppressWarnings("null")
|
||||
@Nonnull
|
||||
private static Pattern getPatternInternal(@Nonnull final String pattern) {
|
||||
Pattern result = PATTERN_CACHE.get(pattern);
|
||||
if (result == null) {
|
||||
result = Pattern.compile(pattern);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将各个正则表达式转为 {@link Pattern} 实例。
|
||||
*
|
||||
* @param patterns 正则表达式
|
||||
* @return {@link Pattern} 实例数组
|
||||
*/
|
||||
@SuppressWarnings("null")
|
||||
@Nonnull
|
||||
private static Pattern[] getAndCachePatternsInternal(@Nonnull final String[] patterns) {
|
||||
return Arrays.stream(patterns)
|
||||
.map(RegexUtil::getAndCachePatternInternal)
|
||||
.toArray(Pattern[]::new);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将各个正则表达式转为 {@link Pattern} 实例。
|
||||
*
|
||||
* @param patterns 正则表达式
|
||||
* @return {@link Pattern} 实例数组
|
||||
*/
|
||||
@SuppressWarnings("null")
|
||||
@Nonnull
|
||||
private static Pattern[] getPatternsInternal(@Nonnull final String[] patterns) {
|
||||
return Arrays.stream(patterns)
|
||||
.map(RegexUtil::getPatternInternal)
|
||||
.toArray(Pattern[]::new);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 {@code input} 是否匹配 {@code pattern}。
|
||||
*
|
||||
* @param input 输入
|
||||
* @param pattern 正则
|
||||
* @return 判断结果
|
||||
*/
|
||||
private static boolean matchesInternal(@Nullable final CharSequence input, @Nonnull final Pattern pattern) {
|
||||
return input != null && pattern.matcher(input).matches();
|
||||
}
|
||||
|
||||
@SuppressWarnings("null")
|
||||
private static boolean matchesOneInternal(@Nullable final CharSequence input, @Nonnull final Pattern[] patterns) {
|
||||
if (input == null) {
|
||||
return false;
|
||||
}
|
||||
for (Pattern pattern : patterns) {
|
||||
if (matchesInternal(input, pattern)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@SuppressWarnings("null")
|
||||
private static boolean matchesAllInternal(final CharSequence input, final Pattern[] patterns) {
|
||||
if (input == null) {
|
||||
return false;
|
||||
}
|
||||
for (Pattern pattern : patterns) {
|
||||
if (!matchesInternal(input, pattern)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private static <T> boolean allNotNull(T[] array) {
|
||||
return Arrays.stream(array).allMatch(Objects::nonNull);
|
||||
}
|
||||
|
||||
private RegexUtil() {
|
||||
// 不允许实例化
|
||||
throw new IllegalStateException("Utility class");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,171 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedList;
|
||||
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;
|
||||
|
||||
public abstract class BasePropertyValidator< //
|
||||
TObj, //
|
||||
TProperty, //
|
||||
TPropertyValidator extends BasePropertyValidator<TObj, TProperty, TPropertyValidator>> {
|
||||
|
||||
private final Function<TObj, ? extends TProperty> getter;
|
||||
|
||||
private final List<Consumer<TProperty>> consumers = new LinkedList<>();
|
||||
|
||||
protected BasePropertyValidator(Function<TObj, ? extends TProperty> getter) {
|
||||
this.getter = getter;
|
||||
}
|
||||
|
||||
public final TPropertyValidator withRule(Predicate<? super TProperty> rule) {
|
||||
return withRule(rule, v -> new IllegalArgumentException());
|
||||
}
|
||||
|
||||
public final TPropertyValidator withRule(
|
||||
Predicate<? super TProperty> rule, String errMsg) {
|
||||
return withRule(rule, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public final <E extends RuntimeException> TPropertyValidator withRule(
|
||||
Predicate<? super TProperty> rule, Supplier<E> e) {
|
||||
return withRule(rule, convertExceptionCreator(e));
|
||||
}
|
||||
|
||||
public final <E extends RuntimeException> TPropertyValidator withRule(
|
||||
Predicate<? super TProperty> rule, Function<TProperty, E> e) {
|
||||
this.consumers.add(v -> {
|
||||
if (!rule.test(v)) {
|
||||
throw e.apply(v);
|
||||
}
|
||||
});
|
||||
return thisObject();
|
||||
}
|
||||
|
||||
public final <T extends TObj> void validate(T obj) {
|
||||
for (Consumer<TProperty> consumer : consumers) {
|
||||
consumer.accept(getter.apply(obj));
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract TPropertyValidator thisObject();
|
||||
|
||||
// ====================
|
||||
// ====== Object ======
|
||||
// ====================
|
||||
|
||||
// ====== notNull =====
|
||||
|
||||
public TPropertyValidator notNull() {
|
||||
return notNull("Value could not be null.");
|
||||
}
|
||||
|
||||
public TPropertyValidator notNull(String errMsg) {
|
||||
return notNull(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> TPropertyValidator notNull(Supplier<E> exceptionCreator) {
|
||||
return notNull(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> TPropertyValidator notNull(Function<TProperty, E> exceptionCreator) {
|
||||
withRule(Objects::nonNull, exceptionCreator);
|
||||
return thisObject();
|
||||
}
|
||||
|
||||
// ====== isNull =====
|
||||
|
||||
public TPropertyValidator isNull(String errMsg) {
|
||||
return isNull(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> TPropertyValidator isNull(Supplier<E> exceptionCreator) {
|
||||
return isNull(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> TPropertyValidator isNull(Function<TProperty, E> exceptionCreator) {
|
||||
withRule(Objects::isNull, exceptionCreator);
|
||||
return thisObject();
|
||||
}
|
||||
|
||||
// ===== equals =====
|
||||
|
||||
public TPropertyValidator equalsThat(Object that) {
|
||||
return equalsThat(that, value -> new IllegalArgumentException(String.format("(%s) 必须与 (%s) 相等", value, that)));
|
||||
}
|
||||
|
||||
public TPropertyValidator equalsThat(Object that, String errMsg) {
|
||||
return equalsThat(that, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> TPropertyValidator equalsThat(
|
||||
Object that, Supplier<E> exceptionCreator) {
|
||||
return equalsThat(that, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> TPropertyValidator equalsThat(
|
||||
Object that, Function<TProperty, E> exceptionCreator) {
|
||||
withRule(value -> Objects.equals(value, that), exceptionCreator);
|
||||
return thisObject();
|
||||
}
|
||||
|
||||
// ===== isTrue =====
|
||||
|
||||
public TPropertyValidator isTrue(Predicate<TProperty> condition) {
|
||||
return isTrue(condition, "无效的用户输入");
|
||||
}
|
||||
|
||||
public TPropertyValidator isTrue(Predicate<TProperty> condition, String errMsg) {
|
||||
return isTrue(condition, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> TPropertyValidator isTrue(
|
||||
Predicate<TProperty> condition,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return isTrue(condition, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> TPropertyValidator isTrue(
|
||||
Predicate<TProperty> condition,
|
||||
Function<TProperty, E> exceptionCreator) {
|
||||
withRule(condition, exceptionCreator);
|
||||
return thisObject();
|
||||
}
|
||||
|
||||
// ===== isTrue =====
|
||||
|
||||
public TPropertyValidator isTrue(Collection<Predicate<TProperty>> conditions) {
|
||||
return isTrue(conditions, "无效的用户输入");
|
||||
}
|
||||
|
||||
public TPropertyValidator isTrue(Collection<Predicate<TProperty>> conditions, String errMsg) {
|
||||
return isTrue(conditions, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> TPropertyValidator isTrue(
|
||||
Collection<Predicate<TProperty>> conditions,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return isTrue(conditions, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> TPropertyValidator isTrue(
|
||||
Collection<Predicate<TProperty>> conditions,
|
||||
Function<TProperty, E> exceptionCreator) {
|
||||
for (Predicate<TProperty> condition : conditions) {
|
||||
withRule(condition, exceptionCreator);
|
||||
}
|
||||
return thisObject();
|
||||
}
|
||||
|
||||
static <V> Function<V, IllegalArgumentException> convertExceptionCreator(String errMsg) {
|
||||
return value -> new IllegalArgumentException(errMsg);
|
||||
}
|
||||
|
||||
static <V, E extends RuntimeException> Function<V, E> convertExceptionCreator(Supplier<E> exceptionSupplier) {
|
||||
return value -> exceptionSupplier.get();
|
||||
}
|
||||
}
|
|
@ -3,32 +3,24 @@ package xyz.zhouxy.plusone.validator;
|
|||
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 java.util.regex.Pattern;
|
||||
|
||||
import com.google.common.base.Strings;
|
||||
|
||||
import xyz.zhouxy.plusone.commons.util.Predicates;
|
||||
import xyz.zhouxy.plusone.commons.util.RegexUtil;
|
||||
|
||||
public class BaseValidator<T> {
|
||||
private final List<Consumer<T>> rules = new ArrayList<>();
|
||||
private final List<PropertyValidator<T, ?, ?>> propertyValidators = new ArrayList<>();
|
||||
private final List<Consumer<? super T>> rules = new ArrayList<>();
|
||||
|
||||
protected void withRule(final Predicate<T> rule, final String errorMessage) {
|
||||
withRule(rule, () -> new InvalidInputException(errorMessage));
|
||||
withRule(rule, () -> new IllegalArgumentException(errorMessage));
|
||||
}
|
||||
|
||||
protected <E extends RuntimeException> void withRule(Predicate<T> rule, Supplier<E> exceptionBuilder) {
|
||||
protected <E extends RuntimeException> void withRule(Predicate<? super T> rule, Supplier<E> exceptionBuilder) {
|
||||
withRule(rule, value -> exceptionBuilder.get());
|
||||
}
|
||||
|
||||
protected <E extends RuntimeException> void withRule(Predicate<T> condition,
|
||||
Function<T, E> exceptionBuilder) {
|
||||
protected <E extends RuntimeException> void withRule(
|
||||
Predicate<? super T> condition, Function<T, E> exceptionBuilder) {
|
||||
withRule(value -> {
|
||||
if (!condition.test(value)) {
|
||||
throw exceptionBuilder.apply(value);
|
||||
|
@ -36,521 +28,47 @@ public class BaseValidator<T> {
|
|||
});
|
||||
}
|
||||
|
||||
protected void withRule(Consumer<T> rule) {
|
||||
protected void withRule(Consumer<? super T> rule) {
|
||||
this.rules.add(rule);
|
||||
}
|
||||
|
||||
protected final <R> ObjectValidator<T, R> ruleFor(Function<T, R> getter) {
|
||||
ObjectValidator<T, R> validValueHolder = new ObjectValidator<>(getter);
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
ObjectValidator<T, R> validator = new ObjectValidator<>(getter);
|
||||
this.rules.add(validator::validate);
|
||||
return validator;
|
||||
}
|
||||
|
||||
protected final IntValidator<T> ruleForInt(Function<T, ?> getter) {
|
||||
IntValidator<T> validValueHolder = new IntValidator<>(getter);
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
protected final IntValidator<T> ruleForInt(Function<T, Integer> getter) {
|
||||
IntValidator<T> validator = new IntValidator<>(getter);
|
||||
this.rules.add(validator::validate);
|
||||
return validator;
|
||||
}
|
||||
|
||||
protected final DoubleValidator<T> ruleForDouble(Function<T, ?> getter) {
|
||||
DoubleValidator<T> validValueHolder = new DoubleValidator<>(getter);
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
protected final DoubleValidator<T> ruleForDouble(Function<T, Double> getter) {
|
||||
DoubleValidator<T> validator = new DoubleValidator<>(getter);
|
||||
this.rules.add(validator::validate);
|
||||
return validator;
|
||||
}
|
||||
|
||||
protected final BoolValidator<T> ruleForBool(Function<T, ?> getter) {
|
||||
BoolValidator<T> validValueHolder = new BoolValidator<>(getter);
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
protected final BoolValidator<T> ruleForBool(Function<T, Boolean> getter) {
|
||||
BoolValidator<T> validator = new BoolValidator<>(getter);
|
||||
this.rules.add(validator::validate);
|
||||
return validator;
|
||||
}
|
||||
|
||||
protected final StringValidator<T> ruleForString(Function<T, ?> getter) {
|
||||
StringValidator<T> validValueHolder = new StringValidator<>(getter);
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
protected final StringValidator<T> ruleForString(Function<T, String> getter) {
|
||||
StringValidator<T> validator = new StringValidator<>(getter);
|
||||
this.rules.add(validator::validate);
|
||||
return validator;
|
||||
}
|
||||
|
||||
protected final <E> CollectionValidator<T, E> ruleForCollection(Function<T, Collection<E>> getter) {
|
||||
CollectionValidator<T, E> validValueHolder = new CollectionValidator<>(getter);
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
CollectionValidator<T, E> validator = new CollectionValidator<>(getter);
|
||||
this.rules.add(validator::validate);
|
||||
return validator;
|
||||
}
|
||||
|
||||
public void validate(T obj) {
|
||||
for (Consumer<T> rule : this.rules) {
|
||||
rule.accept(obj);
|
||||
this.rules.forEach(rule -> rule.accept(obj));
|
||||
}
|
||||
for (PropertyValidator<T, ?, ?> valueValidator : this.propertyValidators) {
|
||||
valueValidator.validate(obj);
|
||||
}
|
||||
}
|
||||
|
||||
abstract static class PropertyValidator<DTO, PROPERTY, THIS> {
|
||||
Function<DTO, ?> getter;
|
||||
Validator<PROPERTY> validator = new Validator<>();
|
||||
|
||||
PropertyValidator(Function<DTO, ?> getter) {
|
||||
this.getter = getter;
|
||||
}
|
||||
|
||||
<E extends RuntimeException> void withRule(Predicate<? super PROPERTY> condition,
|
||||
Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(value -> {
|
||||
if (!condition.test(value)) {
|
||||
throw exceptionCreator.apply(value);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void withRule(Consumer<PROPERTY> rule) {
|
||||
this.validator.addRule(rule);
|
||||
}
|
||||
|
||||
// ====================
|
||||
// ====== Object ======
|
||||
// ====================
|
||||
|
||||
// ====== notNull =====
|
||||
|
||||
public THIS notNull() {
|
||||
return notNull("Value could not be null.");
|
||||
}
|
||||
|
||||
public THIS notNull(String errMsg) {
|
||||
return notNull(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> THIS notNull(Supplier<E> exceptionCreator) {
|
||||
return notNull(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> THIS notNull(Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(Objects::nonNull, exceptionCreator);
|
||||
return thisObject();
|
||||
}
|
||||
|
||||
// ====== isNull =====
|
||||
|
||||
public THIS isNull(String errMsg) {
|
||||
return isNull(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> THIS isNull(Supplier<E> exceptionCreator) {
|
||||
return isNull(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> THIS isNull(Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(Objects::isNull, exceptionCreator);
|
||||
return thisObject();
|
||||
}
|
||||
|
||||
// ===== equals =====
|
||||
|
||||
public THIS equalsThat(Object that) {
|
||||
return equalsThat(that, value -> new InvalidInputException("(%s) 必须与 (%s) 相等", value, that));
|
||||
}
|
||||
|
||||
public THIS equalsThat(Object that, String errMsg) {
|
||||
return equalsThat(that, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> THIS equalsThat(
|
||||
Object that, Supplier<E> exceptionCreator) {
|
||||
return equalsThat(that, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> THIS equalsThat(
|
||||
Object that, Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(value -> Objects.equals(value, that), exceptionCreator);
|
||||
return thisObject();
|
||||
}
|
||||
|
||||
// ===== isTrue =====
|
||||
|
||||
public THIS isTrue(Predicate<? super PROPERTY> condition) {
|
||||
return isTrue(condition, "无效的用户输入");
|
||||
}
|
||||
|
||||
public THIS isTrue(Predicate<? super PROPERTY> condition, String errMsg) {
|
||||
return isTrue(condition, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> THIS isTrue(
|
||||
Predicate<? super PROPERTY> condition,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return isTrue(condition, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> THIS isTrue(
|
||||
Predicate<? super PROPERTY> condition,
|
||||
Function<PROPERTY, E> exceptionCreator) {
|
||||
withRule(condition, exceptionCreator);
|
||||
return thisObject();
|
||||
}
|
||||
|
||||
// ===== isTrue =====
|
||||
|
||||
public THIS isTrue(Collection<Predicate<PROPERTY>> conditions) {
|
||||
return isTrue(conditions, "无效的用户输入");
|
||||
}
|
||||
|
||||
public THIS isTrue(Collection<Predicate<PROPERTY>> conditions, String errMsg) {
|
||||
return isTrue(conditions, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> THIS isTrue(
|
||||
Collection<Predicate<PROPERTY>> conditions,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return isTrue(conditions, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> THIS isTrue(
|
||||
Collection<Predicate<PROPERTY>> conditions,
|
||||
Function<PROPERTY, E> exceptionCreator) {
|
||||
for (Predicate<PROPERTY> condition : conditions) {
|
||||
withRule(condition, exceptionCreator);
|
||||
}
|
||||
return thisObject();
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
void validate(DTO obj) {
|
||||
PROPERTY value = (PROPERTY) this.getter.apply(obj);
|
||||
this.validator.validate(value);
|
||||
}
|
||||
|
||||
static <V> Function<V, InvalidInputException> convertExceptionCreator(String errMsg) {
|
||||
return value -> new InvalidInputException(errMsg);
|
||||
}
|
||||
|
||||
static <V, E extends RuntimeException> Function<V, E> convertExceptionCreator(
|
||||
Supplier<E> exceptionSupplier) {
|
||||
return value -> exceptionSupplier.get();
|
||||
}
|
||||
|
||||
protected abstract THIS thisObject();
|
||||
}
|
||||
|
||||
public static class BoolValidator<DTO> extends PropertyValidator<DTO, Boolean, BoolValidator<DTO>> {
|
||||
|
||||
BoolValidator(Function<DTO, ?> getter) {
|
||||
super(getter);
|
||||
}
|
||||
|
||||
// ====== isTrue ======
|
||||
|
||||
public BoolValidator<DTO> isTrue() {
|
||||
return isTrue("The value must be true.");
|
||||
}
|
||||
|
||||
public BoolValidator<DTO> isTrue(String errMsg) {
|
||||
return isTrue(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> BoolValidator<DTO> isTrue(Supplier<E> exceptionCreator) {
|
||||
return isTrue(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> BoolValidator<DTO> isTrue(
|
||||
Function<Boolean, E> exceptionCreator) {
|
||||
super.withRule(Boolean.TRUE::equals, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ====== isFalse ======
|
||||
|
||||
public BoolValidator<DTO> isFalse() {
|
||||
return isFalse("The value must be false.");
|
||||
}
|
||||
|
||||
public BoolValidator<DTO> isFalse(String errMsg) {
|
||||
return isFalse(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> BoolValidator<DTO> isFalse(Supplier<E> exceptionCreator) {
|
||||
return isFalse(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> BoolValidator<DTO> isFalse(
|
||||
Function<Boolean, E> exceptionCreator) {
|
||||
super.withRule(Boolean.FALSE::equals, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected BoolValidator<DTO> thisObject() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
public static class DoubleValidator<DTO> extends PropertyValidator<DTO, Double, DoubleValidator<DTO>> {
|
||||
|
||||
DoubleValidator(Function<DTO, ?> getter) {
|
||||
super(getter);
|
||||
}
|
||||
|
||||
public DoubleValidator<DTO> between(double min, double max) {
|
||||
return between(min, max, String.format("数值不在 %s 和 %s 之间", String.valueOf(min), String.valueOf(max)));
|
||||
}
|
||||
|
||||
public DoubleValidator<DTO> between(double min, double max, String errMsg) {
|
||||
return between(min, max, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> DoubleValidator<DTO> between(double min, double max,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return between(min, max, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> DoubleValidator<DTO> between(double min, double max,
|
||||
Function<Double, E> exceptionCreator) {
|
||||
super.withRule(value -> (value >= min && value < max), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DoubleValidator<DTO> thisObject() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
public static class IntValidator<DTO> extends PropertyValidator<DTO, Integer, IntValidator<DTO>> {
|
||||
|
||||
IntValidator(Function<DTO, ?> getter) {
|
||||
super(getter);
|
||||
}
|
||||
|
||||
public IntValidator<DTO> between(int min, int max) {
|
||||
return between(min, max, String.format("数值不在 %d 和 %d 之间", min, max));
|
||||
}
|
||||
|
||||
public IntValidator<DTO> between(int min, int max, String errMsg) {
|
||||
return between(min, max, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> IntValidator<DTO> between(int min, int max,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return between(min, max, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> IntValidator<DTO> between(int min, int max,
|
||||
Function<Integer, E> exceptionCreator) {
|
||||
super.withRule(value -> (value >= min && value < max), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected IntValidator<DTO> thisObject() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
public static class StringValidator<DTO> extends PropertyValidator<DTO, String, StringValidator<DTO>> {
|
||||
|
||||
StringValidator(Function<DTO, ?> getter) {
|
||||
super(getter);
|
||||
}
|
||||
|
||||
// ====================
|
||||
// ====== String ======
|
||||
// ====================
|
||||
|
||||
// ===== matches =====
|
||||
|
||||
public StringValidator<DTO> matches(Pattern regex, String errMsg) {
|
||||
return matches(regex, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matches(
|
||||
Pattern regex,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return matches(regex, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matches(
|
||||
Pattern regex,
|
||||
Function<String, E> exceptionCreator) {
|
||||
super.withRule(input -> RegexUtil.matches(input, regex), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ===== matchesOne =====
|
||||
|
||||
public StringValidator<DTO> matchesOne(Pattern[] regexs, String errMsg) {
|
||||
return matchesOne(regexs, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matchesOne(
|
||||
Pattern[] regexs,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return matchesOne(regexs, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matchesOne(
|
||||
Pattern[] regexs,
|
||||
Function<String, E> exceptionCreator) {
|
||||
super.withRule(input -> RegexUtil.matchesOne(input, regexs), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
public StringValidator<DTO> matchesOne(List<Pattern> regexs, String errMsg) {
|
||||
return matchesOne(regexs, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matchesOne(
|
||||
List<Pattern> regexs,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return matchesOne(regexs, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matchesOne(
|
||||
List<Pattern> regexs,
|
||||
Function<String, E> exceptionCreator) {
|
||||
super.withRule(input -> RegexUtil.matchesOne(input, regexs.toArray(new Pattern[regexs.size()])),
|
||||
exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ===== matchesAll =====
|
||||
|
||||
public StringValidator<DTO> matchesAll(Pattern[] regexs, String errMsg) {
|
||||
return matchesAll(regexs, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matchesAll(
|
||||
Pattern[] regexs,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return matchesAll(regexs, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matchesAll(
|
||||
Pattern[] regexs,
|
||||
Function<String, E> exceptionCreator) {
|
||||
super.withRule(input -> RegexUtil.matchesAll(input, regexs), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
public StringValidator<DTO> matchesAll(Collection<Pattern> regexs, String errMsg) {
|
||||
return matchesAll(regexs, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matchesAll(
|
||||
Collection<Pattern> regexs,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return matchesAll(regexs, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matchesAll(
|
||||
Collection<Pattern> regexs,
|
||||
Function<String, E> exceptionCreator) {
|
||||
super.withRule(input -> RegexUtil.matchesAll(input, regexs.toArray(new Pattern[regexs.size()])),
|
||||
exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ====== notEmpty =====
|
||||
|
||||
public StringValidator<DTO> notEmpty() {
|
||||
return notEmpty("The string argument must not be empty.");
|
||||
}
|
||||
|
||||
public StringValidator<DTO> notEmpty(String errMsg) {
|
||||
return notEmpty(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> notEmpty(Supplier<E> exceptionCreator) {
|
||||
return notEmpty(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> notEmpty(
|
||||
Function<String, E> exceptionCreator) {
|
||||
super.withRule(Predicates.not(Strings::isNullOrEmpty), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ====== isEmpty =====
|
||||
|
||||
public StringValidator<DTO> isEmpty() {
|
||||
return notEmpty("The string argument must be empty.");
|
||||
}
|
||||
|
||||
public StringValidator<DTO> isEmpty(String errMsg) {
|
||||
return isEmpty(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> isEmpty(Supplier<E> exceptionCreator) {
|
||||
return isEmpty(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> isEmpty(
|
||||
Function<String, E> exceptionCreator) {
|
||||
super.withRule(Strings::isNullOrEmpty, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected StringValidator<DTO> thisObject() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
public static class ObjectValidator<DTO, T> extends PropertyValidator<DTO, T, ObjectValidator<DTO, T>> {
|
||||
|
||||
ObjectValidator(Function<DTO, T> getter) {
|
||||
super(getter);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ObjectValidator<DTO, T> thisObject() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
public static class CollectionValidator<DTO, T>
|
||||
extends PropertyValidator<DTO, Collection<T>, CollectionValidator<DTO, T>> {
|
||||
|
||||
CollectionValidator(Function<DTO, Collection<T>> getter) {
|
||||
super(getter);
|
||||
}
|
||||
|
||||
// ====== notEmpty =====
|
||||
|
||||
public CollectionValidator<DTO, T> notEmpty(String errMsg) {
|
||||
return notEmpty(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> CollectionValidator<DTO, T> notEmpty(Supplier<E> exceptionCreator) {
|
||||
return notEmpty(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> CollectionValidator<DTO, T> notEmpty(
|
||||
Function<Collection<T>, E> exceptionCreator) {
|
||||
super.withRule(value -> value != null && !value.isEmpty(), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ====== isEmpty =====
|
||||
|
||||
public CollectionValidator<DTO, T> isEmpty(String errMsg) {
|
||||
return isEmpty(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> CollectionValidator<DTO, T> isEmpty(Supplier<E> exceptionCreator) {
|
||||
return isEmpty(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> CollectionValidator<DTO, T> isEmpty(
|
||||
Function<Collection<T>, E> exceptionCreator) {
|
||||
super.withRule(value -> value == null || value.isEmpty(), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected CollectionValidator<DTO, T> thisObject() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -0,0 +1,56 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class BoolValidator<DTO> extends BasePropertyValidator<DTO, Boolean, BoolValidator<DTO>> {
|
||||
|
||||
BoolValidator(Function<DTO, Boolean> getter) {
|
||||
super(getter);
|
||||
}
|
||||
|
||||
// ====== isTrue ======
|
||||
|
||||
public BoolValidator<DTO> isTrue() {
|
||||
return isTrue("The value must be true.");
|
||||
}
|
||||
|
||||
public BoolValidator<DTO> isTrue(String errMsg) {
|
||||
return isTrue(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> BoolValidator<DTO> isTrue(Supplier<E> exceptionCreator) {
|
||||
return isTrue(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> BoolValidator<DTO> isTrue(
|
||||
Function<Boolean, E> exceptionCreator) {
|
||||
withRule(Boolean.TRUE::equals, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ====== isFalse ======
|
||||
|
||||
public BoolValidator<DTO> isFalse() {
|
||||
return isFalse("The value must be false.");
|
||||
}
|
||||
|
||||
public BoolValidator<DTO> isFalse(String errMsg) {
|
||||
return isFalse(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> BoolValidator<DTO> isFalse(Supplier<E> exceptionCreator) {
|
||||
return isFalse(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> BoolValidator<DTO> isFalse(
|
||||
Function<Boolean, E> exceptionCreator) {
|
||||
withRule(Boolean.FALSE::equals, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected BoolValidator<DTO> thisObject() {
|
||||
return this;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,52 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import xyz.zhouxy.plusone.commons.collection.CollectionTools;
|
||||
|
||||
public class CollectionValidator<DTO, T>
|
||||
extends BasePropertyValidator<DTO, Collection<T>, CollectionValidator<DTO, T>> {
|
||||
|
||||
CollectionValidator(Function<DTO, Collection<T>> getter) {
|
||||
super(getter);
|
||||
}
|
||||
|
||||
// ====== notEmpty =====
|
||||
|
||||
public CollectionValidator<DTO, T> notEmpty(String errMsg) {
|
||||
return notEmpty(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> CollectionValidator<DTO, T> notEmpty(Supplier<E> exceptionCreator) {
|
||||
return notEmpty(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> CollectionValidator<DTO, T> notEmpty(
|
||||
Function<Collection<T>, E> exceptionCreator) {
|
||||
withRule(CollectionTools::isNotEmpty, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ====== isEmpty =====
|
||||
|
||||
public CollectionValidator<DTO, T> isEmpty(String errMsg) {
|
||||
return isEmpty(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> CollectionValidator<DTO, T> isEmpty(Supplier<E> exceptionCreator) {
|
||||
return isEmpty(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> CollectionValidator<DTO, T> isEmpty(
|
||||
Function<Collection<T>, E> exceptionCreator) {
|
||||
withRule(CollectionTools::isEmpty, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected CollectionValidator<DTO, T> thisObject() {
|
||||
return this;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class DoubleValidator<DTO> extends BasePropertyValidator<DTO, Double, DoubleValidator<DTO>> {
|
||||
|
||||
DoubleValidator(Function<DTO, Double> getter) {
|
||||
super(getter);
|
||||
}
|
||||
|
||||
public DoubleValidator<DTO> between(double min, double max) {
|
||||
return between(min, max, String.format("数值不在 %s 和 %s 之间", String.valueOf(min), String.valueOf(max)));
|
||||
}
|
||||
|
||||
public DoubleValidator<DTO> between(double min, double max, String errMsg) {
|
||||
return between(min, max, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> DoubleValidator<DTO> between(double min, double max,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return between(min, max, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> DoubleValidator<DTO> between(double min, double max,
|
||||
Function<Double, E> exceptionCreator) {
|
||||
withRule(value -> (value >= min && value < max), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected DoubleValidator<DTO> thisObject() {
|
||||
return this;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
/**
|
||||
* 自带校验方法,校验不通过时直接抛异常。
|
||||
*
|
||||
* @author <a href="https://gitee.com/zhouxy108">ZhouXY</a>
|
||||
*
|
||||
* @see ValidateUtil
|
||||
* @see BaseValidator
|
||||
*/
|
||||
public interface IValidateRequired {
|
||||
void validate();
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
public class IntValidator<DTO> extends BasePropertyValidator<DTO, Integer, IntValidator<DTO>> {
|
||||
|
||||
IntValidator(Function<DTO, Integer> getter) {
|
||||
super(getter);
|
||||
}
|
||||
|
||||
public IntValidator<DTO> between(int min, int max) {
|
||||
return between(min, max, String.format("数值不在 %d 和 %d 之间", min, max));
|
||||
}
|
||||
|
||||
public IntValidator<DTO> between(int min, int max, String errMsg) {
|
||||
return between(min, max, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> IntValidator<DTO> between(int min, int max,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return between(min, max, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> IntValidator<DTO> between(int min, int max,
|
||||
Function<Integer, E> exceptionCreator) {
|
||||
withRule(value -> (value >= min && value < max), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected IntValidator<DTO> thisObject() {
|
||||
return this;
|
||||
}
|
||||
}
|
|
@ -1,31 +0,0 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
/**
|
||||
* 用户请求参数错误
|
||||
*
|
||||
* @author ZhouXY
|
||||
*/
|
||||
public class InvalidInputException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 7956661913360059670L;
|
||||
|
||||
public InvalidInputException() {
|
||||
super("用户请求参数错误");
|
||||
}
|
||||
|
||||
public InvalidInputException(String msg) {
|
||||
super(msg);
|
||||
}
|
||||
|
||||
public InvalidInputException(String msgFormat, Object... args) {
|
||||
super(String.format(msgFormat, args));
|
||||
}
|
||||
|
||||
public InvalidInputException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public InvalidInputException(String msg, Throwable cause) {
|
||||
super(msg, cause);
|
||||
}
|
||||
}
|
|
@ -1,103 +1,71 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import xyz.zhouxy.plusone.validator.BaseValidator.*;
|
||||
public abstract class MapValidator<K, V> extends BaseValidator<Map<K, V>> {
|
||||
|
||||
public abstract class MapValidator {
|
||||
private final List<Consumer<Map<String, Object>>> rules = new ArrayList<>();
|
||||
private final List<PropertyValidator<Map<String, Object>, ?, ?>> propertyValidators = new ArrayList<>();
|
||||
private final Set<K> keys;
|
||||
|
||||
private final String[] propertyNames;
|
||||
|
||||
protected MapValidator(List<String> propertyNames) {
|
||||
this.propertyNames = propertyNames.toArray(new String[0]);
|
||||
protected MapValidator(K[] keys) {
|
||||
this(Arrays.asList(keys));
|
||||
}
|
||||
|
||||
protected void withRule(final Predicate<Map<String, Object>> rule, final String errorMessage) {
|
||||
withRule(rule, () -> new InvalidInputException(errorMessage));
|
||||
protected MapValidator(Collection<K> keys) {
|
||||
this.keys = keys.stream().collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
protected <E extends RuntimeException> void withRule(Predicate<Map<String, Object>> rule,
|
||||
Supplier<E> exceptionBuilder) {
|
||||
withRule(rule, value -> exceptionBuilder.get());
|
||||
// ========== validate & validateAndCopy ==========
|
||||
|
||||
public final Map<K, V> validateAndCopy(Map<K, V> obj) {
|
||||
return validateAndCopyInternal(obj, this.keys);
|
||||
}
|
||||
|
||||
protected <E extends RuntimeException> void withRule(Predicate<Map<String, Object>> condition,
|
||||
Function<Map<String, Object>, E> exceptionBuilder) {
|
||||
withRule(value -> {
|
||||
if (!condition.test(value)) {
|
||||
throw exceptionBuilder.apply(value);
|
||||
}
|
||||
});
|
||||
public final Map<K, V> validateAndCopy(Map<K, V> obj, Collection<K> keys) {
|
||||
return validateAndCopyInternal(obj, keys);
|
||||
}
|
||||
|
||||
protected void withRule(Consumer<Map<String, Object>> rule) {
|
||||
this.rules.add(rule);
|
||||
@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));
|
||||
}
|
||||
|
||||
// ========== ruleFor ==========
|
||||
|
||||
protected final ObjectValidator<Map<K, V>, V> ruleFor(K key) {
|
||||
return ruleFor(m -> m.get(key));
|
||||
}
|
||||
|
||||
protected final IntValidator<Map<K, V>> ruleForInt(K key) {
|
||||
return ruleForInt(m -> (Integer) m.get(key));
|
||||
}
|
||||
|
||||
protected final DoubleValidator<Map<K, V>> ruleForDouble(K key) {
|
||||
return ruleForDouble(m -> (Double) m.get(key));
|
||||
}
|
||||
|
||||
protected final BoolValidator<Map<K, V>> ruleForBool(K key) {
|
||||
return ruleForBool(m -> (Boolean) m.get(key));
|
||||
}
|
||||
|
||||
protected final StringValidator<Map<K, V>> ruleForString(K key) {
|
||||
return ruleForString(m -> (String) m.get(key));
|
||||
}
|
||||
|
||||
protected final <E> CollectionValidator<Map<K, V>, E> ruleForCollection(K key) {
|
||||
@SuppressWarnings("unchecked")
|
||||
protected final <R> ObjectValidator<Map<String, Object>, R> ruleFor(String key) {
|
||||
ObjectValidator<Map<String, Object>, R> validValueHolder = new ObjectValidator<>(map -> (R) map.get(key));
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
}
|
||||
|
||||
protected final IntValidator<Map<String, Object>> ruleForInt(String key) {
|
||||
IntValidator<Map<String, Object>> validValueHolder = new IntValidator<>(map -> map.get(key));
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
}
|
||||
|
||||
protected final DoubleValidator<Map<String, Object>> ruleForDouble(String key) {
|
||||
DoubleValidator<Map<String, Object>> validValueHolder = new DoubleValidator<>(map -> map.get(key));
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
}
|
||||
|
||||
protected final BoolValidator<Map<String, Object>> ruleForBool(String key) {
|
||||
BoolValidator<Map<String, Object>> validValueHolder = new BoolValidator<>(map -> map.get(key));
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
}
|
||||
|
||||
protected final StringValidator<Map<String, Object>> ruleForString(String key) {
|
||||
StringValidator<Map<String, Object>> validValueHolder = new StringValidator<>(map -> map.get(key));
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
protected final <E> CollectionValidator<Map<String, Object>, E> ruleForCollection(String key) {
|
||||
CollectionValidator<Map<String, Object>, E> validValueHolder = new CollectionValidator<>(
|
||||
m -> (Collection<E>) m.get(key));
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
}
|
||||
|
||||
public Map<String, Object> validate(Map<String, Object> obj) {
|
||||
return this.validate(obj, this.propertyNames);
|
||||
}
|
||||
|
||||
public Map<String, Object> validate(Map<String, Object> obj, String... keys) {
|
||||
for (Consumer<Map<String, Object>> rule : this.rules) {
|
||||
rule.accept(obj);
|
||||
}
|
||||
for (PropertyValidator<Map<String, Object>, ?, ?> valueValidator : this.propertyValidators) {
|
||||
valueValidator.validate(obj);
|
||||
}
|
||||
final Map<String, Object> result = new HashMap<>(keys.length);
|
||||
for (String key : keys) {
|
||||
result.put(key, obj.get(key));
|
||||
}
|
||||
return result;
|
||||
Function<Map<K, V>, Collection<E>> getter = m -> (Collection<E>) m.get(key);
|
||||
return ruleForCollection(getter);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,15 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
import java.util.function.Function;
|
||||
|
||||
public class ObjectValidator<DTO, T> extends BasePropertyValidator<DTO, T, ObjectValidator<DTO, T>> {
|
||||
|
||||
ObjectValidator(Function<DTO, T> getter) {
|
||||
super(getter);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected ObjectValidator<DTO, T> thisObject() {
|
||||
return this;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,244 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
import xyz.zhouxy.plusone.commons.constant.PatternConsts;
|
||||
import xyz.zhouxy.plusone.commons.util.RegexTools;
|
||||
|
||||
public class StringValidator<DTO> extends BasePropertyValidator<DTO, String, StringValidator<DTO>> {
|
||||
|
||||
StringValidator(Function<DTO, String> getter) {
|
||||
super(getter);
|
||||
}
|
||||
|
||||
// ====================
|
||||
// ====== String ======
|
||||
// ====================
|
||||
|
||||
// ===== matches =====
|
||||
|
||||
public StringValidator<DTO> matches(Pattern regex, String errMsg) {
|
||||
return matches(regex, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matches(
|
||||
Pattern regex,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return matches(regex, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matches(
|
||||
Pattern regex,
|
||||
Function<String, E> exceptionCreator) {
|
||||
withRule(input -> RegexTools.matches(input, regex), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ===== matchesOne =====
|
||||
|
||||
public StringValidator<DTO> matchesOne(Pattern[] regexs, String errMsg) {
|
||||
return matchesOne(regexs, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matchesOne(
|
||||
Pattern[] regexs,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return matchesOne(regexs, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matchesOne(
|
||||
Pattern[] regexs,
|
||||
Function<String, E> exceptionCreator) {
|
||||
withRule(input -> RegexTools.matchesOne(input, regexs), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
public StringValidator<DTO> matchesOne(List<Pattern> regexs, String errMsg) {
|
||||
return matchesOne(regexs, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matchesOne(
|
||||
List<Pattern> regexs,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return matchesOne(regexs, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matchesOne(
|
||||
List<Pattern> regexs,
|
||||
Function<String, E> exceptionCreator) {
|
||||
withRule(input -> RegexTools.matchesOne(input, regexs.toArray(new Pattern[regexs.size()])), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ===== matchesAll =====
|
||||
|
||||
public StringValidator<DTO> matchesAll(Pattern[] regexs, String errMsg) {
|
||||
return matchesAll(regexs, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matchesAll(
|
||||
Pattern[] regexs,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return matchesAll(regexs, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matchesAll(
|
||||
Pattern[] regexs,
|
||||
Function<String, E> exceptionCreator) {
|
||||
withRule(input -> RegexTools.matchesAll(input, regexs), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
public StringValidator<DTO> matchesAll(Collection<Pattern> regexs, String errMsg) {
|
||||
return matchesAll(regexs, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matchesAll(
|
||||
Collection<Pattern> regexs,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return matchesAll(regexs, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> matchesAll(
|
||||
Collection<Pattern> regexs,
|
||||
Function<String, E> exceptionCreator) {
|
||||
withRule(input -> RegexTools.matchesAll(input, regexs.toArray(new Pattern[regexs.size()])), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ===== notBlank =====
|
||||
|
||||
static boolean isNotBlank(final String cs) {
|
||||
if (cs == null || cs.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < cs.length(); i++) {
|
||||
if (!Character.isWhitespace(cs.charAt(i))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public StringValidator<DTO> notBlank() {
|
||||
return notBlank("This String argument must have text; it must not be null, empty, or blank");
|
||||
}
|
||||
|
||||
public StringValidator<DTO> notBlank(String errMsg) {
|
||||
return notBlank(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> notBlank(Supplier<E> exceptionCreator) {
|
||||
return notBlank(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> notBlank(
|
||||
Function<String, E> exceptionCreator) {
|
||||
withRule(StringValidator::isNotBlank, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ===== email =====
|
||||
|
||||
public StringValidator<DTO> email() {
|
||||
return email("The value is not an email address.");
|
||||
}
|
||||
|
||||
public StringValidator<DTO> email(String errMsg) {
|
||||
return email(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> email(Supplier<E> exceptionCreator) {
|
||||
return email(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> email(Function<String, E> exceptionCreator) {
|
||||
return matches(PatternConsts.EMAIL, exceptionCreator);
|
||||
}
|
||||
|
||||
// ====== notEmpty =====
|
||||
|
||||
public StringValidator<DTO> notEmpty(String errMsg) {
|
||||
return notEmpty(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> notEmpty(Supplier<E> exceptionCreator) {
|
||||
return notEmpty(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> notEmpty(
|
||||
Function<String, E> exceptionCreator) {
|
||||
withRule(s -> s != null && !s.isEmpty(), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ====== isNullOrEmpty =====
|
||||
|
||||
public StringValidator<DTO> isNullOrEmpty(String errMsg) {
|
||||
return isNullOrEmpty(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> isNullOrEmpty(Supplier<E> exceptionCreator) {
|
||||
return isNullOrEmpty(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> isNullOrEmpty(
|
||||
Function<String, E> exceptionCreator) {
|
||||
withRule(s -> s == null || s.isEmpty(), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ====== length =====
|
||||
|
||||
public StringValidator<DTO> length(int length, String errMsg) {
|
||||
return length(length, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> length(int length,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return length(length, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> length(int length,
|
||||
Function<String, E> exceptionCreator) {
|
||||
Preconditions.checkArgument(length >= 0, "The minimum value must be less than the maximum value.");
|
||||
withRule(s -> s != null && s.length() == length, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
static boolean length(String str, int min, int max) {
|
||||
if (str == null) {
|
||||
return false;
|
||||
}
|
||||
final int len = str.length();
|
||||
return len >= min && len < max;
|
||||
}
|
||||
|
||||
public StringValidator<DTO> length(int min, int max, String errMsg) {
|
||||
return length(min, max, convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> length(int min, int max,
|
||||
Supplier<E> exceptionCreator) {
|
||||
return length(min, max, convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> length(int min, int max,
|
||||
Function<String, E> exceptionCreator) {
|
||||
Preconditions.checkArgument(min >= 0, "The minimum value must be greater than equal to 0.");
|
||||
Preconditions.checkArgument(min < max, "The minimum value must be less than the maximum value.");
|
||||
withRule(s -> length(s, min, max), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected StringValidator<DTO> thisObject() {
|
||||
return this;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
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 void validate(Object obj) {
|
||||
if (obj instanceof IValidateRequired) {
|
||||
((IValidateRequired) obj).validate();
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> void validate(T obj, BaseValidator<T> validator) {
|
||||
validator.validate(obj);
|
||||
}
|
||||
}
|
|
@ -32,7 +32,7 @@ import java.util.function.Supplier;
|
|||
* </pre>
|
||||
* </p>
|
||||
*
|
||||
* @author ZhouXY
|
||||
* @author <a href="https://gitee.com/zhouxy108">ZhouXY</a>
|
||||
* @see IValidateRequired
|
||||
* @see ValidateUtil
|
||||
* @see BaseValidator
|
||||
|
|
|
@ -1,37 +0,0 @@
|
|||
package xyz.zhouxy.plusone.constant;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public enum Patterns {
|
||||
DATE("^\\d{4}-\\d{2}-\\d{2}"),
|
||||
|
||||
PASSWORD("^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])[\\w\\\\!#$%&'*\\+\\-/=?^`{|}~@\\(\\)\\[\\]\",\\.;':><]{8,32}$"),
|
||||
|
||||
CAPTCHA("^[0-9A-Za-z]{4,6}$"),
|
||||
|
||||
EMAIL("^\\w+([-+.]\\w+)*@[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})*(\\.(?![0-9]+$)[a-zA-Z0-9][-0-9A-Za-z]{0,62})$"),
|
||||
|
||||
MOBILE_PHONE("^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\\d{8}$"),
|
||||
|
||||
USERNAME("^[\\da-zA-Z_.@\\\\]{4,36}$"),
|
||||
|
||||
NICKNAME("^[\\da-zA-Z_.@\\\\]{4,36}$"),
|
||||
|
||||
;
|
||||
|
||||
private final String regex;
|
||||
private final Pattern pattern;
|
||||
|
||||
Patterns(String regex) {
|
||||
this.regex = regex;
|
||||
this.pattern = Pattern.compile(regex);
|
||||
}
|
||||
|
||||
public String getRegex() {
|
||||
return regex;
|
||||
}
|
||||
|
||||
public Pattern getPattern() {
|
||||
return pattern;
|
||||
}
|
||||
}
|
|
@ -1,71 +0,0 @@
|
|||
package xyz.zhouxy.plusone.map;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import xyz.zhouxy.plusone.commons.util.Predicates;
|
||||
import xyz.zhouxy.plusone.constant.Patterns;
|
||||
import xyz.zhouxy.plusone.validator.MapValidator;
|
||||
|
||||
class MapValidatorTests {
|
||||
|
||||
@Test
|
||||
void testMapValidator() {
|
||||
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", 25);
|
||||
params.put("boolean", true);
|
||||
params.put("roleList", Arrays.asList("admin", ""));
|
||||
|
||||
Map<String, Object> validedParams = TestValidator.INSTANCE
|
||||
.validate(params);
|
||||
System.out.println(validedParams);
|
||||
}
|
||||
}
|
||||
|
||||
class TestValidator extends MapValidator {
|
||||
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";
|
||||
|
||||
TestValidator() {
|
||||
super(Arrays.asList(USERNAME, ACCOUNT, PASSWORD, AGE, BOOLEAN, ROLE_LIST));
|
||||
this.ruleForString(USERNAME)
|
||||
.isTrue(Predicates.of(StringUtils::isNotEmpty)
|
||||
.and(Objects::nonNull))
|
||||
.matches(Patterns.USERNAME.getPattern(),
|
||||
username -> new IllegalArgumentException(String.format("用户名【%s】不符合规范", username)));
|
||||
this.ruleForString(ACCOUNT)
|
||||
.notEmpty()
|
||||
.matchesOne(new Pattern[] { Patterns.EMAIL.getPattern(), Patterns.MOBILE_PHONE.getPattern() }, "请输入正确的邮箱地址或手机号");
|
||||
this.ruleForString(PASSWORD)
|
||||
.notEmpty("密码不能为空")
|
||||
.matches(Patterns.PASSWORD.getPattern(), "密码不符合规范");
|
||||
this.withRule(m -> Objects.equals(m.get(PASSWORD), m.get(PASSWORD2)),
|
||||
"两次输入的密码不一样!");
|
||||
this.ruleForInt(AGE)
|
||||
.notNull()
|
||||
.isTrue(age -> (18 <= age && 60 >= age));
|
||||
this.ruleForBool(BOOLEAN)
|
||||
.notNull("admin could not be null.")
|
||||
.isTrue("admin must be true.");
|
||||
this.<String>ruleForCollection(ROLE_LIST)
|
||||
.notNull(() -> new NullPointerException(ROLE_LIST))
|
||||
.notEmpty("角色列表不能为空!");
|
||||
}
|
||||
|
||||
static final TestValidator INSTANCE = new TestValidator();
|
||||
}
|
|
@ -1,148 +0,0 @@
|
|||
package xyz.zhouxy.plusone.pojo;
|
||||
|
||||
import static xyz.zhouxy.plusone.constant.Patterns.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
import xyz.zhouxy.plusone.commons.util.Predicates;
|
||||
import xyz.zhouxy.plusone.commons.util.RegexUtil;
|
||||
import xyz.zhouxy.plusone.validator.Validator;
|
||||
|
||||
class ValidatorTests {
|
||||
@Test
|
||||
void testValidate() {
|
||||
RegisterCommand registerCommand = new RegisterCommand(
|
||||
"null", "luquanlion@outlook.com", "22336",
|
||||
"A1b2C3d4", "A1b2C3d4",
|
||||
Arrays.asList(new String[] { "admin", "editor" }));
|
||||
|
||||
Validator<RegisterCommand> registerCommandValidator = new Validator<RegisterCommand>()
|
||||
// 传入 predicate 和 Function<T, E extends RuntimeException>
|
||||
.addRule(command -> {
|
||||
String username = command.getUsername();
|
||||
return Objects.nonNull(username)
|
||||
&& StringUtils.isNotEmpty(username)
|
||||
&& StringUtils.isNotBlank(username)
|
||||
&& RegexUtil.matches(username, USERNAME.getPattern());
|
||||
}, command -> new IllegalArgumentException(String.format("用户名【%s】不符合规范", command.getUsername())))
|
||||
// 传入 predicate 和 error message
|
||||
.addRule(command -> Predicates
|
||||
.<String>of(Objects::nonNull)
|
||||
.and(account -> RegexUtil.matchesOne(account, new Pattern[] { EMAIL.getPattern(), MOBILE_PHONE.getPattern() }))
|
||||
.test(command.getAccount()),
|
||||
"请输入邮箱地址或手机号")
|
||||
// 传入 rule
|
||||
.addRule(command -> {
|
||||
String code = command.getCode();
|
||||
Preconditions.checkArgument(Objects.nonNull(code), "验证码不能为空");
|
||||
Preconditions.checkArgument(RegexUtil.matches(code, CAPTCHA.getPattern()), "验证码不符合规范");
|
||||
})
|
||||
// 传入 rule
|
||||
.addRule(command -> {
|
||||
String password = command.getPassword();
|
||||
Preconditions.checkArgument(StringUtils.isNotEmpty(password), "密码不能为空");
|
||||
Preconditions.checkArgument(RegexUtil.matches(password, PASSWORD.getPattern()), "密码不符合规范");
|
||||
})
|
||||
// 传入 predicate 和 Supplier<E extends RuntimeException>
|
||||
.addRule(command -> {
|
||||
List<String> roles = command.getRoles();
|
||||
return roles != null && !roles.isEmpty();
|
||||
}, () -> new RuntimeException("角色列表不能为空"))
|
||||
// 传入 predicate 和 error message
|
||||
.addRule(command -> Objects.equals(command.getPassword(), command.getPassword2()),
|
||||
"两次输入的密码不一致");
|
||||
registerCommandValidator.validate(registerCommand);
|
||||
System.out.println(registerCommand);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* RegisterCommand
|
||||
*/
|
||||
class RegisterCommand {
|
||||
|
||||
private String username;
|
||||
private String account;
|
||||
private String code;
|
||||
private String password;
|
||||
private String password2;
|
||||
private List<String> roles;
|
||||
|
||||
public RegisterCommand() {
|
||||
}
|
||||
|
||||
public RegisterCommand(String username, String account, String code, String password, String password2,
|
||||
List<String> roles) {
|
||||
this.username = username;
|
||||
this.account = account;
|
||||
this.code = code;
|
||||
this.password = password;
|
||||
this.password2 = password2;
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getAccount() {
|
||||
return account;
|
||||
}
|
||||
|
||||
public void setAccount(String account) {
|
||||
this.account = account;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getPassword2() {
|
||||
return password2;
|
||||
}
|
||||
|
||||
public void setPassword2(String password2) {
|
||||
this.password2 = password2;
|
||||
}
|
||||
|
||||
public List<String> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
public void setRoles(List<String> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("RegisterCommand [username=").append(username).append(", account=").append(account)
|
||||
.append(", code=").append(code).append(", password=").append(password).append(", password2=")
|
||||
.append(password2).append(", roles=").append(roles).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,81 @@
|
|||
package xyz.zhouxy.plusone.validator.map.test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import xyz.zhouxy.plusone.commons.constant.PatternConsts;
|
||||
import xyz.zhouxy.plusone.validator.MapValidator;
|
||||
|
||||
public //
|
||||
class MapValidatorTests {
|
||||
|
||||
private static final MapValidator<String, Object> validator = ParamsValidator.INSTANCE;
|
||||
|
||||
@Test
|
||||
void testValidateAndCopy() {
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put(ParamsValidator.USERNAME, "ZhouXY");
|
||||
params.put(ParamsValidator.ACCOUNT, "zhouxy@code108.cn");
|
||||
params.put(ParamsValidator.PASSWORD, "99Code108");
|
||||
params.put(ParamsValidator.PASSWORD2, "99Code108");
|
||||
params.put(ParamsValidator.AGE, 18);
|
||||
params.put(ParamsValidator.BOOLEAN, true);
|
||||
params.put(ParamsValidator.ROLE_LIST, Arrays.asList("admin", ""));
|
||||
|
||||
Map<String, Object> validedParams = validator.validateAndCopy(params);
|
||||
System.out.println(validedParams);
|
||||
}
|
||||
}
|
||||
|
||||
class ParamsValidator extends MapValidator<String, Object> {
|
||||
public static final String USERNAME = "username";
|
||||
public static final String ACCOUNT = "account";
|
||||
public static final String PASSWORD = "password";
|
||||
public static final String PASSWORD2 = "password2";
|
||||
public static final String AGE = "age";
|
||||
public static final String BOOLEAN = "boolean";
|
||||
public static final String ROLE_LIST = "roleList";
|
||||
|
||||
public static final ParamsValidator INSTANCE = new ParamsValidator();
|
||||
|
||||
private ParamsValidator() {
|
||||
super(new String[] { USERNAME, ACCOUNT, PASSWORD, AGE, BOOLEAN, ROLE_LIST });
|
||||
ruleForString(USERNAME)
|
||||
.notBlank("用户名不能为空")
|
||||
.matches(PatternConsts.USERNAME,
|
||||
username -> new IllegalArgumentException(String.format("用户名【%s】不符合规范", username)));
|
||||
|
||||
ruleForString(ACCOUNT)
|
||||
.notBlank("账号不能为空")
|
||||
.matchesOne(new Pattern[] { PatternConsts.EMAIL, PatternConsts.MOBILE_PHONE }, "请输入正确的邮箱地址或手机号");
|
||||
|
||||
ruleForString(PASSWORD)
|
||||
.notEmpty("密码不能为空")
|
||||
.matches(PatternConsts.PASSWORD, "密码不符合规范");
|
||||
|
||||
// 校验到多个属性,只能针对 map 本身进行校验
|
||||
withRule(m -> Objects.equals(m.get(PASSWORD), m.get(PASSWORD2)),
|
||||
"两次输入的密码不一样!");
|
||||
|
||||
ruleForInt(AGE)
|
||||
.withRule(Objects::nonNull)
|
||||
.between(18, 61);
|
||||
|
||||
ruleForBool(BOOLEAN)
|
||||
.notNull("Boolean property could not be null.")
|
||||
.isTrue("Boolean property must be true.");
|
||||
|
||||
this.<String>ruleForCollection(ROLE_LIST)
|
||||
.notEmpty("角色列表不能为空!")
|
||||
.withRule(l -> l.stream().allMatch(StringUtils::isNotBlank),
|
||||
() -> new IllegalArgumentException("角色标识不能为空!"));
|
||||
}
|
||||
}
|
|
@ -0,0 +1,143 @@
|
|||
package xyz.zhouxy.plusone.validator.test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import xyz.zhouxy.plusone.commons.constant.PatternConsts;
|
||||
import xyz.zhouxy.plusone.commons.function.PredicateTools;
|
||||
import xyz.zhouxy.plusone.commons.util.RegexTools;
|
||||
import xyz.zhouxy.plusone.validator.BaseValidator;
|
||||
import xyz.zhouxy.plusone.validator.ValidateUtil;
|
||||
|
||||
class BaseValidatorTest {
|
||||
@Test
|
||||
void testValidate() {
|
||||
RegisterCommand registerCommand = new RegisterCommand("zhouxy108", "luquanlion@outlook.com", "22336",
|
||||
"A1b2C3d4",
|
||||
"A1b2C3d4",
|
||||
Arrays.asList(new String[] { "admin", "editor" }));
|
||||
RegisterCommandValidator.INSTANCE.validate(registerCommand);
|
||||
ValidateUtil.validate(registerCommand, RegisterCommandValidator.INSTANCE);
|
||||
System.out.println(registerCommand);
|
||||
}
|
||||
|
||||
static class RegisterCommandValidator extends BaseValidator<RegisterCommand> {
|
||||
|
||||
static final RegisterCommandValidator INSTANCE = new RegisterCommandValidator();
|
||||
|
||||
private RegisterCommandValidator() {
|
||||
ruleForString(RegisterCommand::getUsername)
|
||||
.isTrue(PredicateTools.<String>from(Objects::nonNull)
|
||||
.and(StringUtils::isNotEmpty)
|
||||
.and(StringUtils::isNotBlank)
|
||||
.and(username -> RegexTools.matches(username, PatternConsts.USERNAME)),
|
||||
username -> new IllegalArgumentException(String.format("用户名【%s】不符合规范", username)));
|
||||
ruleForString(RegisterCommand::getAccount)
|
||||
.notNull("请输入邮箱地址或手机号")
|
||||
.matchesOne(Arrays.asList(PatternConsts.EMAIL, PatternConsts.MOBILE_PHONE), "请输入邮箱地址或手机号");
|
||||
ruleForString(RegisterCommand::getCode)
|
||||
.notNull("验证码不能为空")
|
||||
.matches(PatternConsts.CAPTCHA, "验证码不符合规范");
|
||||
ruleForString(RegisterCommand::getPassword)
|
||||
.notEmpty("密码不能为空")
|
||||
.matches(PatternConsts.PASSWORD, "密码不符合规范");
|
||||
ruleForCollection(RegisterCommand::getRoles)
|
||||
.notEmpty(() -> new RuntimeException("角色列表不能为空"));
|
||||
|
||||
withRule(registerCommand -> Objects.equals(registerCommand.getPassword(), registerCommand.getPassword2()),
|
||||
"两次输入的密码不一致");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* RegisterCommand
|
||||
*/
|
||||
static class RegisterCommand {
|
||||
|
||||
private String username;
|
||||
private String account;
|
||||
private String code;
|
||||
private String password;
|
||||
private String password2;
|
||||
private List<String> roles;
|
||||
|
||||
public RegisterCommand() {
|
||||
}
|
||||
|
||||
public RegisterCommand(String username, String account, String code, String password, String password2,
|
||||
List<String> roles) {
|
||||
this.username = username;
|
||||
this.account = account;
|
||||
this.code = code;
|
||||
this.password = password;
|
||||
this.password2 = password2;
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getAccount() {
|
||||
return account;
|
||||
}
|
||||
|
||||
public void setAccount(String account) {
|
||||
this.account = account;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getPassword2() {
|
||||
return password2;
|
||||
}
|
||||
|
||||
public void setPassword2(String password2) {
|
||||
this.password2 = password2;
|
||||
}
|
||||
|
||||
public List<String> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
public void setRoles(List<String> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new StringBuilder()
|
||||
.append("RegisterCommand [")
|
||||
.append("username=").append(username)
|
||||
.append(", account=").append(account)
|
||||
.append(", code=").append(code)
|
||||
.append(", password=").append(password)
|
||||
.append(", password2=").append(password2)
|
||||
.append(", roles=").append(roles)
|
||||
.append("]")
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,147 @@
|
|||
package xyz.zhouxy.plusone.validator.test;
|
||||
|
||||
import static xyz.zhouxy.plusone.commons.constant.PatternConsts.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
import xyz.zhouxy.plusone.commons.collection.CollectionTools;
|
||||
import xyz.zhouxy.plusone.commons.function.PredicateTools;
|
||||
import xyz.zhouxy.plusone.commons.util.RegexTools;
|
||||
import xyz.zhouxy.plusone.validator.Validator;
|
||||
|
||||
class ValidatorTests {
|
||||
@Test
|
||||
void testValidate() {
|
||||
RegisterCommand registerCommand = new RegisterCommand(
|
||||
"null", "luquanlion@outlook.com", "22336",
|
||||
"A1b2C3d4", "A1b2C3d4",
|
||||
Arrays.asList(new String[] { "admin", "editor" }));
|
||||
|
||||
Validator<RegisterCommand> registerCommandValidator = new Validator<RegisterCommand>()
|
||||
// 传入 predicate 和 Function<T, E extends RuntimeException>
|
||||
.addRule(command -> {
|
||||
String username = command.getUsername();
|
||||
return Objects.nonNull(username)
|
||||
&& StringUtils.isNotEmpty(username)
|
||||
&& StringUtils.isNotBlank(username)
|
||||
&& RegexTools.matches(username, USERNAME);
|
||||
}, command -> new IllegalArgumentException(String.format("用户名【%s】不符合规范", command.getUsername())))
|
||||
// 传入 predicate 和 error message
|
||||
.addRule(command -> PredicateTools
|
||||
.<String>from(Objects::nonNull)
|
||||
.and(account -> RegexTools.matchesOne(account, new Pattern[] { EMAIL, MOBILE_PHONE }))
|
||||
.test(command.getAccount()),
|
||||
"请输入邮箱地址或手机号")
|
||||
// 传入 rule
|
||||
.addRule(command -> {
|
||||
String code = command.getCode();
|
||||
Preconditions.checkArgument(Objects.nonNull(code), "验证码不能为空");
|
||||
Preconditions.checkArgument(RegexTools.matches(code, CAPTCHA), "验证码不符合规范");
|
||||
})
|
||||
// 传入 rule
|
||||
.addRule(command -> {
|
||||
String password = command.getPassword();
|
||||
Preconditions.checkArgument(StringUtils.isNotEmpty(password), "密码不能为空");
|
||||
Preconditions.checkArgument(RegexTools.matches(password, PASSWORD), "密码不符合规范");
|
||||
})
|
||||
// 传入 predicate 和 Supplier<E extends RuntimeException>
|
||||
.addRule(command -> CollectionTools.isNotEmpty(command.getRoles()),
|
||||
() -> new RuntimeException("角色列表不能为空"))
|
||||
// 传入 predicate 和 error message
|
||||
.addRule(command -> Objects.equals(command.getPassword(), command.getPassword2()),
|
||||
"两次输入的密码不一致");
|
||||
registerCommandValidator.validate(registerCommand);
|
||||
System.out.println(registerCommand);
|
||||
}
|
||||
|
||||
/**
|
||||
* RegisterCommand
|
||||
*/
|
||||
static class RegisterCommand {
|
||||
|
||||
private String username;
|
||||
private String account;
|
||||
private String code;
|
||||
private String password;
|
||||
private String password2;
|
||||
private List<String> roles;
|
||||
|
||||
public RegisterCommand() {
|
||||
}
|
||||
|
||||
public RegisterCommand(String username, String account, String code, String password, String password2,
|
||||
List<String> roles) {
|
||||
this.username = username;
|
||||
this.account = account;
|
||||
this.code = code;
|
||||
this.password = password;
|
||||
this.password2 = password2;
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getAccount() {
|
||||
return account;
|
||||
}
|
||||
|
||||
public void setAccount(String account) {
|
||||
this.account = account;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getPassword2() {
|
||||
return password2;
|
||||
}
|
||||
|
||||
public void setPassword2(String password2) {
|
||||
this.password2 = password2;
|
||||
}
|
||||
|
||||
public List<String> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
public void setRoles(List<String> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("RegisterCommand [username=").append(username).append(", account=").append(account)
|
||||
.append(", code=").append(code).append(", password=").append(password).append(", password2=")
|
||||
.append(password2).append(", roles=").append(roles).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue