Compare commits
10 Commits
Author | SHA1 | Date |
---|---|---|
ZhouXY108 | 25ec5577cc | |
ZhouXY108 | 315ff1950f | |
ZhouXY108 | 00b9f16176 | |
ZhouXY108 | cb1ad03b9b | |
ZhouXY108 | b03f978da9 | |
ZhouXY108 | 3cac270574 | |
ZhouXY108 | 49f2c437f5 | |
ZhouXY108 | a71d75029e | |
ZhouXY108 | c1a7bafaf6 | |
ZhouXY108 | 92e142dcf3 |
|
@ -0,0 +1,12 @@
|
|||
# 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
|
6
pom.xml
6
pom.xml
|
@ -6,7 +6,7 @@
|
|||
|
||||
<groupId>xyz.zhouxy.plusone</groupId>
|
||||
<artifactId>plusone-validator</artifactId>
|
||||
<version>0.1.3-SNAPSHOT</version>
|
||||
<version>0.1.5-SNAPSHOT</version>
|
||||
|
||||
<name>plusone-validator</name>
|
||||
<url>http://zhouxy.xyz</url>
|
||||
|
@ -15,7 +15,6 @@
|
|||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<maven.compiler.target>1.8</maven.compiler.target>
|
||||
<maven.compiler.source>1.8</maven.compiler.source>
|
||||
<commons-lang3.version>3.12.0</commons-lang3.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
|
@ -27,7 +26,8 @@
|
|||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-lang3</artifactId>
|
||||
<version>${commons-lang3.version}</version>
|
||||
<version>3.12.0</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
|
|
|
@ -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();
|
||||
}
|
||||
}
|
|
@ -9,19 +9,18 @@ import java.util.function.Predicate;
|
|||
import java.util.function.Supplier;
|
||||
|
||||
public class BaseValidator<T> {
|
||||
private final List<Consumer<T>> rules = new ArrayList<>();
|
||||
private final List<PropertyValidator<T, ?, ?>> propertyValidators = new ArrayList<>();
|
||||
private final List<Consumer<? super T>> rules = new ArrayList<>();
|
||||
|
||||
protected void withRule(final Predicate<T> rule, final String errorMessage) {
|
||||
withRule(rule, () -> InvalidInputException.of(errorMessage));
|
||||
withRule(rule, () -> new IllegalArgumentException(errorMessage));
|
||||
}
|
||||
|
||||
protected <E extends RuntimeException> void withRule(Predicate<T> rule, Supplier<E> exceptionBuilder) {
|
||||
protected <E extends RuntimeException> void withRule(Predicate<? super T> rule, Supplier<E> exceptionBuilder) {
|
||||
withRule(rule, value -> exceptionBuilder.get());
|
||||
}
|
||||
|
||||
protected <E extends RuntimeException> void withRule(Predicate<T> condition,
|
||||
Function<T, E> exceptionBuilder) {
|
||||
protected <E extends RuntimeException> void withRule(
|
||||
Predicate<? super T> condition, Function<T, E> exceptionBuilder) {
|
||||
withRule(value -> {
|
||||
if (!condition.test(value)) {
|
||||
throw exceptionBuilder.apply(value);
|
||||
|
@ -29,52 +28,47 @@ public class BaseValidator<T> {
|
|||
});
|
||||
}
|
||||
|
||||
protected void withRule(Consumer<T> rule) {
|
||||
protected void withRule(Consumer<? super T> rule) {
|
||||
this.rules.add(rule);
|
||||
}
|
||||
|
||||
protected final <R> ObjectValidator<T, R> ruleFor(Function<T, R> getter) {
|
||||
ObjectValidator<T, R> validValueHolder = new ObjectValidator<>(getter);
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
ObjectValidator<T, R> validator = new ObjectValidator<>(getter);
|
||||
this.rules.add(validator::validate);
|
||||
return validator;
|
||||
}
|
||||
|
||||
protected final IntValidator<T> ruleForInt(Function<T, Integer> getter) {
|
||||
IntValidator<T> validValueHolder = new IntValidator<>(getter);
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
IntValidator<T> validator = new IntValidator<>(getter);
|
||||
this.rules.add(validator::validate);
|
||||
return validator;
|
||||
}
|
||||
|
||||
protected final DoubleValidator<T> ruleForDouble(Function<T, Double> getter) {
|
||||
DoubleValidator<T> validValueHolder = new DoubleValidator<>(getter);
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
DoubleValidator<T> validator = new DoubleValidator<>(getter);
|
||||
this.rules.add(validator::validate);
|
||||
return validator;
|
||||
}
|
||||
|
||||
protected final BoolValidator<T> ruleForBool(Function<T, Boolean> getter) {
|
||||
BoolValidator<T> validValueHolder = new BoolValidator<>(getter);
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
BoolValidator<T> validator = new BoolValidator<>(getter);
|
||||
this.rules.add(validator::validate);
|
||||
return validator;
|
||||
}
|
||||
|
||||
protected final StringValidator<T> ruleForString(Function<T, String> getter) {
|
||||
StringValidator<T> validValueHolder = new StringValidator<>(getter);
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
StringValidator<T> validator = new StringValidator<>(getter);
|
||||
this.rules.add(validator::validate);
|
||||
return validator;
|
||||
}
|
||||
|
||||
protected final <E> CollectionValidator<T, E> ruleForCollection(Function<T, Collection<E>> getter) {
|
||||
CollectionValidator<T, E> validValueHolder = new CollectionValidator<>(getter);
|
||||
propertyValidators.add(validValueHolder);
|
||||
return validValueHolder;
|
||||
CollectionValidator<T, E> validator = new CollectionValidator<>(getter);
|
||||
this.rules.add(validator::validate);
|
||||
return validator;
|
||||
}
|
||||
|
||||
public void validate(T obj) {
|
||||
for (Consumer<T> rule : this.rules) {
|
||||
rule.accept(obj);
|
||||
}
|
||||
for (PropertyValidator<T, ?, ?> valueValidator : this.propertyValidators) {
|
||||
valueValidator.validate(obj);
|
||||
}
|
||||
this.rules.forEach(rule -> rule.accept(obj));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,9 +3,7 @@ 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>> {
|
||||
public class BoolValidator<DTO> extends BasePropertyValidator<DTO, Boolean, BoolValidator<DTO>> {
|
||||
|
||||
BoolValidator(Function<DTO, Boolean> getter) {
|
||||
super(getter);
|
||||
|
@ -27,7 +25,7 @@ public class BoolValidator<DTO> extends PropertyValidator<DTO, Boolean, BoolVali
|
|||
|
||||
public <E extends RuntimeException> BoolValidator<DTO> isTrue(
|
||||
Function<Boolean, E> exceptionCreator) {
|
||||
withRule(BooleanUtils::isTrue, exceptionCreator);
|
||||
withRule(Boolean.TRUE::equals, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
@ -47,7 +45,7 @@ public class BoolValidator<DTO> extends PropertyValidator<DTO, Boolean, BoolVali
|
|||
|
||||
public <E extends RuntimeException> BoolValidator<DTO> isFalse(
|
||||
Function<Boolean, E> exceptionCreator) {
|
||||
withRule(BooleanUtils::isFalse, exceptionCreator);
|
||||
withRule(Boolean.FALSE::equals, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
|
|
@ -4,7 +4,10 @@ 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>> {
|
||||
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);
|
||||
|
@ -22,7 +25,7 @@ public class CollectionValidator<DTO, T> extends PropertyValidator<DTO, Collecti
|
|||
|
||||
public <E extends RuntimeException> CollectionValidator<DTO, T> notEmpty(
|
||||
Function<Collection<T>, E> exceptionCreator) {
|
||||
withRule(value -> value != null && !value.isEmpty(), exceptionCreator);
|
||||
withRule(CollectionTools::isNotEmpty, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
@ -38,7 +41,7 @@ public class CollectionValidator<DTO, T> extends PropertyValidator<DTO, Collecti
|
|||
|
||||
public <E extends RuntimeException> CollectionValidator<DTO, T> isEmpty(
|
||||
Function<Collection<T>, E> exceptionCreator) {
|
||||
withRule(value -> value == null || value.isEmpty(), exceptionCreator);
|
||||
withRule(CollectionTools::isEmpty, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
|
|
@ -3,7 +3,7 @@ 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>> {
|
||||
public class DoubleValidator<DTO> extends BasePropertyValidator<DTO, Double, DoubleValidator<DTO>> {
|
||||
|
||||
DoubleValidator(Function<DTO, Double> getter) {
|
||||
super(getter);
|
||||
|
|
|
@ -3,7 +3,7 @@ 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>> {
|
||||
public class IntValidator<DTO> extends BasePropertyValidator<DTO, Integer, IntValidator<DTO>> {
|
||||
|
||||
IntValidator(Function<DTO, Integer> getter) {
|
||||
super(getter);
|
||||
|
|
|
@ -1,39 +0,0 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
import xyz.zhouxy.plusone.commons.exception.BaseRuntimeException;
|
||||
|
||||
/**
|
||||
* 4040000 - 用户请求参数错误
|
||||
*
|
||||
* @author <a href="https://gitee.com/zhouxy108">ZhouXY</a>
|
||||
*/
|
||||
public class InvalidInputException extends BaseRuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 7956661913360059670L;
|
||||
|
||||
public static final String ERROR_CODE = "4040000";
|
||||
|
||||
protected InvalidInputException(String code, String msg) {
|
||||
super(code, msg);
|
||||
}
|
||||
|
||||
protected InvalidInputException(String code, Throwable cause) {
|
||||
super(code, cause);
|
||||
}
|
||||
|
||||
protected InvalidInputException(String code, String msg, Throwable cause) {
|
||||
super(code, msg, cause);
|
||||
}
|
||||
|
||||
public static InvalidInputException of(String msg) {
|
||||
return new InvalidInputException(ERROR_CODE, msg);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,71 @@
|
|||
package xyz.zhouxy.plusone.validator;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
public abstract class MapValidator<K, V> extends BaseValidator<Map<K, V>> {
|
||||
|
||||
private final Set<K> keys;
|
||||
|
||||
protected MapValidator(K[] keys) {
|
||||
this(Arrays.asList(keys));
|
||||
}
|
||||
|
||||
protected MapValidator(Collection<K> keys) {
|
||||
this.keys = keys.stream().collect(Collectors.toSet());
|
||||
}
|
||||
|
||||
// ========== validate & validateAndCopy ==========
|
||||
|
||||
public final Map<K, V> validateAndCopy(Map<K, V> obj) {
|
||||
return validateAndCopyInternal(obj, this.keys);
|
||||
}
|
||||
|
||||
public final Map<K, V> validateAndCopy(Map<K, V> obj, Collection<K> keys) {
|
||||
return validateAndCopyInternal(obj, keys);
|
||||
}
|
||||
|
||||
@SafeVarargs
|
||||
public final Map<K, V> validateAndCopy(Map<K, V> obj, K... keys) {
|
||||
return validateAndCopyInternal(obj, Arrays.asList(keys));
|
||||
}
|
||||
|
||||
private final Map<K, V> validateAndCopyInternal(Map<K, V> obj, Collection<K> keys) {
|
||||
validate(obj);
|
||||
return obj.entrySet().stream()
|
||||
.filter(kv -> keys.contains(kv.getKey()))
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
}
|
||||
|
||||
// ========== ruleFor ==========
|
||||
|
||||
protected final ObjectValidator<Map<K, V>, V> ruleFor(K key) {
|
||||
return ruleFor(m -> m.get(key));
|
||||
}
|
||||
|
||||
protected final IntValidator<Map<K, V>> ruleForInt(K key) {
|
||||
return ruleForInt(m -> (Integer) m.get(key));
|
||||
}
|
||||
|
||||
protected final DoubleValidator<Map<K, V>> ruleForDouble(K key) {
|
||||
return ruleForDouble(m -> (Double) m.get(key));
|
||||
}
|
||||
|
||||
protected final BoolValidator<Map<K, V>> ruleForBool(K key) {
|
||||
return ruleForBool(m -> (Boolean) m.get(key));
|
||||
}
|
||||
|
||||
protected final StringValidator<Map<K, V>> ruleForString(K key) {
|
||||
return ruleForString(m -> (String) m.get(key));
|
||||
}
|
||||
|
||||
protected final <E> CollectionValidator<Map<K, V>, E> ruleForCollection(K key) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Function<Map<K, V>, Collection<E>> getter = m -> (Collection<E>) m.get(key);
|
||||
return ruleForCollection(getter);
|
||||
}
|
||||
}
|
|
@ -2,7 +2,7 @@ package xyz.zhouxy.plusone.validator;
|
|||
|
||||
import java.util.function.Function;
|
||||
|
||||
public class ObjectValidator<DTO, T> extends PropertyValidator<DTO, T, ObjectValidator<DTO, T>> {
|
||||
public class ObjectValidator<DTO, T> extends BasePropertyValidator<DTO, T, ObjectValidator<DTO, T>> {
|
||||
|
||||
ObjectValidator(Function<DTO, T> getter) {
|
||||
super(getter);
|
||||
|
|
|
@ -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();
|
||||
}
|
|
@ -6,12 +6,12 @@ import java.util.function.Function;
|
|||
import java.util.function.Supplier;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
import xyz.zhouxy.plusone.commons.constant.PatternConsts;
|
||||
import xyz.zhouxy.plusone.commons.util.RegexUtil;
|
||||
import xyz.zhouxy.plusone.commons.util.RegexTools;
|
||||
|
||||
public class StringValidator<DTO> extends PropertyValidator<DTO, String, StringValidator<DTO>> {
|
||||
public class StringValidator<DTO> extends BasePropertyValidator<DTO, String, StringValidator<DTO>> {
|
||||
|
||||
StringValidator(Function<DTO, String> getter) {
|
||||
super(getter);
|
||||
|
@ -36,7 +36,7 @@ public class StringValidator<DTO> extends PropertyValidator<DTO, String, StringV
|
|||
public <E extends RuntimeException> StringValidator<DTO> matches(
|
||||
Pattern regex,
|
||||
Function<String, E> exceptionCreator) {
|
||||
withRule(input -> RegexUtil.matches(input, regex), exceptionCreator);
|
||||
withRule(input -> RegexTools.matches(input, regex), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
@ -55,7 +55,7 @@ public class StringValidator<DTO> extends PropertyValidator<DTO, String, StringV
|
|||
public <E extends RuntimeException> StringValidator<DTO> matchesOne(
|
||||
Pattern[] regexs,
|
||||
Function<String, E> exceptionCreator) {
|
||||
withRule(input -> RegexUtil.matchesOne(input, regexs), exceptionCreator);
|
||||
withRule(input -> RegexTools.matchesOne(input, regexs), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
@ -72,7 +72,7 @@ public class StringValidator<DTO> extends PropertyValidator<DTO, String, StringV
|
|||
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);
|
||||
withRule(input -> RegexTools.matchesOne(input, regexs.toArray(new Pattern[regexs.size()])), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
@ -91,7 +91,7 @@ public class StringValidator<DTO> extends PropertyValidator<DTO, String, StringV
|
|||
public <E extends RuntimeException> StringValidator<DTO> matchesAll(
|
||||
Pattern[] regexs,
|
||||
Function<String, E> exceptionCreator) {
|
||||
withRule(input -> RegexUtil.matchesAll(input, regexs), exceptionCreator);
|
||||
withRule(input -> RegexTools.matchesAll(input, regexs), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
@ -108,12 +108,24 @@ public class StringValidator<DTO> extends PropertyValidator<DTO, String, StringV
|
|||
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);
|
||||
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");
|
||||
}
|
||||
|
@ -128,7 +140,7 @@ public class StringValidator<DTO> extends PropertyValidator<DTO, String, StringV
|
|||
|
||||
public <E extends RuntimeException> StringValidator<DTO> notBlank(
|
||||
Function<String, E> exceptionCreator) {
|
||||
withRule(StringUtils::isNotBlank, exceptionCreator);
|
||||
withRule(StringValidator::isNotBlank, exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
|
@ -162,23 +174,66 @@ public class StringValidator<DTO> extends PropertyValidator<DTO, String, StringV
|
|||
|
||||
public <E extends RuntimeException> StringValidator<DTO> notEmpty(
|
||||
Function<String, E> exceptionCreator) {
|
||||
withRule(StringUtils::isNotEmpty, exceptionCreator);
|
||||
withRule(s -> s != null && !s.isEmpty(), exceptionCreator);
|
||||
return this;
|
||||
}
|
||||
|
||||
// ====== isEmpty =====
|
||||
// ====== isNullOrEmpty =====
|
||||
|
||||
public StringValidator<DTO> isEmpty(String errMsg) {
|
||||
return isEmpty(convertExceptionCreator(errMsg));
|
||||
public StringValidator<DTO> isNullOrEmpty(String errMsg) {
|
||||
return isNullOrEmpty(convertExceptionCreator(errMsg));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> isEmpty(Supplier<E> exceptionCreator) {
|
||||
return isEmpty(convertExceptionCreator(exceptionCreator));
|
||||
public <E extends RuntimeException> StringValidator<DTO> isNullOrEmpty(Supplier<E> exceptionCreator) {
|
||||
return isNullOrEmpty(convertExceptionCreator(exceptionCreator));
|
||||
}
|
||||
|
||||
public <E extends RuntimeException> StringValidator<DTO> isEmpty(
|
||||
public <E extends RuntimeException> StringValidator<DTO> isNullOrEmpty(
|
||||
Function<String, E> exceptionCreator) {
|
||||
withRule(StringUtils::isEmpty, 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;
|
||||
}
|
||||
|
||||
|
|
|
@ -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("角色标识不能为空!"));
|
||||
}
|
||||
}
|
|
@ -8,130 +8,136 @@ 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.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",
|
||||
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 class RegisterCommandValidator extends BaseValidator<RegisterCommand> {
|
||||
|
||||
static final RegisterCommandValidator INSTANCE = new RegisterCommandValidator();
|
||||
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("角色列表不能为空"));
|
||||
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
|
||||
*/
|
||||
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();
|
||||
withRule(registerCommand -> Objects.equals(registerCommand.getPassword(), registerCommand.getPassword2()),
|
||||
"两次输入的密码不一致");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* RegisterCommand
|
||||
*/
|
||||
static class RegisterCommand {
|
||||
|
||||
private String username;
|
||||
private String account;
|
||||
private String code;
|
||||
private String password;
|
||||
private String password2;
|
||||
private List<String> roles;
|
||||
|
||||
public RegisterCommand() {
|
||||
}
|
||||
|
||||
public RegisterCommand(String username, String account, String code, String password, String password2,
|
||||
List<String> roles) {
|
||||
this.username = username;
|
||||
this.account = account;
|
||||
this.code = code;
|
||||
this.password = password;
|
||||
this.password2 = password2;
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getAccount() {
|
||||
return account;
|
||||
}
|
||||
|
||||
public void setAccount(String account) {
|
||||
this.account = account;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getPassword2() {
|
||||
return password2;
|
||||
}
|
||||
|
||||
public void setPassword2(String password2) {
|
||||
this.password2 = password2;
|
||||
}
|
||||
|
||||
public List<String> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
public void setRoles(List<String> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return new StringBuilder()
|
||||
.append("RegisterCommand [")
|
||||
.append("username=").append(username)
|
||||
.append(", account=").append(account)
|
||||
.append(", code=").append(code)
|
||||
.append(", password=").append(password)
|
||||
.append(", password2=").append(password2)
|
||||
.append(", roles=").append(roles)
|
||||
.append("]")
|
||||
.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,147 @@
|
|||
package xyz.zhouxy.plusone.validator.test;
|
||||
|
||||
import static xyz.zhouxy.plusone.commons.constant.PatternConsts.*;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.google.common.base.Preconditions;
|
||||
|
||||
import xyz.zhouxy.plusone.commons.collection.CollectionTools;
|
||||
import xyz.zhouxy.plusone.commons.function.PredicateTools;
|
||||
import xyz.zhouxy.plusone.commons.util.RegexTools;
|
||||
import xyz.zhouxy.plusone.validator.Validator;
|
||||
|
||||
class ValidatorTests {
|
||||
@Test
|
||||
void testValidate() {
|
||||
RegisterCommand registerCommand = new RegisterCommand(
|
||||
"null", "luquanlion@outlook.com", "22336",
|
||||
"A1b2C3d4", "A1b2C3d4",
|
||||
Arrays.asList(new String[] { "admin", "editor" }));
|
||||
|
||||
Validator<RegisterCommand> registerCommandValidator = new Validator<RegisterCommand>()
|
||||
// 传入 predicate 和 Function<T, E extends RuntimeException>
|
||||
.addRule(command -> {
|
||||
String username = command.getUsername();
|
||||
return Objects.nonNull(username)
|
||||
&& StringUtils.isNotEmpty(username)
|
||||
&& StringUtils.isNotBlank(username)
|
||||
&& RegexTools.matches(username, USERNAME);
|
||||
}, command -> new IllegalArgumentException(String.format("用户名【%s】不符合规范", command.getUsername())))
|
||||
// 传入 predicate 和 error message
|
||||
.addRule(command -> PredicateTools
|
||||
.<String>from(Objects::nonNull)
|
||||
.and(account -> RegexTools.matchesOne(account, new Pattern[] { EMAIL, MOBILE_PHONE }))
|
||||
.test(command.getAccount()),
|
||||
"请输入邮箱地址或手机号")
|
||||
// 传入 rule
|
||||
.addRule(command -> {
|
||||
String code = command.getCode();
|
||||
Preconditions.checkArgument(Objects.nonNull(code), "验证码不能为空");
|
||||
Preconditions.checkArgument(RegexTools.matches(code, CAPTCHA), "验证码不符合规范");
|
||||
})
|
||||
// 传入 rule
|
||||
.addRule(command -> {
|
||||
String password = command.getPassword();
|
||||
Preconditions.checkArgument(StringUtils.isNotEmpty(password), "密码不能为空");
|
||||
Preconditions.checkArgument(RegexTools.matches(password, PASSWORD), "密码不符合规范");
|
||||
})
|
||||
// 传入 predicate 和 Supplier<E extends RuntimeException>
|
||||
.addRule(command -> CollectionTools.isNotEmpty(command.getRoles()),
|
||||
() -> new RuntimeException("角色列表不能为空"))
|
||||
// 传入 predicate 和 error message
|
||||
.addRule(command -> Objects.equals(command.getPassword(), command.getPassword2()),
|
||||
"两次输入的密码不一致");
|
||||
registerCommandValidator.validate(registerCommand);
|
||||
System.out.println(registerCommand);
|
||||
}
|
||||
|
||||
/**
|
||||
* RegisterCommand
|
||||
*/
|
||||
static class RegisterCommand {
|
||||
|
||||
private String username;
|
||||
private String account;
|
||||
private String code;
|
||||
private String password;
|
||||
private String password2;
|
||||
private List<String> roles;
|
||||
|
||||
public RegisterCommand() {
|
||||
}
|
||||
|
||||
public RegisterCommand(String username, String account, String code, String password, String password2,
|
||||
List<String> roles) {
|
||||
this.username = username;
|
||||
this.account = account;
|
||||
this.code = code;
|
||||
this.password = password;
|
||||
this.password2 = password2;
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getAccount() {
|
||||
return account;
|
||||
}
|
||||
|
||||
public void setAccount(String account) {
|
||||
this.account = account;
|
||||
}
|
||||
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(String code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public String getPassword2() {
|
||||
return password2;
|
||||
}
|
||||
|
||||
public void setPassword2(String password2) {
|
||||
this.password2 = password2;
|
||||
}
|
||||
|
||||
public List<String> getRoles() {
|
||||
return roles;
|
||||
}
|
||||
|
||||
public void setRoles(List<String> roles) {
|
||||
this.roles = roles;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
builder.append("RegisterCommand [username=").append(username).append(", account=").append(account)
|
||||
.append(", code=").append(code).append(", password=").append(password).append(", password2=")
|
||||
.append(password2).append(", roles=").append(roles).append("]");
|
||||
return builder.toString();
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,147 +0,0 @@
|
|||
package xyz.zhouxy.plusone.validator2.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.function.Predicates;
|
||||
import xyz.zhouxy.plusone.commons.util.MoreCollections;
|
||||
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);
|
||||
}, 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 }))
|
||||
.test(command.getAccount()),
|
||||
"请输入邮箱地址或手机号")
|
||||
// 传入 rule
|
||||
.addRule(command -> {
|
||||
String code = command.getCode();
|
||||
Preconditions.checkArgument(Objects.nonNull(code), "验证码不能为空");
|
||||
Preconditions.checkArgument(RegexUtil.matches(code, CAPTCHA), "验证码不符合规范");
|
||||
})
|
||||
// 传入 rule
|
||||
.addRule(command -> {
|
||||
String password = command.getPassword();
|
||||
Preconditions.checkArgument(StringUtils.isNotEmpty(password), "密码不能为空");
|
||||
Preconditions.checkArgument(RegexUtil.matches(password, PASSWORD), "密码不符合规范");
|
||||
})
|
||||
// 传入 predicate 和 Supplier<E extends RuntimeException>
|
||||
.addRule(command -> MoreCollections.isNotEmpty(command.getRoles()),
|
||||
() -> 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();
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue