1 Commits

Author SHA1 Message Date
6556a53163 refactor!: 重构 MultiTypesException (#58@Gitea)
- 将 `MultiTypesException` 重命名为 `IMultiTypesException`
- 将 `ExceptionType` 重命名为 `IExceptionType`
- 将 `IExceptionType` 中的工厂方法抽取到 `IExceptionFactory` 中
- 在 `IMultiTypesException` 接口中添加泛型参数 `TCode`,用于指定异常类型代码的类型
- 在 `IExceptionType` 接口中添加 `getDescription` 方法,用于获取异常类型的描述信息

Co-authored-by: ZhouXY108 <luquanlion@outlook.com>
Co-committed-by: ZhouXY108 <luquanlion@outlook.com>
2025-07-25 09:28:59 +08:00
19 changed files with 124 additions and 620 deletions

View File

@@ -68,16 +68,16 @@ System.out.println(result); // Output: Return string
`RegexConsts` 包含常见正则表达式;`PatternConsts` 包含对应的 `Pattern` 对象
## 五、exception - 异常
### 1. MultiTypesException - 多类型异常
### 1. IMultiTypesException - 多类型异常
异常在不同场景下被抛出,可以用不同的枚举值,表示不同的场景类型。
异常实现 `MultiTypesException` 的 `MultiTypesException#getType` 方法,返回对应的场景类型。
异常实现 `IMultiTypesException` 的 `IMultiTypesException#getType` 方法,返回对应的场景类型。
表示场景类型的枚举实现 `MultiTypesException.ExceptionType`,其中的工厂方法用于创建对应类型的异常。
表示场景类型的枚举实现 `IMultiTypesException.IExceptionType`,其中的工厂方法用于创建对应类型的异常。
```java
public final class LoginException
extends RuntimeException
implements MultiTypesException<LoginException, LoginException.Type> {
implements IMultiTypesException<LoginException, LoginException.Type, String> {
private static final long serialVersionUID = 881293090625085616L;
private final Type type;
private LoginException(@Nonnull Type type, @Nonnull String message) {
@@ -104,7 +104,7 @@ public final class LoginException
// ...
public enum Type implements ExceptionType {
public enum Type implements IExceptionType<LoginException, String> {
DEFAULT("00", "当前会话未登录"),
NOT_TOKEN("10", "未提供token"),
INVALID_TOKEN("20", "token无效"),

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
package xyz.zhouxy.plusone.commons.regex;
package xyz.zhouxy.plusone.commons.constant;
import java.util.regex.Pattern;

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
package xyz.zhouxy.plusone.commons.regex;
package xyz.zhouxy.plusone.commons.constant;
/**
* 正则表达式常量
@@ -41,15 +41,12 @@ public final class RegexConsts {
public static final String 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}$";
public static final String USERNAME = "^[\\w-_]{4,36}$";
public static final String USERNAME = "^[\\w-_.@]{4,36}$";
public static final String NICKNAME = "^[\\w-_.@]{4,36}$";
public static final String CHINESE_2ND_ID_CARD_NUMBER
= "^(?<county>(?<city>(?<province>\\d{2})\\d{2})\\d{2})"
+ "(?<birthDate>\\d{8})"
+ "(?<orderCode>\\d{2}(?<gender>\\d))"
+ "(?<checkDigit>[\\dX])$";
= "^(?<county>(?<city>(?<province>\\d{2})\\d{2})\\d{2})(?<birthDate>\\d{8})\\d{2}(?<gender>\\d)([\\dX])$";
private RegexConsts() {
throw new IllegalStateException("Utility class");

View File

@@ -14,4 +14,16 @@
* limitations under the License.
*/
package xyz.zhouxy.plusone.commons.regex;
/**
* <h2>常量</h2>
*
* <h3>
* 1. 正则常量
* </h3>
* {@link RegexConsts} 包含常见正则表达式{@link PatternConsts} 包含对应的 {@link Pattern} 对象
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
*/
package xyz.zhouxy.plusone.commons.constant;
import java.util.regex.Pattern;

View File

@@ -0,0 +1,61 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.commons.exception;
import javax.annotation.Nonnull;
/**
* 异常工厂
*
* @author ZhouXY
*/
public interface IExceptionFactory<X extends Exception> {
/**
* 创建异常
*
* @return 异常对象
*/
@Nonnull
X create();
/**
* 使用指定 {@code message} 创建异常
*
* @param message 异常信息
* @return 异常对象
*/
@Nonnull
X create(String message);
/**
* 使用指定 {@code cause} 创建异常
*
* @param cause 包装的异常
* @return 异常对象
*/
@Nonnull
X create(Throwable cause);
/**
* 使用指定 {@code message} 和 {@code cause} 创建异常
*
* @param message 异常信息
* @param cause 包装的异常
* @return 异常对象
*/
@Nonnull
X create(String message, Throwable cause);
}

View File

@@ -15,26 +15,30 @@
*/
package xyz.zhouxy.plusone.commons.exception;
import java.io.Serializable;
import javax.annotation.Nonnull;
import xyz.zhouxy.plusone.commons.annotation.Virtual;
import xyz.zhouxy.plusone.commons.base.IWithCode;
/**
* MultiTypesException
* IMultiTypesException
*
* <p>
* 异常在不同场景下被抛出可以用不同的枚举值表示不同的场景类型
*
* <p>
* 异常实现 {@link MultiTypesException} {@link #getType} 方法返回对应的场景类型
* 异常实现 {@link IMultiTypesException} {@link #getType} 方法返回对应的场景类型
*
* <p>
* 表示场景类型的枚举实现 {@link ExceptionType}其中的工厂方法用于创建对应类型的异常
* 表示场景类型的枚举实现 {@link IExceptionType}各个枚举值本身就是该场景的异常的工厂实例
* 使用其中的工厂方法用于创建对应类型的异常
*
* <pre>
* public final class LoginException
* extends RuntimeException
* implements MultiTypesException&lt;LoginException, LoginException.Type&gt; {
* implements IMultiTypesException&lt;LoginException, LoginException.Type, String&gt; {
* private static final long serialVersionUID = 881293090625085616L;
* private final Type type;
* private LoginException(&#64;Nonnull Type type, &#64;Nonnull String message) {
@@ -61,7 +65,7 @@ import xyz.zhouxy.plusone.commons.base.IWithCode;
*
* // ...
*
* public enum Type implements ExceptionType&lt;LoginException&gt; {
* public enum Type implements IExceptionType&lt;LoginException, String&gt; {
* DEFAULT("00", "当前会话未登录"),
* NOT_TOKEN("10", "未提供token"),
* INVALID_TOKEN("20", "token无效"),
@@ -118,15 +122,20 @@ import xyz.zhouxy.plusone.commons.base.IWithCode;
* throw LoginException.Type.TOKEN_TIMEOUT.create();
* </pre>
*
* @param <X> 具体异常类
* @param <T> 异常场景
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @since 1.0.0
*/
public interface MultiTypesException<E extends Exception, T extends MultiTypesException.ExceptionType<E>> {
public interface IMultiTypesException<
X extends Exception,
T extends IMultiTypesException.IExceptionType<X, TCode>,
TCode extends Serializable> {
/**
* 异常类型
*
* @return 异常类型通常是实现了 {@link ExceptionType} 的枚举
* @return 异常类型通常是实现了 {@link IExceptionType} 的枚举
*/
@Nonnull
T getType();
@@ -136,55 +145,25 @@ public interface MultiTypesException<E extends Exception, T extends MultiTypesEx
*
* @return 异常类型编码
*/
default @Nonnull String getTypeCode() {
default @Nonnull TCode getTypeCode() {
return getType().getCode();
}
/**
* 异常类型
*/
public static interface ExceptionType<E extends Exception> extends IWithCode<String> {
public static interface IExceptionType<X extends Exception, TCode extends Serializable>
extends IWithCode<TCode>, IExceptionFactory<X> {
/**
* 默认异常信息
*/
String getDefaultMessage();
/**
* 创建异常
*
* @return 异常对象
*/
@Nonnull
E create();
/**
* 使用指定 {@code message} 创建异常
*
* @param message 异常信息
* @return 异常对象
*/
@Nonnull
E create(String message);
/**
* 使用指定 {@code cause} 创建异常
*
* @param cause 包装的异常
* @return 异常对象
*/
@Nonnull
E create(Throwable cause);
/**
* 使用指定 {@code message} {@code cause} 创建异常
*
* @param message 异常信息
* @param cause 包装的异常
* @return 异常对象
*/
@Nonnull
E create(String message, Throwable cause);
@Virtual
default String getDescription() {
return getDefaultMessage();
}
}
}

View File

@@ -21,7 +21,7 @@ import java.time.format.DateTimeParseException;
import javax.annotation.Nonnull;
import xyz.zhouxy.plusone.commons.exception.business.RequestParamsException;
import xyz.zhouxy.plusone.commons.exception.MultiTypesException.ExceptionType;
import xyz.zhouxy.plusone.commons.exception.IMultiTypesException.IExceptionType;
/**
* 解析失败异常
@@ -39,7 +39,7 @@ import xyz.zhouxy.plusone.commons.exception.MultiTypesException.ExceptionType;
*/
public final class ParsingFailureException
extends Exception
implements MultiTypesException<ParsingFailureException, ParsingFailureException.Type> {
implements IMultiTypesException<ParsingFailureException, ParsingFailureException.Type, String> {
private static final long serialVersionUID = 795996090625132616L;
private final Type type;
@@ -171,7 +171,7 @@ public final class ParsingFailureException
/** XML 解析失败 */
public static final Type XML_PARSING_FAILURE = Type.XML_PARSING_FAILURE;
public enum Type implements ExceptionType<ParsingFailureException> {
public enum Type implements IExceptionType<ParsingFailureException, String> {
DEFAULT("00", "解析失败"),
NUMBER_PARSING_FAILURE("10", "数字转换失败"),
DATE_TIME_PARSING_FAILURE("20", "时间解析失败"),

View File

@@ -18,8 +18,8 @@ package xyz.zhouxy.plusone.commons.exception.business;
import javax.annotation.Nonnull;
import xyz.zhouxy.plusone.commons.exception.MultiTypesException.ExceptionType;
import xyz.zhouxy.plusone.commons.exception.MultiTypesException;
import xyz.zhouxy.plusone.commons.exception.IMultiTypesException.IExceptionType;
import xyz.zhouxy.plusone.commons.exception.IMultiTypesException;
/**
* InvalidInputException
@@ -35,7 +35,7 @@ import xyz.zhouxy.plusone.commons.exception.MultiTypesException;
*/
public final class InvalidInputException
extends RequestParamsException
implements MultiTypesException<InvalidInputException, InvalidInputException.Type> {
implements IMultiTypesException<InvalidInputException, InvalidInputException.Type, String> {
private static final long serialVersionUID = -28994090625082516L;
private final Type type;
@@ -109,7 +109,7 @@ public final class InvalidInputException
return this.type;
}
public enum Type implements ExceptionType<InvalidInputException> {
public enum Type implements IExceptionType<InvalidInputException, String> {
DEFAULT("00", "用户输入内容非法"),
CONTAINS_ILLEGAL_AND_MALICIOUS_LINKS("01", "包含非法恶意跳转链接"),
CONTAINS_ILLEGAL_WORDS("02", "包含违禁敏感词"),

View File

@@ -17,20 +17,21 @@
/**
* <h2>异常</h2>
*
* <h3>1. {@link MultiTypesException} - 多类型异常</h3>
* <h3>1. {@link IMultiTypesException} - 多类型异常</h3>
* <p>
* 异常在不同场景下被抛出,可以用不同的枚举值,表示不同的场景类型。
*
* <p>
* 异常实现 {@link MultiTypesException} 的 {@link MultiTypesException#getType} 方法,返回对应的场景类型。
* 异常实现 {@link IMultiTypesException} 的 {@link IMultiTypesException#getType} 方法,返回对应的场景类型。
*
* <p>
* 表示场景类型的枚举实现 {@link MultiTypesException.ExceptionType}其中的工厂方法用于创建对应类型的异常。
* 表示场景类型的枚举实现 {@link IMultiTypesException.IExceptionType}各个枚举值本身就是该场景的异常的工厂实例,
* 使用其中的工厂方法用于创建对应类型的异常。
*
* <pre>
* public final class LoginException
* extends RuntimeException
* implements MultiTypesException&lt;LoginException, LoginException.Type&gt; {
* implements IMultiTypesException&lt;LoginException, LoginException.Type, String&gt; {
* private static final long serialVersionUID = 881293090625085616L;
* private final Type type;
* private LoginException(&#64;Nonnull Type type, &#64;Nonnull String message) {
@@ -57,7 +58,7 @@
*
* // ...
*
* public enum Type implements ExceptionType&lt;LoginException&gt; {
* public enum Type implements IExceptionType&lt;LoginException, String&gt; {
* DEFAULT("00", "当前会话未登录"),
* NOT_TOKEN("10", "未提供token"),
* INVALID_TOKEN("20", "token无效"),

View File

@@ -33,7 +33,7 @@ import com.google.errorprone.annotations.Immutable;
import xyz.zhouxy.plusone.commons.annotation.ReaderMethod;
import xyz.zhouxy.plusone.commons.annotation.ValueObject;
import xyz.zhouxy.plusone.commons.regex.PatternConsts;
import xyz.zhouxy.plusone.commons.constant.PatternConsts;
import xyz.zhouxy.plusone.commons.util.StringTools;
/**
@@ -44,7 +44,7 @@ import xyz.zhouxy.plusone.commons.util.StringTools;
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @since 1.0.0
* @see xyz.zhouxy.plusone.commons.regex.PatternConsts#CHINESE_2ND_ID_CARD_NUMBER
* @see xyz.zhouxy.plusone.commons.constant.PatternConsts#CHINESE_2ND_ID_CARD_NUMBER
*/
@ValueObject
@Immutable

View File

@@ -1,38 +0,0 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.commons.regex;
import java.util.regex.Matcher;
public abstract class AbstractMatcher {
private final Matcher matcher;
AbstractMatcher(Matcher matcher) {
this.matcher = matcher;
}
public final Matcher matcher() {
return this.matcher;
}
public final boolean matches() {
return this.matcher.matches();
}
public final String getGroupValue(String groupName) {
return this.matcher.group(groupName);
}
}

View File

@@ -1,60 +0,0 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.commons.regex;
import java.util.regex.Matcher;
import xyz.zhouxy.plusone.commons.model.Gender;
public final class Chinese2ndIdCardNumberMatcher extends AbstractMatcher {
Chinese2ndIdCardNumberMatcher(Matcher matcher) {
super(matcher);
}
public final String getProvince() {
return getGroupValue("province");
}
public final String getCity() {
return getGroupValue("city");
}
public final String getCounty() {
return getGroupValue("county");
}
public final String getBirthDate() {
return getGroupValue("birthDate");
}
public final String getOrderCode() {
return getGroupValue("orderCode");
}
public final String getGenderCode() {
return getGroupValue("gender");
}
public final Gender getGender() {
final int genderCode = Integer.parseInt(getGenderCode());
return genderCode % 2 == 0 ? Gender.FEMALE : Gender.MALE;
}
public final String getCheckDigit() {
return getGroupValue("checkDigit");
}
}

View File

@@ -1,37 +0,0 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.commons.regex;
import java.util.regex.Matcher;
public final class LocalDateMatcher extends AbstractMatcher {
LocalDateMatcher(Matcher matcher) {
super(matcher);
}
public String getYear() {
return getGroupValue("yyyy");
}
public String getMonth() {
return getGroupValue("MM");
}
public String getDay() {
return getGroupValue("dd");
}
}

View File

@@ -1,38 +0,0 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.commons.regex;
import java.util.regex.Pattern;
public abstract class PatternInfo<T> {
private final String regex;
private final Pattern pattern;
PatternInfo(String regex, Pattern pattern) {
this.regex = regex;
this.pattern = pattern;
}
public final String regex() {
return this.regex;
}
public final Pattern pattern() {
return this.pattern;
}
public abstract T matcher(String input);
}

View File

@@ -1,114 +0,0 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.commons.regex;
import java.util.regex.Matcher;
public final class PatternInfos {
// @see RegexConsts#BASIC_ISO_DATE
public static final PatternInfo<LocalDateMatcher> BASIC_ISO_DATE = new PatternInfo<LocalDateMatcher>(
RegexConsts.BASIC_ISO_DATE,
PatternConsts.BASIC_ISO_DATE) {
@Override
public LocalDateMatcher matcher(String input) {
Matcher matcher = pattern().matcher(input);
return new LocalDateMatcher(matcher);
}
};
// @see RegexConsts#ISO_LOCAL_DATE
public static final PatternInfo<LocalDateMatcher> ISO_LOCAL_DATE = new PatternInfo<LocalDateMatcher>(
RegexConsts.ISO_LOCAL_DATE,
PatternConsts.ISO_LOCAL_DATE) {
@Override
public LocalDateMatcher matcher(String input) {
Matcher matcher = pattern().matcher(input);
return new LocalDateMatcher(matcher);
}
};
// @see RegexConsts#PASSWORD
public static final PatternInfo<Matcher> PASSWORD = new PatternInfo<Matcher>(
RegexConsts.PASSWORD,
PatternConsts.PASSWORD) {
@Override
public Matcher matcher(String input) {
return pattern().matcher(input);
}
};
// @see RegexConsts#CAPTCHA
public static final PatternInfo<Matcher> CAPTCHA = new PatternInfo<Matcher>(
RegexConsts.CAPTCHA,
PatternConsts.CAPTCHA) {
@Override
public Matcher matcher(String input) {
return pattern().matcher(input);
}
};
// @see RegexConsts#EMAIL
public static final PatternInfo<Matcher> EMAIL = new PatternInfo<Matcher>(
RegexConsts.EMAIL,
PatternConsts.EMAIL) {
@Override
public Matcher matcher(String input) {
return pattern().matcher(input);
}
};
public static final PatternInfo<Matcher> MOBILE_PHONE = new PatternInfo<Matcher>(
RegexConsts.MOBILE_PHONE,
PatternConsts.MOBILE_PHONE) {
@Override
public Matcher matcher(String input) {
return pattern().matcher(input);
}
};
public static final PatternInfo<Matcher> USERNAME = new PatternInfo<Matcher>(
RegexConsts.USERNAME,
PatternConsts.USERNAME) {
@Override
public Matcher matcher(String input) {
return pattern().matcher(input);
}
};
public static final PatternInfo<Matcher> NICKNAME = new PatternInfo<Matcher>(
RegexConsts.NICKNAME,
PatternConsts.NICKNAME) {
@Override
public Matcher matcher(String input) {
return pattern().matcher(input);
}
};
public static final PatternInfo<Chinese2ndIdCardNumberMatcher> CHINESE_2ND_ID_CARD_NUMBER = new PatternInfo<Chinese2ndIdCardNumberMatcher>(
RegexConsts.CHINESE_2ND_ID_CARD_NUMBER,
PatternConsts.CHINESE_2ND_ID_CARD_NUMBER) {
@Override
public Chinese2ndIdCardNumberMatcher matcher(String input) {
Matcher matcher = pattern().matcher(input);
return new Chinese2ndIdCardNumberMatcher(matcher);
}
};
private PatternInfos() {
throw new IllegalStateException("Utility class");
}
}

View File

@@ -26,7 +26,7 @@ import javax.annotation.Nullable;
import com.google.common.annotations.Beta;
import xyz.zhouxy.plusone.commons.regex.PatternConsts;
import xyz.zhouxy.plusone.commons.constant.PatternConsts;
/**
* StringTools

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
package xyz.zhouxy.plusone.commons.regex;
package xyz.zhouxy.plusone.commons.constant;
import static org.junit.jupiter.api.Assertions.*;

View File

@@ -31,7 +31,7 @@ import org.slf4j.LoggerFactory;
import xyz.zhouxy.plusone.commons.annotation.StaticFactoryMethod;
import xyz.zhouxy.plusone.commons.annotation.ValueObject;
import xyz.zhouxy.plusone.commons.regex.PatternConsts;
import xyz.zhouxy.plusone.commons.constant.PatternConsts;
import java.util.Arrays;
import java.util.Collections;

View File

@@ -1,259 +0,0 @@
/*
* Copyright 2024-2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.commons.regex;
import static org.junit.jupiter.api.Assertions.*;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.regex.Matcher;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import lombok.extern.slf4j.Slf4j;
import xyz.zhouxy.plusone.commons.model.Gender;
@Slf4j
public //
class PatternInfosTests {
// ================================
// #region - BASIC_ISO_DATE
// ================================
@Test
void testBasicIsoDate_ValidDate() {
LocalDateMatcher localDateMatcher = PatternInfos.BASIC_ISO_DATE.matcher("20241229");
Matcher matcher = localDateMatcher.matcher();
assertTrue(matcher.matches());
assertTrue(localDateMatcher.matches());
assertEquals("2024", localDateMatcher.getYear());
assertEquals("12", localDateMatcher.getMonth());
assertEquals("29", localDateMatcher.getDay());
}
@ParameterizedTest
@ValueSource(strings = {
"20231301", // InvalidMonth
"20230230", // InvalidDay
"20210229", // NonLeapYearFeb29
})
void testBasicIsoDate_InvalidDate_butMatches(String date) {
// 虽然日期有误,但这个正则无法判断。实际工作中,应使用日期时间 API。
LocalDateMatcher matcher = PatternInfos.BASIC_ISO_DATE.matcher(date);
assertTrue(matcher.matches());
}
@ParameterizedTest
@ValueSource(strings = {
"2023041", // TooShort
"99999999990415", // TooLong
"2023-04-15", // NonNumeric
})
void testBasicIsoDate_InvalidDate_Mismatches(String date) {
LocalDateMatcher matcher = PatternInfos.BASIC_ISO_DATE.matcher(date);
assertFalse(matcher.matches());
}
// ================================
// #endregion - BASIC_ISO_DATE
// ================================
// ================================
// #region - ISO_LOCAL_DATE
// ================================
@Test
void testIsoLocalDate_ValidDate() {
LocalDateMatcher matcher = PatternInfos.ISO_LOCAL_DATE.matcher("2024-12-29");
assertTrue(matcher.matches());
assertEquals("2024", matcher.getYear());
assertEquals("12", matcher.getMonth());
assertEquals("29", matcher.getDay());
// LeapYearFeb29()
assertTrue(PatternInfos.ISO_LOCAL_DATE.matcher("2020-02-29").matches());
// BoundaryMin()
assertTrue(PatternInfos.ISO_LOCAL_DATE.matcher("0000-01-01").matches());
// BoundaryMax()
assertTrue(PatternInfos.ISO_LOCAL_DATE.matcher("999999999-12-31").matches());
}
@ParameterizedTest
@ValueSource(strings = {
"2023-13-01", // InvalidMonth
"2023-02-30", // InvalidDay
"2021-02-29", // NonLeapYearFeb29
})
void testIsoLocalDate_InvalidDate_butMatches(String date) {
// 虽然日期有误,但这个正则无法判断。实际工作中,应使用日期时间 API。
LocalDateMatcher matcher = PatternInfos.ISO_LOCAL_DATE.matcher(date);
assertTrue(matcher.matches());
}
@ParameterizedTest
@ValueSource(strings = {
"2023-04-1", // TooShort
"9999999999-04-15", // TooLong
"20230415",
})
void testIsoLocalDate_InvalidDate_Mismatches(String date) {
LocalDateMatcher matcher = PatternInfos.ISO_LOCAL_DATE.matcher(date);
assertFalse(matcher.matches());
}
// ================================
// #endregion - ISO_LOCAL_DATE
// ================================
// ================================
// #region - PASSWORD
// ================================
@Test
void testPassword_ValidPassword_Matches() {
assertTrue(PatternInfos.PASSWORD.matcher("Abc123!@#").matches());
}
@Test
void testPassword_InvalidPassword_Mismatches() {
assertFalse(PatternInfos.PASSWORD.matcher("Abc123 !@#").matches()); // 带空格
assertFalse(PatternInfos.PASSWORD.matcher("Abc123!@# ").matches()); // 带空格
assertFalse(PatternInfos.PASSWORD.matcher(" Abc123!@#").matches()); // 带空格
assertFalse(PatternInfos.PASSWORD.matcher(" Abc123!@# ").matches()); // 带空格
assertFalse(PatternInfos.PASSWORD.matcher("77553366998844113322").matches()); // 纯数字
assertFalse(PatternInfos.PASSWORD.matcher("poiujhgbfdsazxcfvghj").matches()); // 纯小写字母
assertFalse(PatternInfos.PASSWORD.matcher("POIUJHGBFDSAZXCFVGHJ").matches()); // 纯大写字母
assertFalse(PatternInfos.PASSWORD.matcher("!#$%&'*\\+-/=?^`{|}~@()[]\",.;':").matches()); // 纯特殊字符
assertFalse(PatternInfos.PASSWORD.matcher("sdfrghbv525842582752").matches()); // 没有小写字母
assertFalse(PatternInfos.PASSWORD.matcher("SDFRGHBV525842582752").matches()); // 没有小写字母
assertFalse(PatternInfos.PASSWORD.matcher("sdfrghbvSDFRGHBV").matches()); // 没有数字
assertFalse(PatternInfos.PASSWORD.matcher("Abc1!").matches()); // 太短
assertFalse(PatternInfos.PASSWORD.matcher("Abc1!Abc1!Abc1!Abc1!Abc1!Abc1!Abc1!").matches()); // 太长
assertFalse(PatternInfos.PASSWORD.matcher("").matches());
assertFalse(PatternInfos.PASSWORD.matcher(" ").matches());
}
// ================================
// #endregion - PASSWORD
// ================================
// ================================
// #region - EMAIL
// ================================
@Test
public void testValidEmails() {
assertTrue(PatternInfos.EMAIL.matcher("test@example.com").matches());
assertTrue(PatternInfos.EMAIL.matcher("user.name+tag+sorting@example.com").matches());
assertTrue(PatternInfos.EMAIL.matcher("user@sub.example.com").matches());
assertTrue(PatternInfos.EMAIL.matcher("user@123.123.123.123").matches());
}
@Test
public void testInvalidEmails() {
assertFalse(PatternInfos.EMAIL.matcher(".username@example.com").matches());
assertFalse(PatternInfos.EMAIL.matcher("@missingusername.com").matches());
assertFalse(PatternInfos.EMAIL.matcher("plainaddress").matches());
assertFalse(PatternInfos.EMAIL.matcher("username..username@example.com").matches());
assertFalse(PatternInfos.EMAIL.matcher("username.@example.com").matches());
assertFalse(PatternInfos.EMAIL.matcher("username@-example.com").matches());
assertFalse(PatternInfos.EMAIL.matcher("username@-example.com").matches());
assertFalse(PatternInfos.EMAIL.matcher("username@.com.com").matches());
assertFalse(PatternInfos.EMAIL.matcher("username@.com.my").matches());
assertFalse(PatternInfos.EMAIL.matcher("username@.com").matches());
assertFalse(PatternInfos.EMAIL.matcher("username@com.").matches());
assertFalse(PatternInfos.EMAIL.matcher("username@com").matches());
assertFalse(PatternInfos.EMAIL.matcher("username@example..com").matches());
assertFalse(PatternInfos.EMAIL.matcher("username@example.com-").matches());
assertFalse(PatternInfos.EMAIL.matcher("username@example.com.").matches());
assertFalse(PatternInfos.EMAIL.matcher("username@example").matches());
}
// ================================
// #endregion - EMAIL
// ================================
// ================================
// #region - Chinese2ndIdCardNumber
// ================================
@ParameterizedTest
@ValueSource(strings = {
"44520019900101456X",
"44520019900101456x",
"445200199001014566",
})
void testChinese2ndIdCardNumber_ValidChinese2ndIdCardNumber(String value) {
Chinese2ndIdCardNumberMatcher chinese2ndIdCardNumberMatcher = PatternInfos.CHINESE_2ND_ID_CARD_NUMBER.matcher(value);
Matcher matcher = chinese2ndIdCardNumberMatcher.matcher();
assertTrue(matcher.matches());
assertEquals("44", chinese2ndIdCardNumberMatcher.getProvince());
assertEquals("4452", chinese2ndIdCardNumberMatcher.getCity());
assertEquals("445200", chinese2ndIdCardNumberMatcher.getCounty());
assertEquals("19900101", chinese2ndIdCardNumberMatcher.getBirthDate());
assertEquals("456", chinese2ndIdCardNumberMatcher.getOrderCode());
assertEquals("6", chinese2ndIdCardNumberMatcher.getGenderCode());
assertEquals(Gender.FEMALE, chinese2ndIdCardNumberMatcher.getGender());
String checkDigit = value.substring(value.length() - 1);
assertEquals(checkDigit, chinese2ndIdCardNumberMatcher.getCheckDigit());
}
@ParameterizedTest
@ValueSource(strings = {
"4452200199001014566",
"44520199001014566",
" ",
"",
})
void testChinese2ndIdCardNumber_InvalidChinese2ndIdCardNumber(String value) {
assertFalse(PatternInfos.CHINESE_2ND_ID_CARD_NUMBER.matcher(value).matches());
}
// ================================
// #endregion - Chinese2ndIdCardNumber
// ================================
// ================================
// #region - invoke constructor
// ================================
@Test
void test_constructor_isNotAccessible_ThrowsIllegalStateException() {
Constructor<?>[] constructors;
constructors = PatternInfos.class.getDeclaredConstructors();
Arrays.stream(constructors)
.forEach(constructor -> {
assertFalse(constructor.isAccessible());
constructor.setAccessible(true);
Throwable cause = assertThrows(Exception.class, constructor::newInstance)
.getCause();
assertInstanceOf(IllegalStateException.class, cause);
assertEquals("Utility class", cause.getMessage());
});
}
// ================================
// #endregion - invoke constructor
// ================================
}