0.1.3-SNAPSHOT (#1)

Reviewed-on: #1
ZhouXY108 2024-08-05 08:59:30 +08:00
parent 8545dd714f
commit 4bef831a47
12 changed files with 276 additions and 128 deletions

View File

@ -1,4 +1,5 @@
{
"java.configuration.updateBuildConfiguration": "automatic",
"java.dependency.packagePresentation": "hierarchical"
"java.dependency.packagePresentation": "hierarchical",
"java.compile.nullAnalysis.mode": "automatic"
}

21
pom.xml
View File

@ -1,12 +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">
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>xyz.zhouxy.plusone</groupId>
<artifactId>plusone-validator</artifactId>
<version>0.1.2-SNAPSHOT</version>
<version>0.1.3-SNAPSHOT</version>
<name>plusone-validator</name>
<url>http://zhouxy.xyz</url>
@ -15,6 +15,7 @@
<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>
@ -24,15 +25,21 @@
<version>0.1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.9.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<!-- 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>

View File

@ -13,7 +13,7 @@ public class BaseValidator<T> {
private final List<PropertyValidator<T, ?, ?>> propertyValidators = new ArrayList<>();
protected void withRule(final Predicate<T> rule, final String errorMessage) {
withRule(rule, value -> new InvalidInputException(errorMessage));
withRule(rule, () -> InvalidInputException.of(errorMessage));
}
protected <E extends RuntimeException> void withRule(Predicate<T> rule, Supplier<E> exceptionBuilder) {

View File

@ -3,6 +3,8 @@ 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) {
@ -25,7 +27,7 @@ public class BoolValidator<DTO> extends PropertyValidator<DTO, Boolean, BoolVali
public <E extends RuntimeException> BoolValidator<DTO> isTrue(
Function<Boolean, E> exceptionCreator) {
withRule(Boolean.TRUE::equals, exceptionCreator);
withRule(BooleanUtils::isTrue, exceptionCreator);
return this;
}
@ -45,7 +47,7 @@ public class BoolValidator<DTO> extends PropertyValidator<DTO, Boolean, BoolVali
public <E extends RuntimeException> BoolValidator<DTO> isFalse(
Function<Boolean, E> exceptionCreator) {
withRule(Boolean.FALSE::equals, exceptionCreator);
withRule(BooleanUtils::isFalse, exceptionCreator);
return this;
}

View File

@ -22,12 +22,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 -> {
if (value == null) {
return false;
}
return !((Collection<?>) value).isEmpty();
}, exceptionCreator);
withRule(value -> value != null && !value.isEmpty(), exceptionCreator);
return this;
}
@ -43,12 +38,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 -> {
if (value == null) {
return false;
}
return ((Collection<?>) value).isEmpty();
}, exceptionCreator);
withRule(value -> value == null || value.isEmpty(), exceptionCreator);
return this;
}

View File

@ -10,7 +10,7 @@ public class IntValidator<DTO> extends PropertyValidator<DTO, Integer, IntValida
}
public IntValidator<DTO> between(int min, int max) {
return between(min, max, String.format("数值不在 %s 和 %s 之间", String.valueOf(min), String.valueOf(max)));
return between(min, max, String.format("数值不在 %d 和 %d 之间", min, max));
}
public IntValidator<DTO> between(int min, int max, String errMsg) {

View File

@ -1,53 +1,39 @@
package xyz.zhouxy.plusone.validator;
import xyz.zhouxy.plusone.exception.BaseException;
import xyz.zhouxy.plusone.commons.exception.BaseRuntimeException;
/**
* 4040200 -
* 4040000 -
*
* @author <a href="https://gitee.com/zhouxy108">ZhouXY</a>
*/
public class InvalidInputException extends BaseException {
public class InvalidInputException extends BaseRuntimeException {
private static final long serialVersionUID = 7956661913360059670L;
public static final int ERROR_CODE = 4040200;
public static final String ERROR_CODE = "4040000";
private InvalidInputException(int code, String msg) {
protected InvalidInputException(String code, String msg) {
super(code, msg);
}
private InvalidInputException(int code, Throwable cause) {
protected InvalidInputException(String code, Throwable cause) {
super(code, cause);
}
private InvalidInputException(int code, String msg, Throwable cause) {
protected InvalidInputException(String code, String msg, Throwable cause) {
super(code, msg, cause);
}
public InvalidInputException(String msg) {
this(ERROR_CODE, msg);
public static InvalidInputException of(String msg) {
return new InvalidInputException(ERROR_CODE, msg);
}
public InvalidInputException(Throwable cause) {
this(ERROR_CODE, cause);
public static InvalidInputException of(Throwable cause) {
return new InvalidInputException(ERROR_CODE, cause);
}
public InvalidInputException(String msg, Throwable cause) {
this(ERROR_CODE, msg, cause);
}
/**
* Principal
*/
public static InvalidInputException unsupportedPrincipalTypeException() {
return unsupportedPrincipalTypeException("不支持的 PrincipalType");
}
/**
* Principal
*/
public static InvalidInputException unsupportedPrincipalTypeException(String message) {
return new InvalidInputException(4040201, message);
public static InvalidInputException of(String msg, Throwable cause) {
return new InvalidInputException(ERROR_CODE, msg, cause);
}
}

View File

@ -69,7 +69,7 @@ abstract class PropertyValidator<DTO, PROPERTY, THIS> {
// ===== equals =====
public THIS equalsThat(Object that) {
return equalsThat(that, value -> new InvalidInputException(String.format("(%s) 必须与 (%s) 相等", value, that)));
return equalsThat(that, value -> InvalidInputException.of(String.format("(%s) 必须与 (%s) 相等", value, that)));
}
public THIS equalsThat(Object that, String errMsg) {
@ -87,46 +87,46 @@ abstract class PropertyValidator<DTO, PROPERTY, THIS> {
return thisObject();
}
// ===== state =====
// ===== isTrue =====
public THIS state(Predicate<PROPERTY> condition) {
return state(condition, "无效的用户输入");
public THIS isTrue(Predicate<PROPERTY> condition) {
return isTrue(condition, "无效的用户输入");
}
public THIS state(Predicate<PROPERTY> condition, String errMsg) {
return state(condition, convertExceptionCreator(errMsg));
public THIS isTrue(Predicate<PROPERTY> condition, String errMsg) {
return isTrue(condition, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> THIS state(
public <E extends RuntimeException> THIS isTrue(
Predicate<PROPERTY> condition,
Supplier<E> exceptionCreator) {
return state(condition, convertExceptionCreator(exceptionCreator));
return isTrue(condition, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> THIS state(
public <E extends RuntimeException> THIS isTrue(
Predicate<PROPERTY> condition,
Function<PROPERTY, E> exceptionCreator) {
withRule(condition, exceptionCreator);
return thisObject();
}
// ===== state =====
// ===== isTrue =====
public THIS state(Collection<Predicate<PROPERTY>> conditions) {
return state(conditions, "无效的用户输入");
public THIS isTrue(Collection<Predicate<PROPERTY>> conditions) {
return isTrue(conditions, "无效的用户输入");
}
public THIS state(Collection<Predicate<PROPERTY>> conditions, String errMsg) {
return state(conditions, convertExceptionCreator(errMsg));
public THIS isTrue(Collection<Predicate<PROPERTY>> conditions, String errMsg) {
return isTrue(conditions, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> THIS state(
public <E extends RuntimeException> THIS isTrue(
Collection<Predicate<PROPERTY>> conditions,
Supplier<E> exceptionCreator) {
return state(conditions, convertExceptionCreator(exceptionCreator));
return isTrue(conditions, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> THIS state(
public <E extends RuntimeException> THIS isTrue(
Collection<Predicate<PROPERTY>> conditions,
Function<PROPERTY, E> exceptionCreator) {
for (Predicate<PROPERTY> condition : conditions) {
@ -143,7 +143,7 @@ abstract class PropertyValidator<DTO, PROPERTY, THIS> {
}
static <V> Function<V, InvalidInputException> convertExceptionCreator(String errMsg) {
return value -> new InvalidInputException(errMsg);
return value -> InvalidInputException.of(errMsg);
}
static <V, E extends RuntimeException> Function<V, E> convertExceptionCreator(

View File

@ -1,12 +1,15 @@
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 cn.hutool.core.util.StrUtil;
import xyz.zhouxy.plusone.constant.RegexConsts;
import xyz.zhouxy.plusone.util.RegexUtil;
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>> {
@ -20,75 +23,92 @@ public class StringValidator<DTO> extends PropertyValidator<DTO, String, StringV
// ===== matches =====
public StringValidator<DTO> matches(String regex, String errMsg) {
public StringValidator<DTO> matches(Pattern regex, String errMsg) {
return matches(regex, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> StringValidator<DTO> matches(
String regex,
Pattern regex,
Supplier<E> exceptionCreator) {
return matches(regex, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> StringValidator<DTO> matches(
String regex,
Pattern regex,
Function<String, E> exceptionCreator) {
withRule(input -> RegexUtil.matches(input, regex), exceptionCreator);
return this;
}
// ===== matchesOr =====
// ===== matchesOne =====
public StringValidator<DTO> matchesOr(String[] regexs, String errMsg) {
return matchesOr(regexs, convertExceptionCreator(errMsg));
public StringValidator<DTO> matchesOne(Pattern[] regexs, String errMsg) {
return matchesOne(regexs, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> StringValidator<DTO> matchesOr(
String[] regexs,
public <E extends RuntimeException> StringValidator<DTO> matchesOne(
Pattern[] regexs,
Supplier<E> exceptionCreator) {
return matchesOr(regexs, convertExceptionCreator(exceptionCreator));
return matchesOne(regexs, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> StringValidator<DTO> matchesOr(
String[] regexs,
public <E extends RuntimeException> StringValidator<DTO> matchesOne(
Pattern[] regexs,
Function<String, E> exceptionCreator) {
withRule(input -> RegexUtil.matchesOr(input, regexs), exceptionCreator);
withRule(input -> RegexUtil.matchesOne(input, regexs), exceptionCreator);
return this;
}
public StringValidator<DTO> matchesOr(List<String> regexs, String errMsg) {
return matchesOr(regexs, convertExceptionCreator(errMsg));
public StringValidator<DTO> matchesOne(List<Pattern> regexs, String errMsg) {
return matchesOne(regexs, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> StringValidator<DTO> matchesOr(
List<String> regexs,
public <E extends RuntimeException> StringValidator<DTO> matchesOne(
List<Pattern> regexs,
Supplier<E> exceptionCreator) {
return matchesOr(regexs, convertExceptionCreator(exceptionCreator));
return matchesOne(regexs, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> StringValidator<DTO> matchesOr(
List<String> regexs,
public <E extends RuntimeException> StringValidator<DTO> matchesOne(
List<Pattern> regexs,
Function<String, E> exceptionCreator) {
withRule(input -> RegexUtil.matchesOr(input, regexs.toArray(new String[regexs.size()])), exceptionCreator);
withRule(input -> RegexUtil.matchesOne(input, regexs.toArray(new Pattern[regexs.size()])), exceptionCreator);
return this;
}
// ===== matchesAnd =====
// ===== matchesAll =====
public StringValidator<DTO> matchesAnd(String[] regexs, String errMsg) {
return matchesAnd(regexs, convertExceptionCreator(errMsg));
public StringValidator<DTO> matchesAll(Pattern[] regexs, String errMsg) {
return matchesAll(regexs, convertExceptionCreator(errMsg));
}
public <E extends RuntimeException> StringValidator<DTO> matchesAnd(
String[] regexs,
public <E extends RuntimeException> StringValidator<DTO> matchesAll(
Pattern[] regexs,
Supplier<E> exceptionCreator) {
return matchesAnd(regexs, convertExceptionCreator(exceptionCreator));
return matchesAll(regexs, convertExceptionCreator(exceptionCreator));
}
public <E extends RuntimeException> StringValidator<DTO> matchesAnd(
String[] regexs,
public <E extends RuntimeException> StringValidator<DTO> matchesAll(
Pattern[] regexs,
Function<String, E> exceptionCreator) {
withRule(input -> RegexUtil.matchesAnd(input, regexs), 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;
}
@ -108,7 +128,7 @@ public class StringValidator<DTO> extends PropertyValidator<DTO, String, StringV
public <E extends RuntimeException> StringValidator<DTO> notBlank(
Function<String, E> exceptionCreator) {
withRule(input -> StrUtil.isNotBlank(input), exceptionCreator);
withRule(StringUtils::isNotBlank, exceptionCreator);
return this;
}
@ -127,7 +147,7 @@ public class StringValidator<DTO> extends PropertyValidator<DTO, String, StringV
}
public <E extends RuntimeException> StringValidator<DTO> email(Function<String, E> exceptionCreator) {
return matches(RegexConsts.EMAIL, exceptionCreator);
return matches(PatternConsts.EMAIL, exceptionCreator);
}
// ====== notEmpty =====
@ -142,12 +162,7 @@ public class StringValidator<DTO> extends PropertyValidator<DTO, String, StringV
public <E extends RuntimeException> StringValidator<DTO> notEmpty(
Function<String, E> exceptionCreator) {
withRule(value -> {
if (value == null) {
return false;
}
return !(value.isEmpty());
}, exceptionCreator);
withRule(StringUtils::isNotEmpty, exceptionCreator);
return this;
}
@ -163,12 +178,7 @@ public class StringValidator<DTO> extends PropertyValidator<DTO, String, StringV
public <E extends RuntimeException> StringValidator<DTO> isEmpty(
Function<String, E> exceptionCreator) {
withRule(value -> {
if (value == null) {
return false;
}
return value.isEmpty();
}, exceptionCreator);
withRule(StringUtils::isEmpty, exceptionCreator);
return this;
}

View File

@ -4,15 +4,18 @@ import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import org.junit.Test;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import xyz.zhouxy.plusone.constant.RegexConsts;
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;
public class BaseValidatorTest {
class BaseValidatorTest {
@Test
public void testValidate() {
void testValidate() {
RegisterCommand registerCommand = new RegisterCommand("zhouxy108", "luquanlion@outlook.com", "22336", "A1b2C3d4",
"A1b2C3d4",
Arrays.asList(new String[] { "admin", "editor" }));
@ -28,18 +31,20 @@ class RegisterCommandValidator extends BaseValidator<RegisterCommand> {
private RegisterCommandValidator() {
ruleForString(RegisterCommand::getUsername)
.notNull("用户名不能为空")
.matches(RegexConsts.USERNAME,
username -> new IllegalArgumentException(String.format("用户名\"%s\"不符合规范", username)));
.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("请输入邮箱地址或手机号")
.matchesOr(new String[] { RegexConsts.EMAIL, RegexConsts.MOBILE_PHONE }, "请输入邮箱地址或手机号");
.matchesOne(Arrays.asList(PatternConsts.EMAIL, PatternConsts.MOBILE_PHONE), "请输入邮箱地址或手机号");
ruleForString(RegisterCommand::getCode)
.notNull("验证码不能为空")
.matches(RegexConsts.CAPTCHA, "验证码不符合规范");
.matches(PatternConsts.CAPTCHA, "验证码不符合规范");
ruleForString(RegisterCommand::getPassword)
.notEmpty("密码不能为空")
.matches(RegexConsts.PASSWORD, "密码不符合规范");
.matches(PatternConsts.PASSWORD, "密码不符合规范");
ruleForCollection(RegisterCommand::getRoles)
.notEmpty(() -> new RuntimeException("角色列表不能为空"));

View File

@ -0,0 +1,147 @@
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();
}
}