Compare commits

..

10 Commits

24 changed files with 1106 additions and 1358 deletions

View File

@ -10,6 +10,3 @@ end_of_line = lf
charset = utf-8 charset = utf-8
trim_trailing_whitespace = false trim_trailing_whitespace = false
insert_final_newline = true insert_final_newline = true
[*.xml]
indent_size = 2

37
pom.xml
View File

@ -1,13 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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">
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> <modelVersion>4.0.0</modelVersion>
<groupId>xyz.zhouxy.plusone</groupId> <groupId>xyz.zhouxy.plusone</groupId>
<artifactId>plusone-validator-for-mfp</artifactId> <artifactId>plusone-validator</artifactId>
<version>0.1.3-SNAPSHOT</version> <version>0.1.5-SNAPSHOT</version>
<name>plusone-validator</name> <name>plusone-validator</name>
<url>http://zhouxy.xyz</url> <url>http://zhouxy.xyz</url>
@ -16,43 +15,38 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target> <maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.source>1.8</maven.compiler.source>
<commons-lang3.version>3.12.0</commons-lang3.version>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>xyz.zhouxy.plusone</groupId>
<artifactId>guava</artifactId> <artifactId>plusone-commons</artifactId>
<version>32.0.1-jre</version> <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>
<dependency> <dependency>
<groupId>org.junit.jupiter</groupId> <groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId> <artifactId>junit-jupiter-api</artifactId>
<version>5.9.2</version> <version>5.9.2</version>
<scope>test</scope> <scope>test</scope>
</dependency> </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> </dependencies>
<build> <build>
<!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<pluginManagement> <pluginManagement>
<plugins> <plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin> <plugin>
<artifactId>maven-clean-plugin</artifactId> <artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version> <version>3.1.0</version>
</plugin> </plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin> <plugin>
<artifactId>maven-resources-plugin</artifactId> <artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version> <version>3.0.2</version>
@ -77,6 +71,7 @@
<artifactId>maven-deploy-plugin</artifactId> <artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version> <version>2.8.2</version>
</plugin> </plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin> <plugin>
<artifactId>maven-site-plugin</artifactId> <artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version> <version>3.7.1</version>

View File

@ -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: Dubboissues#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");
}
}

View File

@ -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&lt;String&gt;}
* 使 {@link Predicate#and(Predicate)}{@link Predicate#or(Predicate)}
* {@code Predicate<? super T>}
*
* <pre>
* Predicate&lt;String&gt; predicate = Predicates.&lt;String&gt;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");
}
}

View File

@ -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");
}
}

View File

@ -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();
}
}

View File

@ -3,32 +3,24 @@ package xyz.zhouxy.plusone.validator;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.function.Supplier; 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> { public class BaseValidator<T> {
private final List<Consumer<T>> rules = new ArrayList<>(); private final List<Consumer<? super T>> rules = new ArrayList<>();
private final List<PropertyValidator<T, ?, ?>> propertyValidators = new ArrayList<>();
protected void withRule(final Predicate<T> rule, final String errorMessage) { 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()); withRule(rule, value -> exceptionBuilder.get());
} }
protected <E extends RuntimeException> void withRule(Predicate<T> condition, protected <E extends RuntimeException> void withRule(
Function<T, E> exceptionBuilder) { Predicate<? super T> condition, Function<T, E> exceptionBuilder) {
withRule(value -> { withRule(value -> {
if (!condition.test(value)) { if (!condition.test(value)) {
throw exceptionBuilder.apply(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); this.rules.add(rule);
} }
protected final <R> ObjectValidator<T, R> ruleFor(Function<T, R> getter) { protected final <R> ObjectValidator<T, R> ruleFor(Function<T, R> getter) {
ObjectValidator<T, R> validValueHolder = new ObjectValidator<>(getter); ObjectValidator<T, R> validator = new ObjectValidator<>(getter);
propertyValidators.add(validValueHolder); this.rules.add(validator::validate);
return validValueHolder; return validator;
} }
protected final IntValidator<T> ruleForInt(Function<T, ?> getter) { protected final IntValidator<T> ruleForInt(Function<T, Integer> getter) {
IntValidator<T> validValueHolder = new IntValidator<>(getter); IntValidator<T> validator = new IntValidator<>(getter);
propertyValidators.add(validValueHolder); this.rules.add(validator::validate);
return validValueHolder; return validator;
} }
protected final DoubleValidator<T> ruleForDouble(Function<T, ?> getter) { protected final DoubleValidator<T> ruleForDouble(Function<T, Double> getter) {
DoubleValidator<T> validValueHolder = new DoubleValidator<>(getter); DoubleValidator<T> validator = new DoubleValidator<>(getter);
propertyValidators.add(validValueHolder); this.rules.add(validator::validate);
return validValueHolder; return validator;
} }
protected final BoolValidator<T> ruleForBool(Function<T, ?> getter) { protected final BoolValidator<T> ruleForBool(Function<T, Boolean> getter) {
BoolValidator<T> validValueHolder = new BoolValidator<>(getter); BoolValidator<T> validator = new BoolValidator<>(getter);
propertyValidators.add(validValueHolder); this.rules.add(validator::validate);
return validValueHolder; return validator;
} }
protected final StringValidator<T> ruleForString(Function<T, ?> getter) { protected final StringValidator<T> ruleForString(Function<T, String> getter) {
StringValidator<T> validValueHolder = new StringValidator<>(getter); StringValidator<T> validator = new StringValidator<>(getter);
propertyValidators.add(validValueHolder); this.rules.add(validator::validate);
return validValueHolder; return validator;
} }
protected final <E> CollectionValidator<T, E> ruleForCollection(Function<T, Collection<E>> getter) { protected final <E> CollectionValidator<T, E> ruleForCollection(Function<T, Collection<E>> getter) {
CollectionValidator<T, E> validValueHolder = new CollectionValidator<>(getter); CollectionValidator<T, E> validator = new CollectionValidator<>(getter);
propertyValidators.add(validValueHolder); this.rules.add(validator::validate);
return validValueHolder; return validator;
} }
public void validate(T obj) { public void validate(T obj) {
for (Consumer<T> rule : this.rules) { this.rules.forEach(rule -> rule.accept(obj));
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;
}
}
} }

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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();
}

View File

@ -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;
}
}

View File

@ -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);
}
}

View File

@ -1,103 +1,71 @@
package xyz.zhouxy.plusone.validator; package xyz.zhouxy.plusone.validator;
import java.util.ArrayList; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.function.Consumer; import java.util.Set;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Predicate; import java.util.stream.Collectors;
import java.util.function.Supplier;
import xyz.zhouxy.plusone.validator.BaseValidator.*; public abstract class MapValidator<K, V> extends BaseValidator<Map<K, V>> {
public abstract class MapValidator { private final Set<K> keys;
private final List<Consumer<Map<String, Object>>> rules = new ArrayList<>();
private final List<PropertyValidator<Map<String, Object>, ?, ?>> propertyValidators = new ArrayList<>();
private final String[] propertyNames; protected MapValidator(K[] keys) {
this(Arrays.asList(keys));
protected MapValidator(List<String> propertyNames) {
this.propertyNames = propertyNames.toArray(new String[0]);
} }
protected void withRule(final Predicate<Map<String, Object>> rule, final String errorMessage) { protected MapValidator(Collection<K> keys) {
withRule(rule, () -> new InvalidInputException(errorMessage)); this.keys = keys.stream().collect(Collectors.toSet());
} }
protected <E extends RuntimeException> void withRule(Predicate<Map<String, Object>> rule, // ========== validate & validateAndCopy ==========
Supplier<E> exceptionBuilder) {
withRule(rule, value -> exceptionBuilder.get()); 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, public final Map<K, V> validateAndCopy(Map<K, V> obj, Collection<K> keys) {
Function<Map<String, Object>, E> exceptionBuilder) { return validateAndCopyInternal(obj, keys);
withRule(value -> {
if (!condition.test(value)) {
throw exceptionBuilder.apply(value);
}
});
} }
protected void withRule(Consumer<Map<String, Object>> rule) { @SafeVarargs
this.rules.add(rule); public final Map<K, V> validateAndCopy(Map<K, V> obj, K... keys) {
return validateAndCopyInternal(obj, Arrays.asList(keys));
} }
@SuppressWarnings("unchecked") private final Map<K, V> validateAndCopyInternal(Map<K, V> obj, Collection<K> keys) {
protected final <R> ObjectValidator<Map<String, Object>, R> ruleFor(String key) { validate(obj);
ObjectValidator<Map<String, Object>, R> validValueHolder = new ObjectValidator<>(map -> (R) map.get(key)); return obj.entrySet().stream()
propertyValidators.add(validValueHolder); .filter(kv -> keys.contains(kv.getKey()))
return validValueHolder; .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
} }
protected final IntValidator<Map<String, Object>> ruleForInt(String key) { // ========== ruleFor ==========
IntValidator<Map<String, Object>> validValueHolder = new IntValidator<>(map -> map.get(key));
propertyValidators.add(validValueHolder); protected final ObjectValidator<Map<K, V>, V> ruleFor(K key) {
return validValueHolder; return ruleFor(m -> m.get(key));
} }
protected final DoubleValidator<Map<String, Object>> ruleForDouble(String key) { protected final IntValidator<Map<K, V>> ruleForInt(K key) {
DoubleValidator<Map<String, Object>> validValueHolder = new DoubleValidator<>(map -> map.get(key)); return ruleForInt(m -> (Integer) m.get(key));
propertyValidators.add(validValueHolder);
return validValueHolder;
} }
protected final BoolValidator<Map<String, Object>> ruleForBool(String key) { protected final DoubleValidator<Map<K, V>> ruleForDouble(K key) {
BoolValidator<Map<String, Object>> validValueHolder = new BoolValidator<>(map -> map.get(key)); return ruleForDouble(m -> (Double) m.get(key));
propertyValidators.add(validValueHolder);
return validValueHolder;
} }
protected final StringValidator<Map<String, Object>> ruleForString(String key) { protected final BoolValidator<Map<K, V>> ruleForBool(K key) {
StringValidator<Map<String, Object>> validValueHolder = new StringValidator<>(map -> map.get(key)); return ruleForBool(m -> (Boolean) m.get(key));
propertyValidators.add(validValueHolder);
return validValueHolder;
} }
@SuppressWarnings("unchecked") protected final StringValidator<Map<K, V>> ruleForString(K key) {
protected final <E> CollectionValidator<Map<String, Object>, E> ruleForCollection(String key) { return ruleForString(m -> (String) m.get(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) { protected final <E> CollectionValidator<Map<K, V>, E> ruleForCollection(K key) {
return this.validate(obj, this.propertyNames); @SuppressWarnings("unchecked")
} Function<Map<K, V>, Collection<E>> getter = m -> (Collection<E>) m.get(key);
return ruleForCollection(getter);
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;
} }
} }

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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);
}
}

View File

@ -32,7 +32,7 @@ import java.util.function.Supplier;
* </pre> * </pre>
* </p> * </p>
* *
* @author ZhouXY * @author <a href="https://gitee.com/zhouxy108">ZhouXY</a>
* @see IValidateRequired * @see IValidateRequired
* @see ValidateUtil * @see ValidateUtil
* @see BaseValidator * @see BaseValidator

View File

@ -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;
}
}

View File

@ -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();
}

View File

@ -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();
}
}

View File

@ -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("角色标识不能为空!"));
}
}

View File

@ -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();
}
}
}

View File

@ -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();
}
}
}