Compare commits

...

6 Commits

22 changed files with 1215 additions and 766 deletions

15
.editorconfig 100644
View File

@ -0,0 +1,15 @@
# EditorConfig is awesome: https://EditorConfig.org
# top-most EditorConfig file
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = false
insert_final_newline = true
[*.xml]
indent_size = 2

33
pom.xml
View File

@ -1,11 +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</artifactId>
<artifactId>plusone-validator-for-mfp</artifactId>
<version>0.1.3-SNAPSHOT</version>
<name>plusone-validator</name>
@ -20,33 +21,38 @@
<dependencies>
<dependency>
<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>${commons-lang3.version}</version>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>32.0.1-jre</version>
</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>
@ -71,7 +77,6 @@
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>

View File

@ -0,0 +1,43 @@
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

@ -0,0 +1,43 @@
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

@ -0,0 +1,378 @@
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

@ -3,17 +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<>();
protected void withRule(final Predicate<T> rule, final String errorMessage) {
withRule(rule, () -> InvalidInputException.of(errorMessage));
withRule(rule, () -> new InvalidInputException(errorMessage));
}
protected <E extends RuntimeException> void withRule(Predicate<T> rule, Supplier<E> exceptionBuilder) {
@ -39,25 +46,25 @@ public class BaseValidator<T> {
return validValueHolder;
}
protected final IntValidator<T> ruleForInt(Function<T, Integer> getter) {
protected final IntValidator<T> ruleForInt(Function<T, ?> getter) {
IntValidator<T> validValueHolder = new IntValidator<>(getter);
propertyValidators.add(validValueHolder);
return validValueHolder;
}
protected final DoubleValidator<T> ruleForDouble(Function<T, Double> getter) {
protected final DoubleValidator<T> ruleForDouble(Function<T, ?> getter) {
DoubleValidator<T> validValueHolder = new DoubleValidator<>(getter);
propertyValidators.add(validValueHolder);
return validValueHolder;
}
protected final BoolValidator<T> ruleForBool(Function<T, Boolean> getter) {
protected final BoolValidator<T> ruleForBool(Function<T, ?> getter) {
BoolValidator<T> validValueHolder = new BoolValidator<>(getter);
propertyValidators.add(validValueHolder);
return validValueHolder;
}
protected final StringValidator<T> ruleForString(Function<T, String> getter) {
protected final StringValidator<T> ruleForString(Function<T, ?> getter) {
StringValidator<T> validValueHolder = new StringValidator<>(getter);
propertyValidators.add(validValueHolder);
return validValueHolder;
@ -77,4 +84,473 @@ public class BaseValidator<T> {
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

@ -1,58 +0,0 @@
package xyz.zhouxy.plusone.validator;
import java.util.function.Function;
import java.util.function.Supplier;
import org.apache.commons.lang3.BooleanUtils;
public class BoolValidator<DTO> extends PropertyValidator<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(BooleanUtils::isTrue, 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(BooleanUtils::isFalse, exceptionCreator);
return this;
}
@Override
protected BoolValidator<DTO> thisObject() {
return this;
}
}

View File

@ -1,49 +0,0 @@
package xyz.zhouxy.plusone.validator;
import java.util.Collection;
import java.util.function.Function;
import java.util.function.Supplier;
public 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) {
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) {
withRule(value -> value == null || value.isEmpty(), exceptionCreator);
return this;
}
@Override
protected CollectionValidator<DTO, T> thisObject() {
return this;
}
}

View File

@ -1,35 +0,0 @@
package xyz.zhouxy.plusone.validator;
import java.util.function.Function;
import java.util.function.Supplier;
public class DoubleValidator<DTO> extends PropertyValidator<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

@ -1,13 +0,0 @@
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

@ -1,35 +0,0 @@
package xyz.zhouxy.plusone.validator;
import java.util.function.Function;
import java.util.function.Supplier;
public class IntValidator<DTO> extends PropertyValidator<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,39 +1,31 @@
package xyz.zhouxy.plusone.validator;
import xyz.zhouxy.plusone.commons.exception.BaseRuntimeException;
/**
* 4040000 -
*
*
* @author <a href="https://gitee.com/zhouxy108">ZhouXY</a>
* @author ZhouXY
*/
public class InvalidInputException extends BaseRuntimeException {
public class InvalidInputException extends RuntimeException {
private static final long serialVersionUID = 7956661913360059670L;
public static final String ERROR_CODE = "4040000";
protected InvalidInputException(String code, String msg) {
super(code, msg);
public InvalidInputException() {
super("用户请求参数错误");
}
protected InvalidInputException(String code, Throwable cause) {
super(code, cause);
public InvalidInputException(String msg) {
super(msg);
}
protected InvalidInputException(String code, String msg, Throwable cause) {
super(code, msg, cause);
public InvalidInputException(String msgFormat, Object... args) {
super(String.format(msgFormat, args));
}
public static InvalidInputException of(String msg) {
return new InvalidInputException(ERROR_CODE, msg);
public InvalidInputException(Throwable cause) {
super(cause);
}
public static InvalidInputException of(Throwable cause) {
return new InvalidInputException(ERROR_CODE, cause);
}
public static InvalidInputException of(String msg, Throwable cause) {
return new InvalidInputException(ERROR_CODE, msg, cause);
public InvalidInputException(String msg, Throwable cause) {
super(msg, cause);
}
}

View File

@ -0,0 +1,103 @@
package xyz.zhouxy.plusone.validator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import xyz.zhouxy.plusone.validator.BaseValidator.*;
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 String[] propertyNames;
protected MapValidator(List<String> propertyNames) {
this.propertyNames = propertyNames.toArray(new String[0]);
}
protected void withRule(final Predicate<Map<String, Object>> rule, final String errorMessage) {
withRule(rule, () -> new InvalidInputException(errorMessage));
}
protected <E extends RuntimeException> void withRule(Predicate<Map<String, Object>> rule,
Supplier<E> exceptionBuilder) {
withRule(rule, value -> exceptionBuilder.get());
}
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);
}
});
}
protected void withRule(Consumer<Map<String, Object>> rule) {
this.rules.add(rule);
}
@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;
}
}

View File

@ -1,15 +0,0 @@
package xyz.zhouxy.plusone.validator;
import java.util.function.Function;
public 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;
}
}

View File

@ -1,155 +0,0 @@
package xyz.zhouxy.plusone.validator;
import java.util.Collection;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
abstract class PropertyValidator<DTO, PROPERTY, THIS> {
Function<DTO, PROPERTY> getter;
Validator<PROPERTY> validator = new Validator<>();
PropertyValidator(Function<DTO, PROPERTY> getter) {
this.getter = getter;
}
<E extends RuntimeException> void withRule(Predicate<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 -> InvalidInputException.of(String.format("(%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<PROPERTY> condition) {
return isTrue(condition, "无效的用户输入");
}
public THIS isTrue(Predicate<PROPERTY> condition, String errMsg) {
return isTrue(condition, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> THIS isTrue(
Predicate<PROPERTY> condition,
Supplier<E> exceptionCreator) {
return isTrue(condition, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> THIS isTrue(
Predicate<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();
}
// ========================================================================
void validate(DTO obj) {
PROPERTY value = this.getter.apply(obj);
this.validator.validate(value);
}
static <V> Function<V, InvalidInputException> convertExceptionCreator(String errMsg) {
return value -> InvalidInputException.of(errMsg);
}
static <V, E extends RuntimeException> Function<V, E> convertExceptionCreator(
Supplier<E> exceptionSupplier) {
return value -> exceptionSupplier.get();
}
protected abstract THIS thisObject();
}

View File

@ -1,189 +0,0 @@
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 org.apache.commons.lang3.StringUtils;
import xyz.zhouxy.plusone.commons.constant.PatternConsts;
import xyz.zhouxy.plusone.commons.util.RegexUtil;
public class StringValidator<DTO> extends PropertyValidator<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 -> 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) {
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) {
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) {
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) {
withRule(input -> RegexUtil.matchesAll(input, regexs.toArray(new Pattern[regexs.size()])), exceptionCreator);
return this;
}
// ===== notBlank =====
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(StringUtils::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(StringUtils::isNotEmpty, exceptionCreator);
return this;
}
// ====== isEmpty =====
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) {
withRule(StringUtils::isEmpty, exceptionCreator);
return this;
}
@Override
protected StringValidator<DTO> thisObject() {
return this;
}
}

View File

@ -1,29 +0,0 @@
package xyz.zhouxy.plusone.validator;
/**
*
* <p>
* {@link IValidateRequired}
* </p>
*
* @author <a href="https://gitee.com/zhouxy108">ZhouXY</a>
*
* @see BaseValidator
* @see Validator
* @see IValidateRequired
*/
public class ValidateUtil {
private ValidateUtil() {
throw new IllegalStateException("Utility class");
}
public static 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>
* </p>
*
* @author <a href="https://gitee.com/zhouxy108">ZhouXY</a>
* @author ZhouXY
* @see IValidateRequired
* @see ValidateUtil
* @see BaseValidator

View File

@ -0,0 +1,37 @@
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

@ -0,0 +1,71 @@
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,6 +1,6 @@
package xyz.zhouxy.plusone.validator2.test;
package xyz.zhouxy.plusone.pojo;
import static xyz.zhouxy.plusone.commons.constant.PatternConsts.*;
import static xyz.zhouxy.plusone.constant.Patterns.*;
import java.util.Arrays;
import java.util.List;
@ -12,8 +12,7 @@ import org.junit.jupiter.api.Test;
import com.google.common.base.Preconditions;
import xyz.zhouxy.plusone.commons.function.Predicates;
import xyz.zhouxy.plusone.commons.util.MoreCollections;
import xyz.zhouxy.plusone.commons.util.Predicates;
import xyz.zhouxy.plusone.commons.util.RegexUtil;
import xyz.zhouxy.plusone.validator.Validator;
@ -32,29 +31,31 @@ class ValidatorTests {
return Objects.nonNull(username)
&& StringUtils.isNotEmpty(username)
&& StringUtils.isNotBlank(username)
&& RegexUtil.matches(username, 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, MOBILE_PHONE }))
.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), "验证码不符合规范");
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), "密码不符合规范");
Preconditions.checkArgument(RegexUtil.matches(password, PASSWORD.getPattern()), "密码不符合规范");
})
// 传入 predicate 和 Supplier<E extends RuntimeException>
.addRule(command -> MoreCollections.isNotEmpty(command.getRoles()),
() -> new 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()),
"两次输入的密码不一致");

View File

@ -1,137 +0,0 @@
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.Predicates;
import xyz.zhouxy.plusone.commons.util.RegexUtil;
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);
}
}
class RegisterCommandValidator extends BaseValidator<RegisterCommand> {
static final RegisterCommandValidator INSTANCE = new RegisterCommandValidator();
private RegisterCommandValidator() {
ruleForString(RegisterCommand::getUsername)
.isTrue(Predicates.<String>of(Objects::nonNull)
.and(StringUtils::isNotEmpty)
.and(StringUtils::isNotBlank)
.and(username -> RegexUtil.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
*/
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();
}
}