70 Commits

Author SHA1 Message Date
829a7ed798 docs: 更新项目描述信息 2025-10-24 17:13:36 +08:00
f492d5d62e docs: 重命名文档文件名 2025-10-24 17:10:17 +08:00
159a7769dc docs: 修改文档目录 2025-10-24 17:02:57 +08:00
9ab92ce471 docs: 完善项目文档 [!9 (gitee)]
修改包描述(package-info.java)
修改 README.md
添加 docs 文件夹,包含各部分功能的介绍
2025-10-24 03:18:37 +00:00
8dfb3ff694 refactor!: 将 Ref 类从 base 包移动到 util 2025-10-23 16:59:04 +08:00
264717eb62 docs: 修复 UnifiedResponses 的 javadoc 错误 2025-10-23 16:26:11 +08:00
ba38175d93 refactor!: 优化 PagingAndSortingQueryParams (!7 @Gitee)
`PagingAndSortingQueryParams` 的构造器中必须传入一个 `PagingParamsBuilder`,
构建分页参数时使用此 `PagingParamsBuilder`。

只要子类确保同一场景下共用一个  `PagingParamsBuilder`  实例,就不会导致白名单重复校验。
2025-10-23 08:17:17 +00:00
b8c666a023 test: 使用 lombok 简化 TreeBuilder 的测试代码 2025-10-22 17:50:09 +08:00
255aaf182a feat: 新增 MapModifier 用于链式操作修改 Map 数据 (#71 @Gitea)
1. 添加 `MapModifier` 类,封装了一系列对 Map 数据的修改过程,如 `put`、`putIfAbsent`、`putAll`、`remove`、`clear` 等
2. 支持直接修改指定的 `Map`
3. 支持从 `Supplier` 中获取 `Map` 并进行修改
4. 提供了创建并初始化 unmodifiableMap 的方法
5. 增加了相应的单元测试用例

issue Close #67 @Gitea
2025-10-22 09:37:04 +08:00
468453781e chore: add lincese header 2025-10-21 16:32:29 +08:00
3b241de08c docs: 修改 UnifiedResponses 相关文档 (!5 @Gitee) 2025-10-21 07:16:24 +00:00
fb46def402 update NOTICE.
Signed-off-by: ZhouXY108 <luquanlion@outlook.com>
2025-10-21 05:25:00 +00:00
386ede6afd add NOTICE.
Signed-off-by: ZhouXY108 <luquanlion@outlook.com>
2025-10-21 05:23:42 +00:00
8ec61a84c9 build: 添加 MinIO 依赖版本管理 2025-10-20 23:16:03 +08:00
726a94a1a8 chore: 添加依赖管理注释 2025-10-20 23:15:24 +08:00
3b441e4575 docs: update README.md
Signed-off-by: ZhouXY108 <luquanlion@outlook.com>
2025-10-17 10:25:54 +00:00
4ed6edd9b6 feat(model): 添加 SemVer 表示语义版本号 (!4 @Gitee)
- feat: 添加 `SemVer` 表示语义版本号
- test: 完善 `SemVer` 的单元测试
2025-10-17 18:13:29 +08:00
3d297331c4 test: 减少 ZipTools 测试时处理的数据量 2025-10-17 10:16:52 +08:00
665de3cdf0 docs: 更新 IdWorker 的文档注释 (!3 @Gitee) 2025-10-14 13:12:04 +00:00
c2862203d4 feat: 新增 RandomTools#randomInt 用于生成指定区间内的随机整数 (!2 @Gitee) 2025-10-14 02:00:04 +00:00
fafb26fcf7 test: 减少测试时处理的数据量 2025-10-14 02:37:03 +08:00
a65af967cb feat: 新增 ZipTools 工具类 (#70 #Gitea)
新增 `ZipTools` 工具类提供最基础的数据压缩/解压方法
2025-10-13 21:21:15 +08:00
27e5650482 perf: 优化 AssertTools 代码 2025-10-13 17:36:47 +08:00
8106126e79 refactor!: 重构 PagingAndSortingQueryParams (#69 @Gitea)
将构建 `PagingParams` 的过程放在 `PagingParamsBuilder` 中。
当定义一个 `PagingAndSortingQueryParams` 的子类时,
该类应包含一个静态的 `PagingParamsBuilder` 单例对象,
使对 `sortableProperties` 的校验逻辑在类加载时执行。

原来实现方式是将校验 `sortableProperties` 的逻辑放在
`PagingAndSortingQueryParams` 的构造方法中,
每创建一个对象就得执行一次,造成不必要的浪费。
2025-10-12 01:33:18 +08:00
99d8f210c5 feat(dependencies): 添加 okhttp 和 okio 依赖 2025-10-09 10:41:24 +08:00
08432353fe refactor(exception)!: 修改 SysExceptionBizException
- 将 `SysException` 和 `BizException` 的构造方法设为 `protected`,供子类的构造方法调用
- 创建对应的工厂方法用于直接创建 `SysException` 和 `BizException` 实例
2025-10-01 22:56:56 +08:00
a7b1067ebb test: 完善 Numbers#sum(BigInteger...) 的单元测试 2025-09-03 21:40:51 +08:00
1dbfb36146 feat: Numbers 类新增 parseXxx 方法 (#65 @Gitea)
`Numbers` 类新增 `parseXxx` 方法用于将字符串转为对应类型的数字,当转换失败时返回默认值。默认值允许为 `null`。
2025-09-03 21:37:42 +08:00
1fc0b198c9 feat: 新增将日期区间转为日期时间区间的方法 (#64 @Gitea)
- 重载 `DateTimeTools#toDateTimeRange`
- 对新增的方法进行单元测试
- 简化单元测试代码
2025-09-03 21:08:51 +08:00
15e07901e6 perf: 简单优化代码 (#63 @Gitea) 2025-09-03 21:01:50 +08:00
8f451e7eb9 refactor(exception)!: 重构多场景异常相关代码 (#62 @Gitea)
- `IExceptionType` 不继承自 `IExceptionFactory`,具体表示异常场景的枚举,可按需实现这两个接口
- 简化 `IMultiTypesException` 接口定义,不与 `IExceptionType` 强制绑定
- 修改相关文档与描述

通过以上修改,使表示异常场景的枚举可以与异常类分开定义,使不同的异常可以复用同一套场景枚举。不强制作为单一异常的工厂,在被不同的异常复用时,可以更灵活地定义不同的工厂方法。
2025-09-03 20:41:23 +08:00
2b6f946759 perf: 优化 JodaTimeTools (#61 @Gitea)
- 优化 `JodaTimeTools`
- 完善 javadoc
2025-09-03 19:49:12 +08:00
ce9f3edfbc build: 保持开发分支的版本号为 SNAPSHOT 2025-08-01 11:31:55 +08:00
0f90756f44 release: 1.1.0-RC2 2025-07-31 11:14:10 +08:00
34a49d30ca chore: 更新代码仓库地址 (plusone/plusone-commons#60 @Gitea)
Co-authored-by: ZhouXY108 <luquanlion@outlook.com>
Co-committed-by: ZhouXY108 <luquanlion@outlook.com>
2025-07-25 10:27:10 +08:00
f4c3793aab chore: 修改 @author 信息 (#59@Gitea)
Co-authored-by: ZhouXY108 <luquanlion@outlook.com>
Co-committed-by: ZhouXY108 <luquanlion@outlook.com>
2025-07-25 10:23:26 +08:00
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
56079c29d8 refactor!: 将 ParsingFailureException 改为受检异常 2025-07-22 14:58:04 +08:00
f111b02c21 build: 将 plusone-dependencies 版本更新为项目版本
- 将 plusone-dependencies 的固定版本号替换为 ${project.version}
- 该修改确保了依赖版本与项目版本的一致性
2025-07-22 14:58:00 +08:00
56fd5f0a6a refactor!: 将 JodaTime 相关方法从 DateTimeTools 类中提取到新的 JodaTimeTools 类 2025-07-22 14:57:34 +08:00
e2e5f50162 refactor: AssertTools 类中的方法使用静态导入 2025-06-12 16:11:53 +08:00
8eac9054cd refactor(gson): 重构 JSR310TypeAdapters
- 抽象出 TemporalAccessorTypeAdapter 类,简化了 LocalDate、LocalDateTime、ZonedDateTime 和 Instant 类型适配器的实现
2025-06-09 17:55:25 +08:00
a55c712349 test: 使用 JSR310TypeAdapters 简化测试代码 2025-06-09 17:21:26 +08:00
0eda94a658 refactor(exception): 为异常类添加 serialVersionUID
为以下异常类添加 serialVersionUID 字段:
- ParsingFailureException
- BizException
- InvalidInputException
- RequestParamsException
- DataOperationResultException
- SysException
2025-06-09 17:05:10 +08:00
c816696c55 docs: 改正 ParsingFailureException 文档注释中的错误描述 2025-06-09 16:14:44 +08:00
8828b12c78 release: 1.1.0-RC1 2025-06-08 13:38:03 +08:00
89acbecc5a docs: 修改 javadoc 中的格式错误 2025-06-08 13:08:45 +08:00
336d99d4ba feat(gson): 添加 Gson 适配器以支持 JSR-310 中常用的类
Reviewed-on: http://zhouxy.xyz:3000/plusone/plusone-commons/pulls/57
2025-06-07 01:02:15 +08:00
0731bf2c22 refactor(gson): 合并多个 JSR-310 类型适配器到 JSR310TypeAdapters
- 将 InstantTypeAdapter、LocalDateTimeTypeAdapter、LocalDateTypeAdapter 和 ZonedDateTimeTypeAdapter 合并到 JSR310TypeAdapters 类中
- 更新包结构,移动适配器到 adapter 子包
- 新增相关包的 javadoc
2025-06-07 00:56:11 +08:00
2827f69aef feat(gson): 新增 InstantTypeAdapter 用于 Gson 序列化和反序列化 Instant
`InstantTypeAdapter` 用于 Gson 通过 `DateTimeFormatter#ISO_INSTANT` 序列化和反序列化 `Instant` 类型。
2025-06-07 00:22:04 +08:00
2e73ca5f6d feat(gson): 添加 Gson 适配器以支持 Java 8 日期时间 API
- 新增 `LocalDateTimeTypeAdapter`、`LocalDateTypeAdapter` 和 `ZonedDateTimeTypeAdapter`
- 将 Gson 作为可选依赖
2025-06-06 19:13:52 +08:00
1239a11cd7 refactor: 优化 UnifiedResponses 工厂方法的泛型定义
将不指定 data 的工厂方法也改成泛型方法,而不是返回 `UnifiedResponse<Void>`。
2025-06-06 11:40:20 +08:00
f8a2046d2d refactor!: 将 RegexToolsmatchesOne 方法重命名为 matchesAny 2025-06-04 17:12:29 +08:00
fb2036c038 build: 升级 logback 到 1.3.15
logback 1.3.x 是最后一个支持 JDK8 的版本。

如果使用 Spring Boot,建议使用 Spring Boot 绑定的版本,但是 Spring Boot 2.7.x 最高只支持 logback 1.2.x,所以不可避免使用的有漏洞的版本。
2025-05-28 21:14:27 +08:00
f9b4c3c58c feat: 新增 StringTools#toQuotedString 方法 2025-05-18 15:18:52 +08:00
3ca2ec3be0 build: 简化依赖声明 2025-05-14 10:42:06 +08:00
f83bb55fd6 refactor!: 重构 DataOperationResultException (#56)
删除 `DataOperationResultException` 多余的构造方法,仅提供两个构造方法。
创建 `DataOperationResultException` 实例时,必须将预计影响的行数
和实际影响的行数作为入参。(不兼容)

重构 `AssertTools` 中相关的断言方法。

Reviewed-on: http://zhouxy.xyz:3000/plusone/plusone-commons/pulls/56
Co-authored-by: ZhouXY108 <luquanlion@outlook.com>
Co-committed-by: ZhouXY108 <luquanlion@outlook.com>
2025-05-09 21:45:30 +08:00
e90e3dc1b4 fix(dependencies): 改正 jasypt 版本配置
Reviewed-on: http://zhouxy.xyz:3000/plusone/plusone-commons/pulls/55
Co-authored-by: ZhouXY108 <luquanlion@outlook.com>
Co-committed-by: ZhouXY108 <luquanlion@outlook.com>
2025-05-02 17:07:48 +08:00
b774d8c477 chore: 更新 Code Spell Checker 的配置
Reviewed-on: http://zhouxy.xyz:3000/plusone/plusone-commons/pulls/54
Co-authored-by: ZhouXY108 <luquanlion@outlook.com>
Co-committed-by: ZhouXY108 <luquanlion@outlook.com>
2025-05-02 15:27:32 +08:00
2a18a47ffe chore: 更新 guava
Reviewed-on: http://zhouxy.xyz:3000/plusone/plusone-commons/pulls/53
Co-authored-by: ZhouXY108 <luquanlion@outlook.com>
Co-committed-by: ZhouXY108 <luquanlion@outlook.com>
2025-05-02 15:09:06 +08:00
cb903a8cce docs: 修改 MultiTypesException 文档描述
Co-authored-by: ZhouXY108 <luquanlion@outlook.com>
Co-committed-by: ZhouXY108 <luquanlion@outlook.com>
2025-05-02 14:13:07 +08:00
030ed9ed3b refactor: 更改项目结构
创建父项目 plusone-parent,将 plusone-commons 放在 plusone-parent 下;
在 plusone-parent 下创建 plusone-dependencies,由 plusone-dependencies 管理可能用到的所有依赖。
2025-05-02 11:31:57 +08:00
5ce738bdfc docs: 完善 javadoc 2025-05-01 03:46:03 +08:00
97a4ae2279 perf: RegexTools 的缓存改用 guava cache 2025-05-01 02:15:23 +08:00
af66cd2380 feat: RegexTools 新增重载方法,当将字符串视为正则表达式入参时,允许传对应的 flags 2025-05-01 02:08:23 +08:00
3b519105bf refactor!: 删除 RegexTools 中以 String[] 作为多个正则表达式入参的方法
字符串无法代表一个正则表达式,还需考虑正则表达式的 flag(s),所以当使用多个正则表达式时,更推荐使用 `Pattern[]`。
2025-04-30 22:57:47 +08:00
b70e526509 docs: 修改段落问题
Signed-off-by: zhouxy108 <luquanlion@outlook.com>
2025-04-30 22:47:49 +08:00
a2781012be feat: 在 AssertTools 中新增 checkArgumentNotNull 系列方法 2025-04-30 22:44:29 +08:00
9e410029b1 refactor: 修改 AssertTools 中的参数名称 2025-04-30 22:17:18 +08:00
ee7213a687 refactor(util): ArrayTools 中的 isNullOrEmpty 重命名为 isEmpty
保持方法命名的一致性

BREAKING CHANGE: `ArrayTools#isNullOrEmpty` 重命名为 `ArrayTools#isEmpty`
2025-04-29 11:26:12 +08:00
136 changed files with 6198 additions and 2850 deletions

60
NOTICE Normal file
View File

@@ -0,0 +1,60 @@
Plusone Commons
Copyright 2022-present ZhouXY108
This product includes software developed at
Plusone Commons (http://gitea.zhouxy.xyz/plusone/plusone-commons).
===========================================================================
Third-party components and their licenses:
===========================================================================
This software contains code from the following third-party projects:
1. Apache Seata
- Component: IdWorker class implementation
- Source: org.apache.seata.common.util.IdWorker
- Origin: https://github.com/apache/incubator-seata/blob/2.x/common/src/main/java/org/apache/seata/common/util/IdWorker.java
- License: Apache License 2.0
- License URL: https://www.apache.org/licenses/LICENSE-2.0.txt
- Copyright: The Apache Software Foundation
===========================================================================
Dependencies and their licenses:
===========================================================================
The following dependencies are used in this project:
Required Dependencies:
- guava: Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
Optional Dependencies:
- gson: Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
- jsr305: Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
- joda-time: Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
Test Dependencies:
- commons-lang3: Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
- Logback: Eclipse Public License 1.0 (https://www.eclipse.org/org/documents/epl-1.0/EPL-1.0.txt) / LGPL 2.1 (https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html)
- Slf4j: MIT License (https://mit-license.org/)
- JUnit: Eclipse Public License 2.0 (https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt)
- lombok: MIT License (https://mit-license.org/)
- hutool: MulanPSL-2.0 (http://license.coscl.org.cn/MulanPSL2)
- MyBatis: Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
- h2: MPL 2.0 (https://www.mozilla.org/en-US/MPL/2.0/) / EPL 1.0 (https://www.eclipse.org/org/documents/epl-1.0/EPL-1.0.txt)
- Jackson: Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
===========================================================================
Apache License 2.0 Notice:
===========================================================================
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
http://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.

228
README.md
View File

@@ -1,219 +1,31 @@
## 一、annotation - 注解
### 1. StaticFactoryMethod
标识静态工厂方法。 *《Effective Java》***Item1** 建议考虑用静态工厂方法替换构造器, 因而考虑有一个注解可以标记一下静态工厂方法,以和其它方法进行区分
# Plusone Commons
## 1. 简介
Plusone Commons 是一个 Java 工具类库,提供了一系列实用的类和方法,用于简化开发
### 2. ReaderMethod 和 WriterMethod
分别标识读方法(如 getter或写方法如 setter
一开始是为了补充日常开发中guava 认为不需要,而我又用得上的工具,所以需要结合 guava 使用。后面也包含了一些从日常工作与学习中抽离出来可以通用的东西。
最早是写了一个集合类,为了方便判断使用读写锁时,哪些情况下使用读锁,哪些情况下使用写锁
Plusone Commons 的工具类不追求“大而全”,而是只提供相对需要的部分功能
### 3. UnsupportedOperation
标识该方法不被支持或没有实现,将抛出 `UnsupportedOperationException`。 为了方便在使用时,不需要点进源码,就能知道该方法没有实现。
> 未来一些不够“通用”的组件会迁移到更合适的模块中。
### 4. Virtual
Java 非 final 的实例方法,对应 C++/C# 中的虚方法,允许被子类覆写。 Virtual 注解旨在设计父类时,强调该方法父类虽然有默认实现,但子类可以根据自己的需要覆写
## 2. 安装
项目基于 OpenJDK 8 和 maven 构建
### 5. ValueObject
标记一个类,表示其作为值对象,区别于 Entity。
项目目前暂未发布到 maven 中央仓库,使用时需克隆代码到本地,并安装到本地仓库,然后才能在项目中引入依赖。
## 二、base - 基础组件
### 1. Ref
`Ref` 包装了一个值,表示对该值的应用。
## 3. 功能
详细功能说明请查阅文档:
灵感来自于 C# 的 ref 参数修饰符。C# 允许通过以下方式,将值返回给调用端:
```C#
void Method(ref int refArgument)
{
refArgument = refArgument + 44;
}
+ [文档地址](/plusone-commons/docs)
int number = 1;
Method(ref number);
Console.WriteLine(number); // Output: 45
```
`Ref` 使 Java 可以达到类似的效果,如:
```java
void method(Ref<Integer> refArgument) {
refArgument.transformValue(i -> i + 44);
}
## 4. 代码仓库
项目仓库一共建了三个:
Ref<Integer> number = Ref.of(1);
method(number);
System.out.println(number.getValue()); // Output: 45
```
当一个方法需要产生多个结果时,无法有多个返回值,可以使用 `Ref` 作为参数传入,方法内部修改 `Ref` 的值。 调用方在调用方法之后,使用 `getValue()` 获取结果。
```java
String method(Ref<Integer> intRefArgument, Ref<String> strRefArgument) {
intRefArgument.transformValue(i -> i + 44);
strRefArgument.setValue("Hello " + strRefArgument.getValue());
return "Return string";
}
+ [GitHub](https://github.com/ZhouXY108/plusone-commons)
+ [gitee](https://gitee.com/zhouxy108/plusone-commons)
+ [自建 Gitea 仓库](http://gitea.zhouxy.xyz/plusone/plusone-commons)
Ref<Integer> number = Ref.of(1);
Ref<String> str = Ref.of("Java");
String result = method(number, str);
System.out.println(number.getValue()); // Output: 45
System.out.println(str.getValue()); // Output: Hello Java
System.out.println(result); // Output: Return string
```
### 2. IWithCode
类似于枚举这样的类型,通常需要设置固定的码值表示对应的含义。 可实现 `IWithCode`、`IWithIntCode`、`IWithLongCode`,便于在需要的地方对这些接口的实现进行处理。
欢迎在 GitHub 和 gitee 上通过 issue 反馈使用过程中发现的问题和建议,也接受善意的 PR。
## 三、collection - 集合
### 1. CollectionTools
集合工具类
## 四、constant - 常量
### 1. 正则常量
`RegexConsts` 包含常见正则表达式;`PatternConsts` 包含对应的 `Pattern` 对象
## 五、exception - 异常
### 1. MultiTypesException - 多类型异常
异常在不同场景下被抛出,可以用不同的枚举值,表示不同的场景类型。
异常实现 `MultiTypesException` 的 `MultiTypesException#getType` 方法,返回对应的场景类型。
表示场景类型的枚举实现 `MultiTypesException.ExceptionType`,其中的工厂方法用于创建类型对象。
```java
public final class LoginException
extends RuntimeException
implements MultiTypesException<LoginException, LoginException.Type> {
private final Type type;
private LoginException(@Nonnull Type type, @Nonnull String message) {
super(message);
this.type = type;
}
private LoginException(@Nonnull Type type, @Nonnull Throwable cause) {
super(cause);
this.type = type;
}
private LoginException(@Nonnull Type type,
@Nonnull String message,
@Nonnull Throwable cause) {
super(message, cause);
this.type = type;
}
@Override
public @Nonnull Type getType() {
return this.type;
}
// ...
public enum Type implements ExceptionType {
DEFAULT("00", "当前会话未登录"),
NOT_TOKEN("10", "未提供token"),
INVALID_TOKEN("20", "token无效"),
TOKEN_TIMEOUT("30", "token已过期"),
BE_REPLACED("40", "token已被顶下线"),
KICK_OUT("50", "token已被踢下线"),
;
@Nonnull
private final String code;
@Nonnull
private final String defaultMessage;
Type(@Nonnull String code, @Nonnull String defaultMessage) {
this.code = code;
this.defaultMessage = defaultMessage;
}
@Override
public @Nonnull String getCode() {
return code;
}
@Override
public @Nonnull String getDefaultMessage() {
return defaultMessage;
}
@Override
public @Nonnull LoginException create() {
return new LoginException(this, this.defaultMessage);
}
@Override
public @Nonnull LoginException create(String message) {
return new LoginException(this, message);
}
@Override
public @Nonnull LoginException create(Throwable cause) {
return new LoginException(this, cause);
}
@Override
public @Nonnull LoginException create(String message, Throwable cause) {
return new LoginException(this, message, cause);
}
}
}
```
使用时,可以使用这种方式创建并抛出异常:
```java
throw LoginException.Type.TOKEN_TIMEOUT.create();
```
### 2. 业务异常
预设常见的业务异常。可继承 `BizException` 自定义业务异常。
### 3. 系统异常
预设常见的系统异常。可继承 `SysException` 自定义系统异常。
## 六、function - 函数式编程
### 1. PredicateTools
`PredicateTools` 用于 `Predicate` 的相关操作。
### 2. Functional interfaces
补充可能用得上的函数式接口:
| Group | FunctionalInterface | method |
| ------------- | -------------------- | -------------------------------- |
| UnaryOperator | BoolUnaryOperator | boolean applyAsBool (boolean) |
| UnaryOperator | CharUnaryOperator | char applyAsChar(char) |
| Throwing | Executable | void execute() throws E |
| Throwing | ThrowingConsumer | void accept(T) throws E |
| Throwing | ThrowingFunction | R apply(T) throws E |
| Throwing | ThrowingPredicate | boolean test(T) throws E |
| Throwing | ThrowingSupplier | T get() throws E |
| Optional | OptionalSupplier | Optional<T> get() throws E |
| Optional | ToOptionalBiFunction | Optional<R> apply(T,U) |
| Optional | ToOptionalFunction | Optional<R> apply(T) |
## 七、model - 业务建模组件
包含业务建模可能用到的性别、身份证等元素,也包含数据传输对象,如分页查询参数、响应结果、分页结果等。
### 数据传输对象
#### 1. 分页
分页组件由 `PagingAndSortingQueryParams` 作为入参, 因为分页必须伴随着排序,不然可能出现同一个对象重复出现在不同页,有的对象不被查询到的情况, 所以分页查询的入参必须包含排序条件。
用户可继承 `PagingAndSortingQueryParams` 构建自己的分页查询入参,需在构造器中调用 `PagingAndSortingQueryParams` 的构造器,传入一个 Map 作为白名单, key 是供前端指定用于排序的**属性名**value 是对应数据库中的**字段名**,只有在白名单中指定的属性名才允许作为排序条件。
`PagingAndSortingQueryParams` 包含三个主要的属性:
- **size** - 每页显示的记录数
- **pageNum** - 当前页码
- **orderBy** - 排序条件
其中 `orderBy` 是一个 List可以指定多个排序条件每个排序条件是一个字符串 格式为“**属性名-ASC**”或“**属性名-DESC**”,分别表示升序和降序。
比如前端传入的 orderBy 为 ["name-ASC","age-DESC"],意味着要按 name 进行升序name 相同的情况下则按 age 进行降序。
使用时调用 `PagingAndSortingQueryParams#buildPagingParams()` 方法获取分页参数 `PagingParams`。
分页结果可以存放到 `PageResult` 中,作为出参。
#### 2. UnifiedResponse
UnifiedResponse 对返回给前端的数据进行封装,包含 `code`、`message`、`data。`
可使用 `UnifiedResponses` 快速构建 `UnifiedResponse` 对象。 `UnifiedResponses` 默认的成功代码为 "2000000" 用户按测试类 `CustomUnifiedResponseFactoryTests` 中所示范的,继承 `UnifiedResponses` 实现自己的工厂类, 自定义 `SUCCESS_CODE` 和 `DEFAULT_SUCCESS_MSG` 和工厂方法。 见 [issue#22](http://zhouxy.xyz:3000/plusone/plusone-commons/issues/22)。
## 八、time - 时间 API
### 1. 季度
模仿 JDK 的 `java.time.Month` 和 `java.time.YearMonth` 实现 `Quarter`、`YearQuarter`,对季度进行建模。
## 九、util - 工具类
包含树构建器(`TreeBuilder`)、断言工具(`AssertTools`、ID 生成器(`IdGenerator`)及其它实用工具类。
## 5. 许可
项目使用 [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0) 开源,相关声明请参阅 `NOTICE` 文件。

View File

@@ -1,38 +1,45 @@
{
"version": "0.2",
"ignorePaths": [
"src/test"
"*/src/test"
],
"dictionaryDefinitions": [],
"dictionaries": [],
"words": [],
"ignoreWords": [
"words": [
"aliyun",
"baomidou",
"Batis",
"buildmetadata",
"Consolas",
"cspell",
"databind",
"datasource",
"dbutils",
"fasterxml",
"findbugs",
"gson",
"Hikari",
"hutool",
"jasypt",
"jbcrypt",
"Jdbc",
"joda",
"logback",
"mapstruct",
"mindrot",
"Multimap",
"Multiset",
"mybatis",
"Nonnull",
"NOSONAR",
"okhttp",
"okio",
"ooxml",
"overriden",
"plusone",
"println",
"projectlombok",
"querydsl",
"regexs",
"Seata",
"sonarlint",

View File

@@ -0,0 +1,8 @@
## 1. 注解
|注解|说明|
|--|--|
| **StaticFactoryMethod** | **标识静态工厂方法***《Effective Java》***Item1** 建议考虑用静态工厂方法替换构造器, 因而考虑有一个注解可以标记一下静态工厂方法,以和其它方法进行区分。|
| **ReaderMethod** / **WriterMethod** | **分别标识读方法(如 getter或写方法如 setter**<br>*最早是写了一个集合类,为了方便判断使用读写锁时,哪些情况下使用读锁,哪些情况下使用写锁。*|
| **UnsupportedOperation** | **标识该方法不被支持或没有实现**,将抛出 `UnsupportedOperationException`。 为了方便在使用时,不需要点进源码,就能知道该方法没有实现。|
| **Virtual** | Java 非 final 的实例方法,对应 C++/C# 中的虚方法,允许被子类覆写。 **Virtual 注解旨在设计父类时,强调该方法父类虽然有默认实现,但子类可以根据自己的需要覆写**。|
| **ValueObject** | 标记一个类,表示其作为**值对象**,区别于 Entity。|

View File

@@ -0,0 +1,39 @@
## 2. 集合
### 2.1. CollectionTools
简单的集合工具类,包含判空等常用方法。
### 2.2. MapModifier
Map 修改器。封装一系列对 Map 数据的修改操作,修改 Map 的数据。可以用于 Map 的数据初始化等操作。
```java
// MapModifier
MapModifier<String, Object> modifier = new MapModifier<String, Object>()
.putAll(commonProperties)
.put("username", "Ben")
.put("accountStatus", LOCKED);
// 从 Supplier 中获取 Map并修改数据
Map<String, Object> map = modifier.getAndModify(HashMap::new);
// 可以灵活使用不同 Map 类型的不同构造器
Map<String, Object> map = modifier.getAndModify(() -> new HashMap<>(8));
Map<String, Object> map = modifier.getAndModify(() -> new HashMap<>(anotherMap));
Map<String, Object> map = modifier.getAndModify(TreeMap::new);
Map<String, Object> map = modifier.getAndModify(ConcurrentHashMap::new);
// 修改已有的 Map
modifier.modify(map);
// 创建一个有初始化数据的不可变的 Map
Map<String, Object> map = modifier.getUnmodifiableMap();
// 链式调用创建并初始化数据
Map<String, Object> map = new MapModifier<String, Object>()
.putAll(commonProperties)
.put("username", "Ben")
.put("accountStatus", LOCKED)
.getAndModify(HashMap::new);
```

View File

@@ -0,0 +1,118 @@
## 3. 异常
### 3.1. 业务异常
|异常|描述|
|---|---|
|`BizException`|**业务异常**<br>*用户可继承 `BizException` 自定义业务异常。*|
`RequestParamsException`|**用户请求参数错误**|
|» » `InvalidInputException`|**用户输入内容非法**<br>00 - **DEFAULT** (用户输入内容非法)<br>01 - **CONTAINS_ILLEGAL_AND_MALICIOUS_LINKS** (包含非法恶意跳转链接)<br>02 - **CONTAINS_ILLEGAL_WORDS** (包含违禁敏感词)<br>03 - **PICTURE_CONTAINS_ILLEGAL_INFORMATION** (图片包含违禁信息)<br>04 - **INFRINGE_COPYRIGHT** (文件侵犯版权)|
### 3.2. 系统异常
|异常|描述|
|---|---|
|`SysException`|**系统异常**(表示技术异常)<br>*用户可继承 `SysException` 自定义系统异常。*|
`DataOperationResultException`|**数据操作的结果不符合预期**|
`NoAvailableMacFoundException`|**无法找到可访问的 Mac 地址**|
### 3.3. 其它异常
|异常|描述|
|---|---|
|`DataNotExistsException`|**数据不存在异常**|
|`ParsingFailureException`|**数据解析异常**<br>00 - **DEFAULT** (解析失败)<br>10 - **NUMBER_PARSING_FAILURE** (数字转换失败)<br>20 - **DATE_TIME_PARSING_FAILURE** (时间解析失败)<br>30 - **JSON_PARSING_FAILURE** (JSON 解析失败)<br>40 - **XML_PARSING_FAILURE** (XML 解析失败)|
### 3.4. 多类型异常
异常在不同场景下被抛出,可以用不同的枚举值,表示不同的场景类型。
异常实现 `IMultiTypesException``getType` 方法,返回对应的场景类型。
枚举实现 `IExceptionType` 接口,表示不同的异常场景。也可以实现 `IExceptionFactory`,用于创建对应场景的异常。
```java
public final class LoginException
extends RuntimeException
implements IMultiTypesException<LoginException.Type> {
private static final long serialVersionUID = 881293090625085616L;
private final Type type;
private LoginException(@Nonnull Type type, @Nonnull String message) {
super(message);
this.type = type;
}
private LoginException(@Nonnull Type type, @Nonnull Throwable cause) {
super(cause);
this.type = type;
}
private LoginException(@Nonnull Type type,
@Nonnull String message,
@Nonnull Throwable cause) {
super(message, cause);
this.type = type;
}
@Override
public @Nonnull Type getType() {
return this.type;
}
// ...
public enum Type implements IExceptionType<String>, IExceptionFactory<LoginException> {
DEFAULT("00", "当前会话未登录"),
NOT_TOKEN("10", "未提供token"),
INVALID_TOKEN("20", "token无效"),
TOKEN_TIMEOUT("30", "token已过期"),
BE_REPLACED("40", "token已被顶下线"),
KICK_OUT("50", "token已被踢下线"),
;
@Nonnull
private final String code;
@Nonnull
private final String defaultMessage;
Type(@Nonnull String code, @Nonnull String defaultMessage) {
this.code = code;
this.defaultMessage = defaultMessage;
}
@Override
public @Nonnull String getCode() {
return code;
}
@Override
public @Nonnull String getDefaultMessage() {
return defaultMessage;
}
@Override
public @Nonnull LoginException create() {
return new LoginException(this, this.defaultMessage);
}
@Override
public @Nonnull LoginException create(@Nonnull String message) {
return new LoginException(this, message);
}
@Override
public @Nonnull LoginException create(@Nonnull Throwable cause) {
return new LoginException(this, cause);
}
@Override
public @Nonnull LoginException create(@Nonnull String message, @Nonnull Throwable cause) {
return new LoginException(this, message, cause);
}
}
}
```
使用时,可以使用这种方式创建并抛出异常:
```java
throw LoginException.Type.TOKEN_TIMEOUT.create();
```

View File

@@ -0,0 +1,22 @@
## 4. - 函数式编程
### 4.1. PredicateTools
`PredicateTools` 用于 `Predicate` 的相关操作。
### 4.2. Functional interfaces
补充可能用得上的函数式接口:
| Group | FunctionalInterface | method |
| --- | --- | --- |
| UnaryOperator | **BoolUnaryOperator** | boolean applyAsBool (boolean) |
| UnaryOperator | **CharUnaryOperator** | char applyAsChar(char) |
| Throwing | **Executable** | void execute() throws E |
| Throwing | **ThrowingConsumer** | void accept(T) throws E |
| Throwing | **ThrowingFunction** | R apply(T) throws E |
| Throwing | **ThrowingPredicate** | boolean test(T) throws E |
| Throwing | **ThrowingSupplier** | T get() throws E |
| Optional | **OptionalSupplier** | Optional<T> get() throws E |
| Optional | **ToOptionalBiFunction** | Optional<R> apply(T,U) |
| Optional | **ToOptionalFunction** | Optional<R> apply(T) |

View File

@@ -0,0 +1,100 @@
## 5. 数据模型
### 5.1. 业务模型
| | 类型 | 描述 |
| --- | --- | --- |
| 接口 | `IDCardNumber` | 身份证号 |
| 值对象 | » `Chinese2ndGenIDCardNumber` | 中国二代居民身份证号 |
| 值对象 | `SemVer` | 语义化版本号 |
| 值对象(枚举)| `Gender` | 性别 |
| ~~值对象(抽象类)~~| ~~`ValidatableStringRecord`~~ | ~~带校验的字符串值对象~~ |
### 5.2. 数据传输对象
#### 5.2.1. 分页查询
`PagingAndSortingQueryParams` (分页排序查询参数)
`PagingAndSortingQueryParams` 包含三个主要的属性:
- **size** - 每页显示的记录数
- **pageNum** - 当前页码
- **orderBy** - 排序条件
分页必须伴随着排序,不然可能出现同一个对象重复出现在不同页,有的对象不被查询到的情况。
其中 `orderBy` 是一个 `List<String>`,可以指定多个排序条件,每个排序条件是一个字符串, 格式为“**属性名-ASC**”或“**属性名-DESC**”,分别表示升序和降序。
例如当 `orderBy` 的值为 `["name-ASC","age-DESC"]`,意味着要按 `name` 进行升序排列,`name` 相同的情况下则按 `age` 进行降序排列。
用户可继承 `PagingAndSortingQueryParams` 构建自己的分页查询入参,子类需在构造器中调用 `PagingAndSortingQueryParams` 的构造器,传入一个 `PagingParamsBuilder` 用于构建分页参数。同一场景下,复用一个 {@link PagingParamsBuilder} 实例即可。
构建 `PagingParamsBuilder` 时,需传入一个 `Map` 作为可排序字段的白名单,`key` 是供前端指定用于排序的**属性名**`value` 是对应数据库中的**字段名**,只有在白名单中指定的属性名才允许作为排序条件。
```java
@ToString(callSuper = true)
class AccountQueryParams extends PagingAndSortingQueryParams {
private static final Map<String, String> PROPERTY_COLUMN_MAP = ImmutableMap.<String, String>builder()
.put("id", "id")
.put("username", "username")
.build();
private static final PagingParamsBuilder PAGING_PARAMS_BUILDER = PagingAndSortingQueryParams
.pagingParamsBuilder(20, 100, PROPERTY_COLUMN_MAP);
public AccountQueryParams() {
super(PAGING_PARAMS_BUILDER);
}
private @Getter @Setter Long id;
private @Getter @Setter String username;
private @Getter @Setter String email;
private @Getter @Setter Integer status;
}
```
使用时调用 `PagingAndSortingQueryParams#buildPagingParams()` 方法获取分页参数 `PagingParams`。分页结果可以存放到 `PageResult` 中,作为出参。
```java
public PageResult<AccountVO> queryPage(AccountQueryParams params) {
// 获取分页参数
PagingParams pagingParams = params.buildPagingParams();
// 从 params 获取字段查询条件,从 pagingParams 获取分页条件,查询一页数据
List<AccountVO> list = accountQueries.queryAccountList(params, pagingParams);
// 查询总记录数
long count = accountQueries.countAccount(params);
// 返回分页结果
return PageResult.of(list, count);
}
```
#### 5.2.2. UnifiedResponse
`UnifiedResponse` 对返回给前端的数据进行封装,包含 `code``message``data`
`UnifiedResponses``UnifiedResponse` 的工厂类。用于快速构建 `UnifiedResponse` 对象,默认的成功代码为 `2000000`
用户可以继承 `UnifiedResponses` 实现自己的工厂类,自定义 SUCCESS_CODE 和 DEFAULT_SUCCESS_MSG以及工厂方法。如下所示
```java
// 自定义工厂类
public static class CustomUnifiedResponses extends UnifiedResponses {
public static final String SUCCESS_CODE = "000";
public static final String DEFAULT_SUCCESS_MSG = "成功";
public static <T> UnifiedResponse<T> success() {
return of(SUCCESS_CODE, DEFAULT_SUCCESS_MSG);
}
public static <T> UnifiedResponse<T> success(@Nullable String message) {
return of(SUCCESS_CODE, message);
}
public static <T> UnifiedResponse<T> success(@Nullable String message, @Nullable T data) {
return of(SUCCESS_CODE, message, data);
}
private CustomUnifiedResponses() {
super();
}
}
// 使用自定义工厂类
CustomUnifiedResponses.success("查询成功", userList); // 状态码为 000
```
> 见 [issue#22 @Gitea](http://gitea.zhouxy.xyz/plusone/plusone-commons/issues/22)

View File

@@ -0,0 +1,24 @@
## 6. 时间 API
### 6.1. 季度
模仿 JDK 的 `java.time.Month``java.time.YearMonth` 实现 `xyz.zhouxy.plusone.commons.time.Quarter``xyz.zhouxy.plusone.commons.timeYearQuarter`,对季度进行建模。
*这两个类的代码修改后,也提交给了 **hutool**。见 gitee
上的 [pr#1324](https://gitee.com/chinabugotech/hutool/pulls/1324)*。
### 6.2. DateTimeTools
`xyz.zhouxy.plusone.commons.util.DateTimeTools` 提供了包含 Java 旧的时间 API 和 `java.time` API 在内的日期时间的常用操作。
### 6.3. JodaTimeTools
`xyz.zhouxy.plusone.commons.util.JodaTimeTools` 提供了 JodaTime 和 `java.time` API 相互转换的工具方法:
- `toJodaInstant`
- `toJavaInstant`
- `toJodaDateTime`
- `toZonedDateTime`
- `toJodaLocalDateTime`
- `toJavaLocalDateTime`
- `toJavaZone`
- `toJodaZone`

View File

@@ -0,0 +1,275 @@
## 7. 工具类
### 7.1. 数组工具ArrayTools
| 方法 | 描述 |
| --- | --- |
| `isEmpty` | 判断数组是否为空 |
| `isNotEmpty` | 判断数组是否不为空 |
| `isAllElementsNotNull` | 判断数组中所有元素是否不为空 |
| `concat` | 拼接数组 |
| `repeat` | 重复数组中的元素 |
| `fill` | 填充数组 |
| `indexOf` | 获取元素在数组中的索引 |
| `lastIndexOf` | 获取元素最后出现在数组中的索引 |
| `contains` | 判断数组中是否包含某个元素 |
### 7.2. 断言工具AssertTools
`AssertTools` 不封装过多判断逻辑,鼓励充分使用项目中的工具类对数据进行判断:
```java
AssertTools.checkArgument(StringUtils.hasText(str), "The argument cannot be blank.");
AssertTools.checkState(ArrayUtils.isNotEmpty(result), "The result cannot be empty.");
AssertTools.checkCondition(!CollectionUtils.isEmpty(roles),
() -> new InvalidInputException("The roles cannot be empty."));
AssertTools.checkCondition(RegexTools.matches(email, PatternConsts.EMAIL),
"must be a well-formed email address");
```
### 7.3. 枚举工具
#### ~~7.3.1 枚举类Enumeration已废弃~~
~~`Enumeration` 的实现来自于 .net 社区。因为 C# 本身的枚举不带行为,所以继承自 `Enumeration` 类,以实现带行为的枚举常量。~~
**~~但 Java 的枚举可以带行为,故大多数情况下不需要这种设计。~~**
#### 7.3.2 Enum 工具类EnumTools
用于枚举的 ordinal 和枚举值的转换等操作。
由于不推荐使用枚举的 ordinal**故大多数方法已废弃**。更推荐的实现是枚举实现 `IWithCode` 之类的接口,在枚举中提供枚举值和枚举码的转换。
### 7.4. ID 生成器
#### 7.4.1. ID 生成器IdGenerator
- 提供了 `UUID` 相关的方法
| 方法 | 描述 |
| --- | --- |
| newUuid | 获取新的 `UUID` |
| uuidString | 获取新的 UUID 字符串 |
| simpleUuidString | 获取新的 UUID 字符串(无连接符) |
| toSimpleString | 将 `UUID` 转换为无连接符的字符串 |
- 使用 `IdWorker` *(来自 **Seata** 的雪花算法的变种)* 生成分布式唯一 ID
#### 7.4.2. IdWorker
来自 [Apache Seata](https://seata.apache.org/) 的 [`org.apache.seata.common.util.IdWorker`](https://github.com/apache/incubator-seata/blob/2.x/common/src/main/java/org/apache/seata/common/util/IdWorker.java),是雪花算法的变种。
详细介绍参考以下文章:
- [Seata基于改良版雪花算法的分布式UUID生成器分析](https://seata.apache.org/zh-cn/blog/seata-analysis-UUID-generator)
- [关于新版雪花算法的答疑](https://seata.apache.org/zh-cn/blog/seata-snowflake-explain)
- [在开源项目中看到一个改良版的雪花算法,现在它是你的了。](https://juejin.cn/post/7264387737276203065)
- [关于若干读者,阅读“改良版雪花算法”后提出的几个共性问题的回复。](https://juejin.cn/post/7265516484029743138)
#### 7.4.3. SnowflakeIdGenerator
`SnowflakeIdGenerator` 是原版的雪花算法的实现
### 7.5. 树构建器TreeBuilder
`TreeBuilder` 是一个树构建器,用于将列表数据构建为树结构。
`TreeBuilder` 构造器的入参:
- **identityGetter**: 从节点中获取其标识的逻辑
- **parentIdentityGetter**: 获取父节点标识的逻辑
- **addChild**: 添加子节点的逻辑
- **defaultComparator**: 默认的 Comparator用于排序
> **注意:`TreeBuilder` 的 `buildTree` 方法,会直接更改列表中的节点。设计初衷是将查询到的列表,构建成为树结构之后直接返回给前端,如果需要,请在调用之前做深拷贝,然后再将深拷贝的结果作为入参传入。**
以下示例演示 `TreeBuilder` 的使用:
#### 7.5.1. 处理相对复杂的 entity
假设有如下的实体类:
```java
@AllArgsConstructor(access = AccessLevel.PROTECTED)
@EqualsAndHashCode
@ToString
class Menu implements Serializable {
protected final @Getter String parentMenuCode;
protected final @Getter String menuCode;
protected final @Getter String title;
protected final @Getter int orderNum;
private static final long serialVersionUID = 20240917181424L;
}
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
class MenuItem extends Menu {
private final @Getter String url;
private MenuItem(String parentMenuCode, String menuCode, String title, String url, int orderNum) {
super(parentMenuCode, menuCode, title, orderNum);
this.url = url;
}
static MenuItem of(String parentMenuCode, String menuCode, String title, String url, int orderNum) {
return new MenuItem(parentMenuCode, menuCode, title, url, orderNum);
}
static MenuItem of(String menuCode, String title, String url, int orderNum) {
return new MenuItem(null, menuCode, title, url, orderNum);
}
private static final long serialVersionUID = 20240917181910L;
}
@ToString(callSuper = true)
class MenuList extends Menu {
private List<Menu> children;
private MenuList(String parentMenuCode, String menuCode, String title, int orderNum) {
super(parentMenuCode, menuCode, title, orderNum);
}
static MenuList of(String parentMenuCode, String menuCode, String title, int orderNum) {
return new MenuList(parentMenuCode, menuCode, title, orderNum);
}
static MenuList of(String menuCode, String title, int orderNum) {
return new MenuList(null, menuCode, title, orderNum);
}
@SuppressWarnings("unused")
static MenuList of(String menuCode, String title, Iterable<Menu> children, int orderNum) {
return of(null, menuCode, title, children, orderNum);
}
static MenuList of(String parentMenuCode, String menuCode, String title, Iterable<Menu> children,
int orderNum) {
final MenuList instance = of(parentMenuCode, menuCode, title, orderNum);
children.forEach(instance::addChild);
return instance;
}
public void addChild(Menu child) {
if (this.children == null) {
this.children = Lists.newArrayList();
}
this.children.add(child);
}
private static final long serialVersionUID = 20240917181917L;
}
```
其中,`Menu` 表示菜单节点,其子类 `MenuItem` 表示菜单项,在树中作为叶子节点,另一子类 `MenuList` 表示菜单列表,其子菜单放在 `children` 字段中。`MenuList` 提供了 `addChild` 方法用于将子菜单添加到 `children` 中。
使用以下方式构建并使用 `TreeBuilder`
```java
// 创建 TreeBuilder
TreeBuilder<Menu, MenuList, String> treeBuilder = new TreeBuilder<>(
// getMenuCode 方法获取节点标识
Menu::getMenuCode,
// getParentMenuCode 方法获取父节点标识,如果父节点不存在,返回 Optional.empty()
menu -> Optional.ofNullable(menu.getParentMenuCode()),
// addChild 方法用于将子节点添加到父节点的 children 中
MenuList::addChild,
// 默认的 Comparator使用 orderNum 进行排序
Comparator.comparing(Menu::getOrderNum));
// 需要的话进行深拷贝
List<Menu> clonedMenus = menus.stream().map(ObjectUtil::clone).collect(Collectors.toList());
// 按照创建时设置的逻辑,构建树结构
List<Menu> result = treeBuilder.buildTree(clonedMenus);
```
#### 7.5.2. 处理 POJO
`TreeBuilder` 也可以处理 POJO只需要自定义 `TreeBuilder` 所需的入参即可。
```java
// POJO
@Data
class Menu implements Serializable {
private final String parentMenuCode;
private final String menuCode;
private final String title;
private final int orderNum;
private final String url;
private List<Menu> children;
private static final long serialVersionUID = 1298482252210272617L;
}
```
使用以下方式构建并使用 `TreeBuilder`
```java
// 创建 TreeBuilder
TreeBuilder<Menu, MenuList, String> treeBuilder = new TreeBuilder<>(
// getMenuCode 方法获取节点标识
Menu::getMenuCode,
// getParentMenuCode 方法获取父节点标识,如果父节点不存在,返回 Optional.empty()
menu -> Optional.ofNullable(menu.getParentMenuCode()),
// 自定义 addChild 逻辑
(menuList, child) -> {
List<Menu> children = menuList.getChildren();
if (children == null) {
children = Lists.newArrayList();
menuList.setChildren(children);
}
children.add(child);
},
// 默认的 Comparator使用 orderNum 进行排序
Comparator.comparing(Menu::getOrderNum));
// 按照创建时设置的逻辑,构建树结构
List<Menu> result = treeBuilder.buildTree(clonedMenus);
```
### 7.6. Ref
`Ref` 包装了一个值,表示对该值的应用。
C# 中允许通过 ref 参数修饰符,将值返回给调用端:
```csharp
void Method(ref int refArgument)
{
refArgument = refArgument + 44;
}
int number = 1;
Method(ref number);
Console.WriteLine(number); // Output: 45
```
`Ref` 使 Java 可以达到类似的效果,如:
```java
void method(Ref<Integer> refArgument) {
refArgument.transformValue(i -> i + 44);
}
Ref<Integer> number = Ref.of(1);
method(number);
System.out.println(number.getValue()); // Output: 45
```
当一个方法需要产生多个结果时,无法有多个返回值,可以使用 `Ref` 作为参数传入,方法内部修改 `Ref` 的值。 调用方在调用方法之后,使用 `getValue()` 获取结果。
```java
String method(Ref<Integer> intRefArgument, Ref<String> strRefArgument) {
intRefArgument.transformValue(i -> i + 44);
strRefArgument.setValue("Hello " + strRefArgument.getValue());
return "Return string";
}
Ref<Integer> number = Ref.of(1);
Ref<String> str = Ref.of("Java");
String result = method(number, str);
System.out.println(number.getValue()); // Output: 45
System.out.println(str.getValue()); // Output: Hello Java
System.out.println(result); // Output: Return string
```
### 7.7 其它工具类
- **`BigDecimals`**: BigDecimal 工具
- **`Numbers`**: 数字工具
- **`OptionalTools`**: Optional 工具
- **`RandomTools`**: 随机工具
- **`RegexTools`**: 正则工具
- **`StringTools`**: 字符串工具
- **`ZipTools`**: zip 工具

View File

@@ -0,0 +1,9 @@
## 8. 其它内容
### 8.1. IWithCode
对于类似枚举这样的类型,通常需要设置固定的码值表示对应的含义。 可实现 `IWithCode``IWithIntCode``IWithLongCode`,便于在需要的地方对这些接口的实现进行处理。
### 8.2. 正则常量
`RegexConsts` 包含常见正则表达式;`PatternConsts` 包含对应的 `Pattern` 对象

123
plusone-commons/pom.xml Normal file
View File

@@ -0,0 +1,123 @@
<?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">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>xyz.zhouxy.plusone</groupId>
<artifactId>plusone-parent</artifactId>
<version>1.1.0-SNAPSHOT</version>
</parent>
<artifactId>plusone-commons</artifactId>
<description>
Plusone Commons 是一个 Java 工具类库,提供了一系列实用的类和方法,用于简化开发。结合 guava 使用。
</description>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>xyz.zhouxy.plusone</groupId>
<artifactId>plusone-dependencies</artifactId>
<version>${project.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- ========== Compile Dependencies ========== -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<optional>true</optional>
</dependency>
<!-- Gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<optional>true</optional>
</dependency>
<!-- ========== Test Dependencies ========== -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
<scope>test</scope>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<!-- Jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@@ -27,7 +27,7 @@ import java.lang.annotation.Target;
* <p>
* 标识方法是读方法 getter
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
* @see WriterMethod
*/

View File

@@ -26,7 +26,7 @@ import java.lang.annotation.Target;
*
* <p>标识方法为静态工厂方法
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
@Target(ElementType.METHOD)

View File

@@ -27,7 +27,7 @@ import java.lang.annotation.Documented;
*
* <p>标识方法为不支持的操作该方法将抛出 {@link UnsupportedOperationException}
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @version 1.0
* @since 1.0.0
* @see UnsupportedOperationException

View File

@@ -25,7 +25,7 @@ import java.lang.annotation.Target;
/**
* ValueObject - 值对象
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
@Inherited

View File

@@ -25,7 +25,7 @@ import java.lang.annotation.Target;
* 标识该方法是虚方法
* <p>该注解用于提醒强调父类虽然有默认实现但子类可以根据自己的需要覆写</p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
@Target(ElementType.METHOD)

View File

@@ -27,7 +27,7 @@ import java.lang.annotation.Target;
* <p>
* 标识方法是写方法 setter
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
* @see ReaderMethod
*/

View File

@@ -0,0 +1,22 @@
/*
* 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.
*/
/**
* 注解
*
* @author ZhouXY108 <luquanlion@outlook.com>
*/
package xyz.zhouxy.plusone.commons.annotation;

View File

@@ -26,7 +26,7 @@ import javax.annotation.Nullable;
* 用于像自定义异常等需要带有 {@code code} 字段的类
* 方便其它地方的程序判断该类的是否实现了此接口以此获取其实例的 {@code code} 字段的值
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
public interface IWithCode<T> {

View File

@@ -25,7 +25,7 @@ import javax.annotation.Nullable;
* 用于像自定义异常等需要带有 {@code code} 字段的类
* 方便其它地方的程序判断该类的是否实现了此接口以此获取其实例的 {@code code} 字段的值
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
public interface IWithIntCode {

View File

@@ -25,7 +25,7 @@ import javax.annotation.Nullable;
* 用于像自定义异常等需要带有 {@code code} 字段的类
* 方便其它地方的程序判断该类的是否实现了此接口以此获取其实例的 {@code code} 字段的值
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
public interface IWithLongCode {

View File

@@ -0,0 +1,28 @@
/*
* 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.
*/
/**
* 基础内容
*
* @author ZhouXY108 <luquanlion@outlook.com>
*/
@CheckReturnValue
@ParametersAreNonnullByDefault
package xyz.zhouxy.plusone.commons.base;
import javax.annotation.ParametersAreNonnullByDefault;
import javax.annotation.CheckReturnValue;

View File

@@ -33,7 +33,7 @@ import com.google.common.collect.Table;
/**
* 集合工具类
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
public class CollectionTools {

View File

@@ -0,0 +1,254 @@
/*
* 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.collection;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkArgumentNotNull;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.annotations.Beta;
/**
* Map 修改器
*
* <p>
* 封装一系列对 Map 数据的修改操作,修改 Map 的数据。可以用于 Map 的数据初始化等操作。
*
* <pre>
* // MapModifier
* MapModifier&lt;String, Object&gt; modifier = new MapModifier&lt;String, Object&gt;()
* .putAll(commonProperties)
* .put("username", "Ben")
* .put("accountStatus", LOCKED);
*
* // 从 Supplier 中获取 Map并修改数据
* Map&lt;String, Object&gt; map = modifier.getAndModify(HashMap::new);
*
* // 可以灵活使用不同 Map 类型的不同构造器
* Map&lt;String, Object&gt; map = modifier.getAndModify(() -&gt; new HashMap&lt;&gt;(8));
* Map&lt;String, Object&gt; map = modifier.getAndModify(() -&gt; new HashMap&lt;&gt;(anotherMap));
* Map&lt;String, Object&gt; map = modifier.getAndModify(TreeMap::new);
* Map&lt;String, Object&gt; map = modifier.getAndModify(ConcurrentHashMap::new);
*
* // 修改已有的 Map
* modifier.modify(map);
*
* // 创建一个有初始化数据的不可变的 Map
* Map&lt;String, Object&gt; map = modifier.getUnmodifiableMap();
*
* // 链式调用创建并初始化数据
* Map&lt;String, Object&gt; map = new MapModifier&lt;String, Object&gt;()
* .putAll(commonProperties)
* .put("username", "Ben")
* .put("accountStatus", LOCKED)
* .getAndModify(HashMap::new);
* </pre>
*
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.1.0
*/
@Beta
public class MapModifier<K, V> {
@Nonnull
private Consumer<Map<K, V>> operators;
/**
* 创建一个空的 MapModifier
*/
public MapModifier() {
this.operators = m -> {
// do nothing
};
}
/**
* 添加一个键值对。
*
* <p>
* <b>注意:键值对是否允许为 {@code null},由最终作用的 {@link Map} 类型决定。</b>
*
* @param key 要添加的 {@code key}
* @param value 要添加的 {@code value}
* @return MapModifier
*/
public MapModifier<K, V> put(@Nullable K key, @Nullable V value) {
return addOperationInternal(map -> map.put(key, value));
}
/**
* 添加一个键值对,如果 key 已经存在,则不添加。
*
* <p>
* <b>注意:键值对是否允许为 {@code null},由最终作用的 {@link Map} 类型决定。</b>
*
* @param key 要添加的 {@code key}
* @param value 要添加的 {@code value}
* @return MapModifier
*/
public MapModifier<K, V> putIfAbsent(@Nullable K key, @Nullable V value) {
return addOperationInternal(map -> map.putIfAbsent(key, value));
}
/**
* 添加多个键值对。
*
* <p>
* <b>注意:键值对是否允许为 {@code null},由最终作用的 {@link Map} 类型决定。</b>
*
* @param otherMap 要添加的键值对集合。
* 如果为 {@code null},则什么都不做。
*
* @return MapModifier
*/
public MapModifier<K, V> putAll(@Nullable Map<? extends K, ? extends V> otherMap) {
if (otherMap == null || otherMap.isEmpty()) {
return this;
}
return addOperationInternal(map -> map.putAll(otherMap));
}
/**
* 添加多个键值对。
*
* <p>
* <b>注意:键值对是否允许为 {@code null},由最终作用的 {@link Map} 类型决定。</b>
*
* @param entries 要添加的键值对集合
* @return MapModifier
*/
@SafeVarargs
public final MapModifier<K, V> putAll(Map.Entry<? extends K, ? extends V>... entries) {
if (entries.length == 0) {
return this;
}
return addOperationInternal(map -> {
for (Map.Entry<? extends K, ? extends V> entry : entries) {
map.put(entry.getKey(), entry.getValue());
}
});
}
/**
* 当 {@code key} 不存在时,计算对应的值,并添加到 {@code map} 中。
*
* <p>
* 调用 {@link Map#computeIfAbsent(Object, Function)}。
*
* <p>
* <b>注意:键值对是否允许为 {@code null},由最终作用的 {@link Map} 类型决定。</b>
*
* @param key 要添加的 {@code key}
* @param mappingFunction 计算 {@code key} 对应的值
* @return MapModifier
*/
public MapModifier<K, V> computeIfAbsent(K key,
Function<? super K, ? extends V> mappingFunction) {
return addOperationInternal(map -> map.computeIfAbsent(key, mappingFunction));
}
/**
* 当 {@code key} 存在时,计算对应的值,并添加到 {@code map} 中。
*
* <p>
* 调用 {@link Map#computeIfPresent(Object, BiFunction)}。
*
* <p>
* <b>注意:键值对是否允许为 {@code null},由最终作用的 {@link Map} 类型决定。</b>
*
* @param key 要添加的 {@code key}
* @param remappingFunction 计算 {@code key} 对应的值
* @return MapModifier
*/
public MapModifier<K, V> computeIfPresent(K key,
BiFunction<? super K, ? super V, ? extends V> remappingFunction) {
return addOperationInternal(map -> map.computeIfPresent(key, remappingFunction));
}
/**
* 删除 {@code key}。
*
* <p>
* <b>注意key 是否允许为 {@code null},由最终作用的 {@link Map} 类型决定。</b>
*
* @param key 要删除的 {@code key}
* @return MapModifier
*/
public MapModifier<K, V> remove(K key) {
return addOperationInternal(map -> map.remove(key));
}
/**
* 清空 {@code map}
*
* @return MapModifier
*/
public MapModifier<K, V> clear() {
return addOperationInternal(Map::clear);
}
/**
* 修改 {@code map}
*
* @param map 要修改的 {@code map}
* @return 修改后的 {@code map}。当入参是 {@code null} 时,返回 {@code null}。
*/
public <T extends Map<K, V>> void modify(@Nullable T map) {
if (map != null) {
this.operators.accept(map);
}
}
/**
* 修改 {@code map}
*
* @param mapSupplier {@code map} 的 {@link Supplier}
* @return 修改后的 {@code map}。
* 当从 {@code mapSupplier} 获取的 {@code map} 为 {@code null} 时,返回 {@code null}。
*/
@CheckForNull
public <T extends Map<K, V>> T getAndModify(Supplier<T> mapSupplier) {
checkArgumentNotNull(mapSupplier, "The map supplier cannot be null.");
T map = mapSupplier.get();
modify(map);
return map;
}
/**
* 创建一个有初始化数据的不可变的 {@code Map}
*
* @return 不可变的 {@code Map}
*/
public Map<K, V> getUnmodifiableMap() {
return Collections.unmodifiableMap(getAndModify(HashMap::new));
}
private MapModifier<K, V> addOperationInternal(Consumer<Map<K, V>> operator) {
this.operators = this.operators.andThen(operator);
return this;
}
}

View File

@@ -15,14 +15,9 @@
*/
/**
* <h2>集合<h2>
* 集合相关工具
*
* <h3>
* 1. {@link CollectionTools}
* </h3>
* 集合工具类
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
@ParametersAreNonnullByDefault
package xyz.zhouxy.plusone.commons.collection;

View File

@@ -21,7 +21,7 @@ import java.util.regex.Pattern;
/**
* 正则表达式常量
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @see RegexConsts
* @see xyz.zhouxy.plusone.commons.util.RegexTools
*/
@@ -31,7 +31,7 @@ public final class PatternConsts {
* yyyyMMdd
*
* @see RegexConsts#BASIC_ISO_DATE
* </p>
*
*/
public static final Pattern BASIC_ISO_DATE = Pattern.compile(RegexConsts.BASIC_ISO_DATE);

View File

@@ -19,7 +19,7 @@ package xyz.zhouxy.plusone.commons.constant;
/**
* 正则表达式常量
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @see PatternConsts
*/
public final class RegexConsts {

View File

@@ -15,14 +15,14 @@
*/
/**
* <h2>常量<h2>
* <h2>常量</h2>
*
* <h3>
* 1. 正则常量
* </h3>
* {@link RegexConsts} 包含常见正则表达式{@link PatternConsts} 包含对应的 {@link Pattern} 对象
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
package xyz.zhouxy.plusone.commons.constant;

View File

@@ -19,7 +19,7 @@ package xyz.zhouxy.plusone.commons.exception;
/**
* 数据不存在异常
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
public final class DataNotExistsException extends Exception {

View File

@@ -0,0 +1,62 @@
/*
* 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;
/**
* 异常工厂
*
* @param <X> 异常类型
* @author ZhouXY108 <luquanlion@outlook.com>
*/
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

@@ -0,0 +1,39 @@
/*
* 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 xyz.zhouxy.plusone.commons.annotation.Virtual;
import xyz.zhouxy.plusone.commons.base.IWithCode;
/**
* 异常场景
*
* @param <TCode> 场景编码
* @author ZhouXY108 <luquanlion@outlook.com>
*/
public interface IExceptionType<TCode> extends IWithCode<TCode> {
/**
* 默认异常信息
*/
String getDefaultMessage();
@Virtual
default String getDescription() {
return getDefaultMessage();
}
}

View File

@@ -13,25 +13,28 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package xyz.zhouxy.plusone.commons.exception;
import javax.annotation.Nonnull;
/**
* <h2>异常<h2>
* IMultiTypesException
*
* <h3>1. {@link MultiTypesException} - 多类型异常</h3>
* <p>
* 异常在不同场景下被抛出可以用不同的枚举值表示不同的场景类型
* </p>
*
* <p>
* 异常实现 {@link MultiTypesException} {@link MultiTypesException#getType} 方法返回对应的场景类型
* </p>
* 异常实现 {@link IMultiTypesException} {@link #getType} 方法返回对应的场景类型
*
* <p>
* 表示场景类型的枚举实现 {@link MultiTypesException.ExceptionType}其中的工厂方法用于创建类型对象
* </p>
* 表示场景类型的枚举实现 {@link IExceptionType}各个枚举值本身就是该场景的异常的工厂实例
* 使用其中的工厂方法用于创建对应类型的异常
*
* <pre>
* public final class LoginException
* extends RuntimeException
* implements MultiTypesException&lt;LoginException, LoginException.Type&gt; {
* implements IMultiTypesException&lt;LoginException.Type&gt; {
* private static final long serialVersionUID = 881293090625085616L;
* private final Type type;
* private LoginException(&#64;Nonnull Type type, &#64;Nonnull String message) {
* super(message);
@@ -57,7 +60,7 @@
*
* // ...
*
* public enum Type implements ExceptionType<LoginException> {
* public enum Type implements IExceptionType&lt;String&gt;, IExceptionFactory&lt;LoginException&gt; {
* DEFAULT("00", "当前会话未登录"),
* NOT_TOKEN("10", "未提供token"),
* INVALID_TOKEN("20", "token无效"),
@@ -113,17 +116,18 @@
* <pre>
* throw LoginException.Type.TOKEN_TIMEOUT.create();
* </pre>
* </p>
*
* <h3>2. 业务异常</h3>
* 预设常见的业务异常可继承 {@link BizException} 自定义业务异常
*
* <h3>3. 系统异常</h3>
* 预设常见的系统异常可继承 {@link SysException} 自定义系统异常
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @param <T> 异常场景
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
package xyz.zhouxy.plusone.commons.exception;
public interface IMultiTypesException<T extends IExceptionType<?>> {
import xyz.zhouxy.plusone.commons.exception.business.*;
import xyz.zhouxy.plusone.commons.exception.system.*;
/**
* 异常类型
*
* @return 异常类型通常是实现了 {@link IExceptionType} 的枚举
*/
@Nonnull
T getType();
}

View File

@@ -21,7 +21,6 @@ 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;
/**
* 解析失败异常
@@ -31,16 +30,16 @@ import xyz.zhouxy.plusone.commons.exception.MultiTypesException.ExceptionType;
* 如果表示用户传参造成的解析失败可使用 {@link RequestParamsException#RequestParamsException(Throwable)}
* ParsingFailureException 包装成 {@link RequestParamsException} 再抛出
* <pre>
* throw new RequestParamsException(ParsingFailureException.of(ParsingFailureException.Type.NUMBER_PARSING_FAILURE));
* throw new RequestParamsException(ParsingFailureException.Type.NUMBER_PARSING_FAILURE.create());
* </pre>
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
public final class ParsingFailureException
extends RuntimeException
implements MultiTypesException<ParsingFailureException, ParsingFailureException.Type> {
extends Exception
implements IMultiTypesException<ParsingFailureException.Type> {
private static final long serialVersionUID = 795996090625132616L;
private final Type type;
@@ -171,7 +170,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<String>, IExceptionFactory<ParsingFailureException> {
DEFAULT("00", "解析失败"),
NUMBER_PARSING_FAILURE("10", "数字转换失败"),
DATE_TIME_PARSING_FAILURE("20", "时间解析失败"),

View File

@@ -21,33 +21,25 @@ package xyz.zhouxy.plusone.commons.exception.business;
*
* <p>
* 业务异常
* </p>
*
* <p>
* <b>NOTE: 通常表示业务中的意外情况用户错误输入缺失必填字段用户余额不足等</b>
* </p>
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
*
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
public class BizException extends RuntimeException {
private static final long serialVersionUID = 982585090625482416L;
private static final String DEFAULT_MSG = "业务异常";
/**
* 使用默认 message 构造新的业务异常
* {@code cause} 未初始化后面可能会通过调用 {@link #initCause} 进行初始化
*/
public BizException() {
super(DEFAULT_MSG);
}
/**
* 使用指定的 {@code message} 构造新的业务异常
* {@code cause} 未初始化后面可能会通过调用 {@link #initCause} 进行初始化
*
* @param message 异常信息
*/
public BizException(String message) {
protected BizException(String message) {
super(message);
}
@@ -57,7 +49,7 @@ public class BizException extends RuntimeException {
*
* @param cause 包装的异常
*/
public BizException(Throwable cause) {
protected BizException(Throwable cause) {
super(cause);
}
@@ -67,8 +59,27 @@ public class BizException extends RuntimeException {
* @param message 异常信息
* @param cause 包装的异常
*/
public BizException(String message, Throwable cause) {
protected BizException(String message, Throwable cause) {
super(message, cause);
}
public static BizException of() {
return new BizException(DEFAULT_MSG);
}
public static BizException of(String message) {
return new BizException(message);
}
public static BizException of(String errorMessageFormat, Object... errorMessageArgs) {
return new BizException(String.format(errorMessageFormat, errorMessageArgs));
}
public static BizException of(Throwable cause) {
return new BizException(cause);
}
public static BizException of(String message, Throwable cause) {
return new BizException(message, cause);
}
}

View File

@@ -18,25 +18,26 @@ 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.IExceptionFactory;
import xyz.zhouxy.plusone.commons.exception.IExceptionType;
import xyz.zhouxy.plusone.commons.exception.IMultiTypesException;
/**
* InvalidInputException
*
* <p>
* 用户输入内容非法
* </p>
*
* <p>
* <b>NOTE: 属业务异常</b>
* </p>
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
*
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
public final class InvalidInputException
extends RequestParamsException
implements MultiTypesException<InvalidInputException, InvalidInputException.Type> {
implements IMultiTypesException<InvalidInputException.Type> {
private static final long serialVersionUID = -28994090625082516L;
private final Type type;
@@ -109,7 +110,7 @@ public final class InvalidInputException
return this.type;
}
public enum Type implements ExceptionType<InvalidInputException> {
public enum Type implements IExceptionType<String>, IExceptionFactory<InvalidInputException> {
DEFAULT("00", "用户输入内容非法"),
CONTAINS_ILLEGAL_AND_MALICIOUS_LINKS("01", "包含非法恶意跳转链接"),
CONTAINS_ILLEGAL_WORDS("02", "包含违禁敏感词"),

View File

@@ -21,12 +21,12 @@ package xyz.zhouxy.plusone.commons.exception.business;
*
* <p>
* 用户请求参数错误
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
public class RequestParamsException extends BizException {
private static final long serialVersionUID = 448337090625192516L;
private static final String DEFAULT_MSG = "用户请求参数错误";

View File

@@ -17,6 +17,6 @@
/**
* 业务异常
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
package xyz.zhouxy.plusone.commons.exception.business;

View File

@@ -0,0 +1,22 @@
/*
* 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.
*/
/**
* 包含常见的业务异常与系统异常,以及异常相关的工具
*
* @author ZhouXY108 <luquanlion@outlook.com>
*/
package xyz.zhouxy.plusone.commons.exception;

View File

@@ -21,55 +21,61 @@ package xyz.zhouxy.plusone.commons.exception.system;
*
* <p>
* 当数据操作的结果不符合预期时抛出
* </p>
*
* <p>
* 比如当一个 insert update 操作时预计影响数据库中的一行数据但结果却影响了零条数据或多条数据
* 当出现这种始料未及的诡异情况时抛出 {@link DataOperationResultException} 并回滚事务
* 后续需要排查原因
* </p>
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
*
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
public final class DataOperationResultException extends SysException {
private static final long serialVersionUID = 992754090625352516L;
private static final String DEFAULT_MSG = "数据操作的结果不符合预期";
private final long expected;
private final long actual;
/**
* 使用默认 message 构造新的 {@code DataOperationResultException}
* {@code cause} 未初始化后面可能会通过调用 {@link #initCause} 进行初始化
* 创建一个 {@code DataOperationResultException} 对象
*
* @param expected 预期影响的行数
* @param actual 实际影响的行数
*/
public DataOperationResultException() {
super(DEFAULT_MSG);
public DataOperationResultException(long expected, long actual) {
super(String.format("The number of rows affected is expected to be %d, but is: %d", expected, actual));
this.expected = expected;
this.actual = actual;
}
/**
* 使用指定的 {@code message} 构造新的 {@code DataOperationResultException}
* {@code cause} 未初始化后面可能会通过调用 {@link #initCause} 进行初始化
* 创建一个 {@code DataOperationResultException} 对象
*
* @param message 异常信息
* @param expected 预期影响的行数
* @param actual 实际影响的行数
* @param message 错误信息
*/
public DataOperationResultException(String message) {
public DataOperationResultException(long expected, long actual, String message) {
super(message);
this.expected = expected;
this.actual = actual;
}
/**
* 使用指定的 {@code cause} 构造新的 {@code DataOperationResultException}
* {@code message} (cause==null ? null : cause.toString())
* 预期影响的行数
*
* @param cause 包装的异常
* @return the expected
*/
public DataOperationResultException(Throwable cause) {
super(cause);
public long getExpected() {
return expected;
}
/**
* 使用指定的 {@code message} {@code cause} 构造新的 {@code DataOperationResultException}
* 实际影响的行数
*
* @param message 异常信息
* @param cause 包装的异常
* @return the actual
*/
public DataOperationResultException(String message, Throwable cause) {
super(message, cause);
public long getActual() {
return actual;
}
}

View File

@@ -21,9 +21,8 @@ package xyz.zhouxy.plusone.commons.exception.system;
*
* <p>
* 在无法找到可访问的 Mac 地址时抛出
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
public class NoAvailableMacFoundException extends SysException {
@@ -34,7 +33,7 @@ public class NoAvailableMacFoundException extends SysException {
* {@code cause} 未初始化后面可能会通过调用 {@link #initCause} 进行初始化
*/
public NoAvailableMacFoundException() {
super();
super("无法找到可访问的 Mac 地址");
}
/**

View File

@@ -21,30 +21,22 @@ package xyz.zhouxy.plusone.commons.exception.system;
*
* <p>
* 通常表示应用代码存在问题或因环境问题引发异常
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
public class SysException extends RuntimeException {
private static final long serialVersionUID = -936435090625482516L;
private static final String DEFAULT_MSG = "系统异常";
/**
* 使用默认 message 构造新的系统异常
* {@code cause} 未初始化后面可能会通过调用 {@link #initCause} 进行初始化
*/
public SysException() {
super(DEFAULT_MSG);
}
/**
* 使用指定的 {@code message} 构造新的系统异常
* {@code cause} 未初始化后面可能会通过调用 {@link #initCause} 进行初始化
*
* @param message 异常信息
*/
public SysException(String message) {
protected SysException(String message) {
super(message);
}
@@ -54,7 +46,7 @@ public class SysException extends RuntimeException {
*
* @param cause 包装的异常
*/
public SysException(Throwable cause) {
protected SysException(Throwable cause) {
super(cause);
}
@@ -64,7 +56,27 @@ public class SysException extends RuntimeException {
* @param message 异常信息
* @param cause 包装的异常
*/
public SysException(String message, Throwable cause) {
protected SysException(String message, Throwable cause) {
super(message, cause);
}
public static SysException of() {
return new SysException(DEFAULT_MSG);
}
public static SysException of(String message) {
return new SysException(message);
}
public static SysException of(String errorMessageFormat, Object... errorMessageArgs) {
return new SysException(String.format(errorMessageFormat, errorMessageArgs));
}
public static SysException of(Throwable cause) {
return new SysException(cause);
}
public static SysException of(String message, Throwable cause) {
return new SysException(message, cause);
}
}

View File

@@ -17,6 +17,6 @@
/**
* 系统异常
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
package xyz.zhouxy.plusone.commons.exception.system;

View File

@@ -24,9 +24,8 @@ import com.google.common.annotations.Beta;
* <p>
* 一个特殊的 {@link java.util.function.UnaryOperator}
* 表示对 {@code boolean} 值的一元操作
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
* @see java.util.function.UnaryOperator
*/

View File

@@ -24,9 +24,8 @@ import com.google.common.annotations.Beta;
* <p>
* 一个特殊的 {@link java.util.function.UnaryOperator}
* 表示对 {@code char} 的一元操作
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
* @see java.util.function.UnaryOperator
*/

View File

@@ -21,11 +21,10 @@ package xyz.zhouxy.plusone.commons.function;
*
* <p>
* 表示一个无入参无返回值的操作可抛出异常
* </p>
*
* @param <E> 可抛出的异常类型
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
@FunctionalInterface

View File

@@ -24,9 +24,8 @@ import java.util.function.Supplier;
*
* <p>
* 返回 {@code Optional&lt;T&gt;} 对象
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
* @see Optional
* @see Supplier

View File

@@ -23,9 +23,8 @@ import java.util.function.Predicate;
*
* <p>
* {@link Predicate} 相关操作
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
* @see Predicate
*/

View File

@@ -21,9 +21,8 @@ package xyz.zhouxy.plusone.commons.function;
*
* <p>
* 允许抛出异常的消费操作是一个特殊的 {@link java.util.function.Consumer}
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
* @see java.util.function.Consumer
*/

View File

@@ -20,13 +20,12 @@ package xyz.zhouxy.plusone.commons.function;
*
* <p>
* 接收一个参数并返回一个结果可以抛出异常
* </p>
*
* @param <T> 入参类型
* @param <R> 返回结果类型
* @param <E> 异常类型
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0
* @see java.util.function.Function
*/

View File

@@ -21,9 +21,8 @@ package xyz.zhouxy.plusone.commons.function;
*
* <p>
* 接收一个参数返回一个布尔值可抛出异常
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
* @see java.util.function.Predicate
*/

View File

@@ -21,12 +21,11 @@ package xyz.zhouxy.plusone.commons.function;
*
* <p>
* 允许抛出异常的 Supplier 接口
* </p>
*
* @param <T> 结果类型
* @param <E> 异常类型
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
* @see java.util.function.Supplier
*/

View File

@@ -25,7 +25,7 @@ import java.util.function.BiFunction;
* <p>
* 接受类型为 T U 的两个参数返回 {@code Optional&lt;R&gt;} 对象
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
* @see Optional
* @see BiFunction

View File

@@ -25,7 +25,7 @@ import java.util.function.Function;
* <p>
* 接受类型为 T 的参数返回 {@code Optional&lt;R&gt;} 对象
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
* @see Optional
* @see Function

View File

@@ -20,7 +20,6 @@
* <h3>1. PredicateTools</h3>
* <p>
* {@link PredicateTools} 用于 {@link java.util.function.Predicate} 的相关操作
* </p>
*
* <h3>2. Functional interfaces</h3>
* <p>
@@ -39,8 +38,7 @@
* | Optional | ToOptionalBiFunction | Optional&lt;R&gt; apply(T,U) |
* | Optional | ToOptionalFunction | Optional&lt;R&gt; apply(T) |
* </pre>
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
package xyz.zhouxy.plusone.commons.function;

View File

@@ -0,0 +1,169 @@
/*
* 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.gson.adapter;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkArgumentNotNull;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQuery;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
/**
* 包含 JSR-310 相关数据类型的 {@code TypeAdapter}
*
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.1.0
* @see TypeAdapter
* @see com.google.gson.GsonBuilder
*/
public class JSR310TypeAdapters {
/**
* {@code LocalDate} 的 {@code TypeAdapter}
* 用于 Gson 对 {@code LocalDate} 进行相互转换。
*/
public static final class LocalDateTypeAdapter
extends TemporalAccessorTypeAdapter<LocalDate, LocalDateTypeAdapter> {
/**
* 默认构造函数,
* 使用 {@link DateTimeFormatter#ISO_LOCAL_DATE} 进行 {@link LocalDate} 的序列化与反序列化。
*/
public LocalDateTypeAdapter() {
this(DateTimeFormatter.ISO_LOCAL_DATE);
}
/**
* 构造函数,
* 使用传入的 {@link DateTimeFormatter} 进行 {@link LocalDate} 的序列化与反序列化。
*
* @param formatter 用于序列化 {@link LocalDate} 的格式化器,不可为 {@code null}。
*/
public LocalDateTypeAdapter(DateTimeFormatter formatter) {
super(LocalDate::from, formatter);
}
}
/**
* {@code LocalDateTime} 的 {@code TypeAdapter}
* 用于 Gson 对 {@code LocalDateTime} 进行相互转换。
*/
public static final class LocalDateTimeTypeAdapter
extends TemporalAccessorTypeAdapter<LocalDateTime, LocalDateTimeTypeAdapter> {
/**
* 默认构造函数,
* 使用 {@link DateTimeFormatter#ISO_LOCAL_DATE_TIME} 进行 {@link LocalDateTime} 的序列化与反序列化。
*/
public LocalDateTimeTypeAdapter() {
this(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
}
/**
* 构造函数,
* 使用传入的 {@link DateTimeFormatter} 进行 {@link LocalDateTime} 的序列化与反序列化。
*
* @param formatter 用于序列化 {@link LocalDateTime} 的格式化器,不可为 {@code null}。
*/
public LocalDateTimeTypeAdapter(DateTimeFormatter formatter) {
super(LocalDateTime::from, formatter);
}
}
/**
* {@code ZonedDateTime} 的 {@code TypeAdapter}
* 用于 Gson 对 {@code ZonedDateTime} 进行相互转换。
*/
public static final class ZonedDateTimeTypeAdapter
extends TemporalAccessorTypeAdapter<ZonedDateTime, ZonedDateTimeTypeAdapter> {
/**
* 默认构造函数,
* 使用 {@link DateTimeFormatter#ISO_ZONED_DATE_TIME} 进行 {@link ZonedDateTime} 的序列化与反序列化。
*/
public ZonedDateTimeTypeAdapter() {
this(DateTimeFormatter.ISO_ZONED_DATE_TIME);
}
/**
* 构造函数,
* 使用传入的 {@link DateTimeFormatter} 进行 {@link ZonedDateTime} 的序列化与反序列化。
*
* @param formatter 用于序列化 {@link ZonedDateTime} 的格式化器,不可为 {@code null}。
*/
public ZonedDateTimeTypeAdapter(DateTimeFormatter formatter) {
super(ZonedDateTime::from, formatter);
}
}
/**
* {@code Instant} 的 {@code TypeAdapter}
* 用于 Gson 对 {@code Instant} 进行相互转换。
*
* <p>
* 使用 {@link DateTimeFormatter#ISO_INSTANT} 进行 {@link Instant} 的序列化与反序列化。
*
*/
public static final class InstantTypeAdapter
extends TemporalAccessorTypeAdapter<Instant, InstantTypeAdapter> {
public InstantTypeAdapter() {
super(Instant::from, DateTimeFormatter.ISO_INSTANT);
}
}
private abstract static class TemporalAccessorTypeAdapter<
T extends TemporalAccessor,
TTypeAdapter extends TemporalAccessorTypeAdapter<T, TTypeAdapter>>
extends TypeAdapter<T> {
private final TemporalQuery<T> temporalQuery;
private final DateTimeFormatter dateTimeFormatter;
protected TemporalAccessorTypeAdapter(
TemporalQuery<T> temporalQuery, DateTimeFormatter dateTimeFormatter) {
checkArgumentNotNull(dateTimeFormatter, "formatter must not be null.");
this.temporalQuery = temporalQuery;
this.dateTimeFormatter = dateTimeFormatter;
}
/** {@inheritDoc} */
@Override
public void write(JsonWriter out, T value) throws IOException {
out.value(dateTimeFormatter.format(value));
}
/** {@inheritDoc} */
@Override
public T read(JsonReader in) throws IOException {
return dateTimeFormatter.parse(in.nextString(), temporalQuery);
}
}
private JSR310TypeAdapters() {
throw new IllegalStateException("Utility class");
}
}

View File

@@ -0,0 +1,20 @@
/*
* 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.
*/
/**
* Gson 相关类型适配器
*/
package xyz.zhouxy.plusone.commons.gson.adapter;

View File

@@ -0,0 +1,20 @@
/*
* 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.
*/
/**
* Gson 相关辅助工具
*/
package xyz.zhouxy.plusone.commons.gson;

View File

@@ -16,6 +16,8 @@
package xyz.zhouxy.plusone.commons.model;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkArgument;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
@@ -32,7 +34,6 @@ 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.constant.PatternConsts;
import xyz.zhouxy.plusone.commons.util.AssertTools;
import xyz.zhouxy.plusone.commons.util.StringTools;
/**
@@ -40,9 +41,8 @@ import xyz.zhouxy.plusone.commons.util.StringTools;
*
* <p>
* 中国第二代居民身份证号
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
* @see xyz.zhouxy.plusone.commons.constant.PatternConsts#CHINESE_2ND_ID_CARD_NUMBER
*/
@@ -87,13 +87,13 @@ public class Chinese2ndGenIDCardNumber
*/
public static Chinese2ndGenIDCardNumber of(final String idCardNumber) {
try {
AssertTools.checkArgument(StringTools.isNotBlank(idCardNumber), "二代居民身份证校验失败:号码为空");
checkArgument(StringTools.isNotBlank(idCardNumber), "二代居民身份证校验失败:号码为空");
final String value = idCardNumber.toUpperCase();
final Matcher matcher = PatternConsts.CHINESE_2ND_ID_CARD_NUMBER.matcher(value);
AssertTools.checkArgument(matcher.matches(), () -> "二代居民身份证校验失败:" + value);
checkArgument(matcher.matches(), () -> "二代居民身份证校验失败:" + value);
final String provinceCode = matcher.group("province");
AssertTools.checkArgument(Chinese2ndGenIDCardNumber.PROVINCE_CODES.containsKey(provinceCode));
checkArgument(Chinese2ndGenIDCardNumber.PROVINCE_CODES.containsKey(provinceCode));
final String cityCode = matcher.group("city");
final String countyCode = matcher.group("county");

View File

@@ -16,13 +16,14 @@
package xyz.zhouxy.plusone.commons.model;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkCondition;
import xyz.zhouxy.plusone.commons.base.IWithIntCode;
import xyz.zhouxy.plusone.commons.util.AssertTools;
/**
* 性别
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
public enum Gender implements IWithIntCode {
UNKNOWN(0, "Unknown", "未知"),
@@ -50,7 +51,7 @@ public enum Gender implements IWithIntCode {
* @return 枚举值
*/
public static Gender of(int value) {
AssertTools.checkCondition(0 <= value && value < VALUES.length,
checkCondition(0 <= value && value < VALUES.length,
() -> new EnumConstantNotPresentException(Gender.class, String.valueOf(value)));
return VALUES[value];
}

View File

@@ -23,6 +23,8 @@ import xyz.zhouxy.plusone.commons.util.StringTools;
/**
* 身份证号
*
* @author ZhouXY108 <luquanlion@outlook.com>
*/
public interface IDCardNumber {

View File

@@ -0,0 +1,275 @@
/*
* 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.model;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkArgument;
import java.io.Serializable;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import com.google.common.base.Splitter;
import xyz.zhouxy.plusone.commons.util.StringTools;
/**
* SemVer 语义版本号
*
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.1.0
*
* @see <a href="https://semver.org/">Semantic Versioning 2.0.0</a>
*/
public class SemVer implements Comparable<SemVer>, Serializable {
private static final long serialVersionUID = 458265121025514002L;
private final String value;
private final int[] versionNumbers;
@Nullable
private final String preReleaseVersion;
@Nullable
private final String buildMetadata;
private static final String VERSION_NUMBERS = "(?<numbers>(?<major>0|[1-9]\\d*)\\.(?<minor>0|[1-9]\\d*)\\.(?<patch>0|[1-9]\\d*)(\\.(0|[1-9]\\d*)){0,2})";
private static final String PRE_RELEASE_VERSION = "(?:-(?<prerelease>(?:0|[1-9]\\d{0,41}|\\d{0,18}[a-zA-Z-][0-9a-zA-Z-]{0,18})(?:\\.(?:0|[1-9]\\d{0,41}|\\d{0,18}[a-zA-Z-][0-9a-zA-Z-]{0,18})){0,18}))?";
private static final String BUILD_METADATA = "(?:\\+(?<buildmetadata>[0-9a-zA-Z-]{1,18}(?:\\.[0-9a-zA-Z-]{1,18}){0,18}))?";
private static final Pattern PATTERN = Pattern.compile(
"^" + VERSION_NUMBERS + PRE_RELEASE_VERSION + BUILD_METADATA + "$");
/**
* 创建语义化版本号的值对象
*
* @param value 字符串值
* @param versionNumbers 主版本号、次版本号、修订号
* @param preReleaseVersion 先行版本号
* @param buildMetadata 版本编译信息
*/
private SemVer(String value,
int[] versionNumbers,
@Nullable String preReleaseVersion,
@Nullable String buildMetadata) {
this.value = value;
this.versionNumbers = versionNumbers;
this.preReleaseVersion = preReleaseVersion;
this.buildMetadata = buildMetadata;
}
/**
* 创建 SemVer 对象
*
* @param value 语义化版本号
* @return SemVer 对象
*/
public static SemVer of(final String value) {
checkArgument(StringTools.isNotBlank(value), "版本号不能为空");
final Matcher matcher = PATTERN.matcher(value);
checkArgument(matcher.matches(), "版本号格式错误");
// 数字版本部分
final String versionNumbersPart = matcher.group("numbers");
// 先行版本号部分
final String preReleaseVersionPart = matcher.group("prerelease");
// 版本编译信息部分
final String buildMetadataPart = matcher.group("buildmetadata");
final int[] versionNumbers = Splitter.on('.')
.splitToStream(versionNumbersPart)
// 必须都是数字
.mapToInt(Integer::parseInt)
.toArray();
return new SemVer(value, versionNumbers, preReleaseVersionPart, buildMetadataPart);
}
/**
* 获取主版本号
*
* @return 主版本号
*/
public int getMajor() {
return this.versionNumbers[0];
}
/**
* 获取次版本号
*
* @return 次版本号
*/
public int getMinor() {
return this.versionNumbers[1];
}
/**
* 获取修订号
*
* @return 修订号
*/
public int getPatch() {
return this.versionNumbers[2];
}
/**
* 获取先行版本号
*
* @return 先行版本号
*/
@Nullable
public String getPreReleaseVersion() {
return this.preReleaseVersion;
}
/**
* 获取版本编译信息
*
* @return 版本编译信息
*/
@Nullable
public String getBuildMetadata() {
return buildMetadata;
}
/** {@inheritDoc} */
@Override
public int compareTo(@SuppressWarnings("null") SemVer that) {
if (this == that) {
return 0;
}
int result = compareVersionNumbers(that);
if (result != 0) {
return result;
}
return comparePreReleaseVersion(that);
}
/**
* 获取字符串值
*
* @return 版本字符串
*/
public String getValue() {
return value;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
return Objects.hash(value);
}
/** {@inheritDoc} */
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj)
return true;
if (!(obj instanceof SemVer))
return false;
SemVer other = (SemVer) obj;
return Objects.equals(value, other.value);
}
/**
* 获取 SemVer 的字符串表示。如 {@code v1.2.3-alpha.1+build.1234}
*/
@Override
public String toString() {
return 'v' + value;
}
/**
* 比较主版本号、次版本号、修订号
*/
private int compareVersionNumbers(SemVer that) {
final int minLength = Integer.min(this.versionNumbers.length, that.versionNumbers.length);
for (int i = 0; i < minLength; i++) {
final int currentVersionNumberOfThis = this.versionNumbers[i];
final int currentVersionNumberOfThat = that.versionNumbers[i];
if (currentVersionNumberOfThis != currentVersionNumberOfThat) {
return currentVersionNumberOfThis - currentVersionNumberOfThat;
}
}
return this.versionNumbers.length - that.versionNumbers.length;
}
/**
* 比较先行版本号
*/
private int comparePreReleaseVersion(SemVer that) {
int thisWithoutPreReleaseVersionFlag = bool2Int(this.preReleaseVersion == null);
int thatWithoutPreReleaseVersionFlag = bool2Int(that.preReleaseVersion == null);
if (isTrue(thisWithoutPreReleaseVersionFlag | thatWithoutPreReleaseVersionFlag)) {
return thisWithoutPreReleaseVersionFlag - thatWithoutPreReleaseVersionFlag;
}
Splitter splitter = Splitter.on('.');
final String[] preReleaseVersionOfThis = splitter
.splitToStream(this.preReleaseVersion) // NOSONAR
.toArray(String[]::new);
final String[] preReleaseVersionOfThat = splitter
.splitToStream(that.preReleaseVersion) // NOSONAR
.toArray(String[]::new);
final int minLength = Integer.min(preReleaseVersionOfThis.length, preReleaseVersionOfThat.length);
for (int i = 0; i < minLength; i++) {
int r = comparePartOfPreReleaseVersion(preReleaseVersionOfThis[i], preReleaseVersionOfThat[i]);
if (r != 0) {
return r;
}
}
return preReleaseVersionOfThis.length - preReleaseVersionOfThat.length;
}
/**
* 比较先行版本号的组成部分
*/
private static int comparePartOfPreReleaseVersion(String p1, String p2) {
boolean p1IsNumber = isAllDigits(p1);
boolean p2IsNumber = isAllDigits(p2);
if (p1IsNumber) {
return p2IsNumber
? Integer.parseInt(p1) - Integer.parseInt(p2) // 都是数字
: -1; // p1 是数字p2 是字符串
}
// 如果 p1 是字符串p2 是数字,则返回 1字符串优先于纯数字
return p2IsNumber ? 1 : p1.compareTo(p2);
}
/**
* 判断字符串是否全为数字
*/
private static boolean isAllDigits(String str) {
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c < '0' || c > '9') {
return false;
}
}
return true;
}
private static int bool2Int(boolean expression) {
return expression ? 1 : 0;
}
private static boolean isTrue(int b) {
return b != 0;
}
}

View File

@@ -16,6 +16,9 @@
package xyz.zhouxy.plusone.commons.model;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkArgument;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkArgumentNotNull;
import java.util.Objects;
import java.util.function.Supplier;
import java.util.regex.Matcher;
@@ -25,12 +28,11 @@ import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import xyz.zhouxy.plusone.commons.annotation.ReaderMethod;
import xyz.zhouxy.plusone.commons.util.AssertTools;
/**
* 带校验的字符串值对象
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*
* @deprecated 弃用使用工厂方法创建对象并在其中进行校验即可
@@ -74,10 +76,10 @@ public abstract class ValidatableStringRecord<T extends ValidatableStringRecord<
* @param errorMessage 正则不匹配时的错误信息
*/
protected ValidatableStringRecord(String value, Pattern pattern, String errorMessage) {
AssertTools.checkArgument(Objects.nonNull(value), "The value cannot be null.");
AssertTools.checkArgument(Objects.nonNull(pattern), "The pattern cannot be null.");
checkArgumentNotNull(value, "The value cannot be null.");
checkArgumentNotNull(pattern, "The pattern cannot be null.");
this.matcher = pattern.matcher(value);
AssertTools.checkArgument(this.matcher.matches(), errorMessage);
checkArgument(this.matcher.matches(), errorMessage);
this.value = value;
}

View File

@@ -29,7 +29,7 @@ import xyz.zhouxy.plusone.commons.collection.CollectionTools;
*
* @param <T> 内容列表的元素类型
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @see PagingAndSortingQueryParams
*/
public class PageResult<T> {

View File

@@ -0,0 +1,293 @@
/*
* Copyright 2022-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.model.dto;
import static com.google.common.base.Preconditions.checkArgument;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import com.google.common.collect.ImmutableMap;
import xyz.zhouxy.plusone.commons.collection.CollectionTools;
import xyz.zhouxy.plusone.commons.util.RegexTools;
import xyz.zhouxy.plusone.commons.util.StringTools;
/**
* 分页排序查询参数
*
* <p>
* 包含三个主要的属性:
* <ul>
* <li>size - 每页显示的记录数</li>
* <li>pageNum - 当前页码</li>
* <li>orderBy - 排序条件</li>
* </ul>
*
* <p>
* 分页必须伴随着排序,不然可能出现同一个对象重复出现在不同页,有的对象不被查询到的情况。
*
* <p>
* 其中 {@code orderBy} 是一个 {@code List&lt;String&gt;},可以指定多个排序条件。
* 每个排序条件是一个字符串, 格式为“属性名-ASC”或“属性名-DESC”分别表示升序和降序。
* 例如,当 {@code orderBy} 的值为 {@code ["name-ASC","age-DESC"]}
* 意味着要按 {@code name} 进行升序排列,{@code name} 相同的情况下则按 {@code age} 进行降序排列。
*
* <p>
* 用户可继承 {@link PagingAndSortingQueryParams} 构建自己的分页查询入参,
* 子类需在构造器中调用 {@link PagingAndSortingQueryParams} 的构造器,
* 传入一个 {@link PagingParamsBuilder} 用于构建分页参数。
* 同一场景下,复用一个 {@link PagingParamsBuilder} 实例即可。
*
* <p>
* 构建 {@link PagingParamsBuilder} 时,需传入一个 {@code Map} 作为可排序字段的白名单,
* {@code key} 是供前端指定用于排序的属性名,{@code value} 是对应数据库中的字段名。
* 只有在此白名单中的属性名才允许用于排序。
*
* <pre>
* class AccountQueryParams extends PagingAndSortingQueryParams {
* private static final Map&lt;String, String&gt; PROPERTY_COLUMN_MAP = ImmutableMap.&lt;String, String&gt;builder()
* .put("id", "id")
* .put("username", "username")
* .build();
* private static final PagingParamsBuilder PAGING_PARAMS_BUILDER = PagingAndSortingQueryParams
* .pagingParamsBuilder(20, 100, PROPERTY_COLUMN_MAP);
*
* public AccountQueryParams() {
* // 所有的 AccountQueryParams 复用同一个 PagingParamsBuilder 实例
* super(PAGING_PARAMS_BUILDER);
* }
*
* private @Getter @Setter Long id;
* private @Getter @Setter String username;
* private @Getter @Setter String email;
* private @Getter @Setter Integer status;
* }
*
* public PageResult&lt;AccountVO&gt; queryPage(AccountQueryParams params) {
* // 获取分页参数
* PagingParams pagingParams = params.buildPagingParams();
* // 从 params 获取字段查询条件,从 pagingParams 获取分页条件,查询一页数据
* List&lt;AccountVO&gt; list = accountQueries.queryAccountList(params, pagingParams);
* // 查询总记录数
* long count = accountQueries.countAccount(params);
* // 返回分页结果
* return PageResult.of(list, count);
* }
* </pre>
*
* @author ZhouXY108 <luquanlion@outlook.com>
* @see PagingParams
* @see PageResult
*/
public class PagingAndSortingQueryParams {
private final PagingParamsBuilder pagingParamsBuilder;
private Integer size;
private Long pageNum;
private List<String> orderBy;
/**
* 创建一个 {@code PagingAndSortingQueryParams} 实例
*
* @param pagingParamsBuilder
* 分页参数构造器。
* 通过 {@link #pagingParamsBuilder(int, int, Map)} 创建,同一场景下只需要共享同一个实例。
*/
public PagingAndSortingQueryParams(PagingParamsBuilder pagingParamsBuilder) {
this.pagingParamsBuilder = pagingParamsBuilder;
}
// Setters
/**
* 设置排序规则
*
* @param orderBy 排序规则,不能为空
*/
public final void setOrderBy(List<String> orderBy) {
this.orderBy = orderBy;
}
/**
* 设置每页大小
*
* @param size 每页大小
*/
public final void setSize(@Nullable Integer size) {
this.size = size;
}
/**
* 设置页码
*
* @param pageNum 页码
*/
public final void setPageNum(@Nullable Long pageNum) {
this.pageNum = pageNum;
}
// Setters end
@Override
public String toString() {
return "PagingAndSortingQueryParams ["
+ "size=" + size
+ ", pageNum=" + pageNum
+ ", orderBy=" + orderBy
+ "]";
}
/**
* 创建一个分页参数构造器
*
* @param defaultSize 默认每页大小
* @param maxSize 最大每页大小
* @param sortableProperties
* 可排序属性。
* key 是供前端指定用于排序的属性名value 是对应数据库中的字段名。
* 只有在此白名单中的属性名才允许用于排序。
* @return 分页参数构造器
*/
public static PagingParamsBuilder pagingParamsBuilder(
int defaultSize, int maxSize, Map<String, String> sortableProperties) {
return new PagingParamsBuilder(defaultSize, maxSize, sortableProperties);
}
/**
* 根据当前查询参数,构建分页参数
*
* @return 分页参数
*/
public PagingParams buildPagingParams() {
return this.pagingParamsBuilder.buildPagingParams(this);
}
/**
* 可排序属性
*/
public static final class SortableProperty {
private final String propertyName;
private final String columnName;
private final String orderType;
private final String sqlSnippet;
private SortableProperty(String propertyName, String columnName, String orderType) {
this.propertyName = propertyName;
this.columnName = columnName;
checkArgument("ASC".equalsIgnoreCase(orderType) || "DESC".equalsIgnoreCase(orderType));
this.orderType = orderType.toUpperCase();
this.sqlSnippet = this.propertyName + " " + this.orderType;
}
/**
* 属性名
*
* @return 属性名
*/
public String getPropertyName() {
return propertyName;
}
/**
* 对应数据库中列名称
*
* @return 列名称
*/
public String getColumnName() {
return columnName;
}
/**
* 排序方式
*
* @return 排序方式
*/
public String getOrderType() {
return orderType;
}
/**
* SQL 片段
*
* @return SQL 片段
*/
public String getSqlSnippet() {
return sqlSnippet;
}
@Override
public String toString() {
return "SortableProperty ["
+ "propertyName=" + propertyName
+ ", columnName=" + columnName
+ ", orderType=" + orderType
+ "]";
}
}
protected static final class PagingParamsBuilder {
private static final Pattern SORT_STR_PATTERN = Pattern.compile("^[a-zA-Z][\\w-]{0,63}-(desc|asc|DESC|ASC)$");
private final Map<String, String> sortableProperties;
protected final int defaultSize;
protected final int maxSize;
private PagingParamsBuilder(int defaultSize, int maxSize, Map<String, String> sortableProperties) {
this.defaultSize = defaultSize;
this.maxSize = maxSize;
checkArgument(CollectionTools.isNotEmpty(sortableProperties),
"Sortable properties can not be empty.");
sortableProperties.forEach((k, v) ->
checkArgument(StringTools.isNotBlank(k) && StringTools.isNotBlank(v),
"Property name must not be blank."));
this.sortableProperties = ImmutableMap.copyOf(sortableProperties);
}
public PagingParams buildPagingParams(PagingAndSortingQueryParams params) {
final int sizeValue = params.size != null ? params.size : this.defaultSize;
final long pageNumValue = params.pageNum != null ? params.pageNum : 1L;
checkArgument(CollectionTools.isNotEmpty(params.orderBy),
"The 'orderBy' cannot be empty");
final List<SortableProperty> propertiesToSort = params.orderBy.stream()
.map(this::generateSortableProperty)
.collect(Collectors.toList());
return new PagingParams(sizeValue, pageNumValue, propertiesToSort);
}
private SortableProperty generateSortableProperty(String orderByStr) {
checkArgument(StringTools.isNotBlank(orderByStr));
checkArgument(RegexTools.matches(orderByStr, SORT_STR_PATTERN));
String[] propertyNameAndOrderType = orderByStr.split("-");
checkArgument(propertyNameAndOrderType.length == 2);
String propertyName = propertyNameAndOrderType[0];
checkArgument(sortableProperties.containsKey(propertyName),
"The property name must be in the set of sortable properties.");
String columnName = sortableProperties.get(propertyName);
String orderType = propertyNameAndOrderType[1];
return new SortableProperty(propertyName, columnName, orderType);
}
}
}

View File

@@ -21,6 +21,12 @@ import java.util.List;
import xyz.zhouxy.plusone.commons.model.dto.PagingAndSortingQueryParams.SortableProperty;
/**
* 分页参数
*
* @author ZhouXY108 <luquanlion@outlook.com>
* @see PagingAndSortingQueryParams
*/
public class PagingParams {
/** 每页大小 */

View File

@@ -22,7 +22,7 @@ import javax.annotation.Nullable;
/**
* 统一结果对返回给前端的数据进行封装
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
public class UnifiedResponse<T> {

View File

@@ -19,9 +19,42 @@ package xyz.zhouxy.plusone.commons.model.dto;
import javax.annotation.Nullable;
/**
* UnifiedResponse 工厂
* {@link UnifiedResponse} 工厂
* 用于快速构建 {@link UnifiedResponse} 对象默认的成功代码为 {@code 2000000}
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* <p>
* 用户可以继承 {@link UnifiedResponses} 实现自己的工厂类
* 自定义 SUCCESS_CODE DEFAULT_SUCCESS_MSG以及工厂方法
* 如下所示
* <pre>
* // 自定义工厂类
* public static class CustomUnifiedResponses extends UnifiedResponses {
*
* public static final String SUCCESS_CODE = "000";
* public static final String DEFAULT_SUCCESS_MSG = "成功";
*
* public static &lt;T&gt; UnifiedResponse&lt;T&gt; success() {
* return of(SUCCESS_CODE, DEFAULT_SUCCESS_MSG);
* }
*
* public static &lt;T&gt; UnifiedResponse&lt;T&gt; success(@Nullable String message) {
* return of(SUCCESS_CODE, message);
* }
*
* public static &lt;T&gt; UnifiedResponse&lt;T&gt; success(@Nullable String message, @Nullable T data) {
* return of(SUCCESS_CODE, message, data);
* }
*
* private CustomUnifiedResponses() {
* super();
* }
* }
* // 使用自定义工厂类
* CustomUnifiedResponses.success("查询成功", userList); // 状态码为 000
* </pre>
* <a href="http://zhouxy.xyz:3000/plusone/plusone-commons/issues/22">issue#22</a>
*
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
* @see UnifiedResponse
*/
@@ -40,7 +73,7 @@ public class UnifiedResponses {
* @return {@code UnifiedResponse} 对象
* {@code code} = "2000000", {@code message} = "SUCCESS", {@code data} = null
*/
public static UnifiedResponse<Void> success() {
public static <T> UnifiedResponse<T> success() {
return new UnifiedResponse<>(SUCCESS_CODE, DEFAULT_SUCCESS_MSG);
}
@@ -51,7 +84,7 @@ public class UnifiedResponses {
* @return {@code UnifiedResponse} 对象
* {@code code} = "2000000", {@code data} = null
*/
public static UnifiedResponse<Void> success(@Nullable String message) {
public static <T> UnifiedResponse<T> success(@Nullable String message) {
return new UnifiedResponse<>(SUCCESS_CODE, message);
}
@@ -83,7 +116,7 @@ public class UnifiedResponses {
* @param message 错误信息
* @return {@code UnifiedResponse} 对象{@code data} {@code null}
*/
public static UnifiedResponse<Void> error(String code, @Nullable String message) {
public static <T> UnifiedResponse<T> error(String code, @Nullable String message) {
return new UnifiedResponse<>(code, message);
}
@@ -109,7 +142,7 @@ public class UnifiedResponses {
* {@code message} 为异常的 {@code message}
* {@code data} {@code null}
*/
public static UnifiedResponse<Void> error(String code, Throwable e) {
public static <T> UnifiedResponse<T> error(String code, Throwable e) {
return new UnifiedResponse<>(code, e.getMessage());
}
@@ -128,7 +161,7 @@ public class UnifiedResponses {
* @param message 响应信息
* @return {@code UnifiedResponse} 对象{@code data} {@code null}
*/
public static UnifiedResponse<Void> of(String code, @Nullable String message) {
public static <T> UnifiedResponse<T> of(String code, @Nullable String message) {
return new UnifiedResponse<>(code, message);
}

View File

@@ -22,12 +22,12 @@
* 分页组件由 {@link PagingAndSortingQueryParams} 作为入参
* 因为分页必须伴随着排序不然可能出现同一个对象重复出现在不同页有的对象不被查询到的情况
* 所以分页查询的入参必须包含排序条件
* </p>
*
* <p>
* 用户可继承 {@link PagingAndSortingQueryParams}
* 构建自己的分页查询入参需在构造器中调用 {@link PagingAndSortingQueryParams} 的构造器传入一个 Map 作为白名单
* key 是供前端指定用于排序的属性名value 是对应数据库中的字段名只有在白名单中指定的属性名才允许作为排序条件
* </p>
*
* <p>
* {@link PagingAndSortingQueryParams} 包含三个主要的属性
* <ul>
@@ -37,32 +37,28 @@
* </ul>
* 其中 orderBy 是一个 List可以指定多个排序条件每个排序条件是一个字符串
* 格式为属性名-ASC属性名-DESC分别表示升序和降序
* </p>
*
* <p>
* 比如前端传入的 orderBy ["name-ASC","age-DESC"]意味着要按 name 进行升序name 相同的情况下则按 age 进行降序
* </p>
*
* <p>
* 使用时调用 {@link PagingAndSortingQueryParams#buildPagingParams()} 方法获取分页参数 {@link PagingParams}
* </p>
*
* <p>
* 分页结果可以存放到 {@link PageResult} 作为出参
* </p>
*
* <h3>2. {@link UnifiedResponse}</h3>
* <p>
* {@link UnifiedResponse} 对返回给前端的数据进行封装包含 codemessagedata
* </p>
* <p>
* 可使用 {@link UnifiedResponses} 快速构建 {@link UnifiedResponse} 对象
* {@link UnifiedResponses} 默认的成功代码为 "2000000"
* 用户按测试类
* <a href="http://zhouxy.xyz:3000/plusone/plusone-commons/src/branch/main/src/test/java/xyz/zhouxy/plusone/commons/model/dto/CustomUnifiedResponseFactoryTests.java">CustomUnifiedResponseFactoryTests</a>
* 中所示范的继承 {@link UnifiedResponses} 实现自己的工厂类
* 自定义 SUCCESS_CODE DEFAULT_SUCCESS_MSG 和工厂方法
* <a href="http://zhouxy.xyz:3000/plusone/plusone-commons/issues/22">issue#22</a>
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* <p>
* {@link UnifiedResponses} 用于快速构建 {@link UnifiedResponse} 对象默认的成功代码为 {@code 2000000}
*
* <p>
* 用户可以继承 {@link UnifiedResponses} 实现自己的工厂类
* 自定义 SUCCESS_CODE DEFAULT_SUCCESS_MSG以及工厂方法
*
* @author ZhouXY108 <luquanlion@outlook.com>
*/
@ParametersAreNonnullByDefault
package xyz.zhouxy.plusone.commons.model.dto;

View File

@@ -18,9 +18,8 @@
* <h2>业务建模组件</h2>
* <p>
* 包含业务建模可能用到的性别身份证等元素也包含 DTO 相关类如分页查询参数响应结果分页结果等
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
@ParametersAreNonnullByDefault
package xyz.zhouxy.plusone.commons.model;

View File

@@ -16,6 +16,9 @@
package xyz.zhouxy.plusone.commons.time;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkNotNull;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkCondition;
import java.time.DateTimeException;
import java.time.Month;
import java.time.MonthDay;
@@ -25,12 +28,11 @@ import com.google.common.collect.Range;
import xyz.zhouxy.plusone.commons.annotation.StaticFactoryMethod;
import xyz.zhouxy.plusone.commons.base.IWithIntCode;
import xyz.zhouxy.plusone.commons.util.AssertTools;
/**
* 季度
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
public enum Quarter implements IWithIntCode {
/** 第一季度 */
@@ -89,7 +91,7 @@ public enum Quarter implements IWithIntCode {
*/
@StaticFactoryMethod(Quarter.class)
public static Quarter fromMonth(Month month) {
AssertTools.checkNotNull(month);
checkNotNull(month);
final int monthValue = month.getValue();
return of(computeQuarterValueInternal(monthValue));
}
@@ -246,7 +248,7 @@ public enum Quarter implements IWithIntCode {
* @throws DateTimeException 如果给定的季度值不在有效范围内1到4将抛出异常
*/
public static int checkValidIntValue(int value) {
AssertTools.checkCondition(value >= 1 && value <= 4,
checkCondition(value >= 1 && value <= 4,
() -> new DateTimeException("Invalid value for Quarter: " + value));
return value;
}

View File

@@ -17,6 +17,7 @@
package xyz.zhouxy.plusone.commons.time;
import static java.time.temporal.ChronoField.YEAR;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkNotNull;
import java.io.Serializable;
import java.time.LocalDate;
@@ -32,12 +33,11 @@ import javax.annotation.Nullable;
import com.google.errorprone.annotations.Immutable;
import xyz.zhouxy.plusone.commons.annotation.StaticFactoryMethod;
import xyz.zhouxy.plusone.commons.util.AssertTools;
/**
* 表示年份与季度
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
@Immutable
public final class YearQuarter implements Comparable<YearQuarter>, Serializable {
@@ -93,7 +93,7 @@ public final class YearQuarter implements Comparable<YearQuarter>, Serializable
*/
@StaticFactoryMethod(YearQuarter.class)
public static YearQuarter of(LocalDate date) {
AssertTools.checkNotNull(date);
checkNotNull(date);
return new YearQuarter(date.getYear(), Quarter.fromMonth(date.getMonth()));
}
@@ -105,7 +105,7 @@ public final class YearQuarter implements Comparable<YearQuarter>, Serializable
*/
@StaticFactoryMethod(YearQuarter.class)
public static YearQuarter of(Date date) {
AssertTools.checkNotNull(date);
checkNotNull(date);
@SuppressWarnings("deprecation")
final int yearValue = YEAR.checkValidIntValue(date.getYear() + 1900L);
@SuppressWarnings("deprecation")
@@ -121,7 +121,7 @@ public final class YearQuarter implements Comparable<YearQuarter>, Serializable
*/
@StaticFactoryMethod(YearQuarter.class)
public static YearQuarter of(Calendar date) {
AssertTools.checkNotNull(date);
checkNotNull(date);
final int yearValue = ChronoField.YEAR.checkValidIntValue(date.get(Calendar.YEAR));
final int monthValue = date.get(Calendar.MONTH) + 1;
return new YearQuarter(yearValue, Quarter.fromMonth(monthValue));
@@ -135,7 +135,7 @@ public final class YearQuarter implements Comparable<YearQuarter>, Serializable
*/
@StaticFactoryMethod(YearQuarter.class)
public static YearQuarter of(YearMonth yearMonth) {
AssertTools.checkNotNull(yearMonth);
checkNotNull(yearMonth);
return of(yearMonth.getYear(), Quarter.fromMonth(yearMonth.getMonth()));
}

View File

@@ -15,14 +15,14 @@
*/
/**
* <h2>时间 API<h2>
* <h2>时间 API</h2>
*
* <h3>1. 季度 API</h3>
*
* 模仿 JDK {@link java.time.Month} {@link java.time.YearMonth}
* 实现 {@link Quarter}{@link YearQuarter}对季度进行建模
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
@ParametersAreNonnullByDefault
package xyz.zhouxy.plusone.commons.time;

View File

@@ -16,6 +16,10 @@
package xyz.zhouxy.plusone.commons.util;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkArgument;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkArgumentNotNull;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkNotNull;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
@@ -33,9 +37,8 @@ import javax.annotation.Nullable;
*
* <p>
* 数组工具类
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
public class ArrayTools {
@@ -54,9 +57,9 @@ public class ArrayTools {
public static final int NOT_FOUND_INDEX = -1;
// #region - isNullOrEmpty
// #region - isEmpty
// isNullOrEmpty
// isEmpty
/**
* 检查给定数组是否为空
@@ -65,84 +68,84 @@ public class ArrayTools {
* @param <T> 数组中元素的类型
* @return 如果数组为 {@code null} 或长度为 0则返回 {@code true}否则返回 {@code false}
*/
public static <T> boolean isNullOrEmpty(@Nullable T[] arr) {
public static <T> boolean isEmpty(@Nullable T[] arr) {
return arr == null || arr.length == 0;
}
// isNullOrEmpty - char
// isEmpty - char
/**
* 检查给定数组是否为空
*
* @param arr 待检查的数组可以为 {@code null}
* @return 如果数组为 {@code null} 或长度为 0则返回 {@code true}否则返回 {@code false}
*/
public static boolean isNullOrEmpty(@Nullable char[] arr) {
public static boolean isEmpty(@Nullable char[] arr) {
return arr == null || arr.length == 0;
}
// isNullOrEmpty - byte
// isEmpty - byte
/**
* 检查给定数组是否为空
*
* @param arr 待检查的数组可以为 {@code null}
* @return 如果数组为 {@code null} 或长度为 0则返回 {@code true}否则返回 {@code false}
*/
public static boolean isNullOrEmpty(@Nullable byte[] arr) {
public static boolean isEmpty(@Nullable byte[] arr) {
return arr == null || arr.length == 0;
}
// isNullOrEmpty - short
// isEmpty - short
/**
* 检查给定数组是否为空
*
* @param arr 待检查的数组可以为 {@code null}
* @return 如果数组为 {@code null} 或长度为 0则返回 {@code true}否则返回 {@code false}
*/
public static boolean isNullOrEmpty(@Nullable short[] arr) {
public static boolean isEmpty(@Nullable short[] arr) {
return arr == null || arr.length == 0;
}
// isNullOrEmpty - int
// isEmpty - int
/**
* 检查给定数组是否为空
*
* @param arr 待检查的数组可以为 {@code null}
* @return 如果数组为 {@code null} 或长度为 0则返回 {@code true}否则返回 {@code false}
*/
public static boolean isNullOrEmpty(@Nullable int[] arr) {
public static boolean isEmpty(@Nullable int[] arr) {
return arr == null || arr.length == 0;
}
// isNullOrEmpty - long
// isEmpty - long
/**
* 检查给定数组是否为空
*
* @param arr 待检查的数组可以为 {@code null}
* @return 如果数组为 {@code null} 或长度为 0则返回 {@code true}否则返回 {@code false}
*/
public static boolean isNullOrEmpty(@Nullable long[] arr) {
public static boolean isEmpty(@Nullable long[] arr) {
return arr == null || arr.length == 0;
}
// isNullOrEmpty - float
// isEmpty - float
/**
* 检查给定数组是否为空
*
* @param arr 待检查的数组可以为 {@code null}
* @return 如果数组为 {@code null} 或长度为 0则返回 {@code true}否则返回 {@code false}
*/
public static boolean isNullOrEmpty(@Nullable float[] arr) {
public static boolean isEmpty(@Nullable float[] arr) {
return arr == null || arr.length == 0;
}
// isNullOrEmpty - double
// isEmpty - double
/**
* 检查给定数组是否为空
*
* @param arr 待检查的数组可以为 {@code null}
* @return 如果数组为 {@code null} 或长度为 0则返回 {@code true}否则返回 {@code false}
*/
public static boolean isNullOrEmpty(@Nullable double[] arr) {
public static boolean isEmpty(@Nullable double[] arr) {
return arr == null || arr.length == 0;
}
@@ -259,7 +262,7 @@ public class ArrayTools {
* @throws IllegalArgumentException 当参数为空时抛出
*/
public static <T> boolean isAllElementsNotNull(final T[] arr) {
AssertTools.checkArgument(arr != null, "The array cannot be null.");
checkArgument(arr != null, "The array cannot be null.");
return Arrays.stream(arr).allMatch(Objects::nonNull);
}
@@ -489,10 +492,10 @@ public class ArrayTools {
* @return 重复后的数组
*/
public static char[] repeat(char[] arr, int times, int maxLength) {
AssertTools.checkArgument(Objects.nonNull(arr));
AssertTools.checkArgument(times >= 0,
checkArgumentNotNull(arr);
checkArgument(times >= 0,
"The number of times must be greater than or equal to zero");
AssertTools.checkArgument(maxLength >= 0,
checkArgument(maxLength >= 0,
"The max length must be greater than or equal to zero");
if (times == 0) {
return EMPTY_CHAR_ARRAY;
@@ -524,10 +527,10 @@ public class ArrayTools {
* @return 重复后的数组
*/
public static byte[] repeat(byte[] arr, int times, int maxLength) {
AssertTools.checkArgument(Objects.nonNull(arr));
AssertTools.checkArgument(times >= 0,
checkArgumentNotNull(arr);
checkArgument(times >= 0,
"The number of times must be greater than or equal to zero");
AssertTools.checkArgument(maxLength >= 0,
checkArgument(maxLength >= 0,
"The max length must be greater than or equal to zero");
if (times == 0) {
return EMPTY_BYTE_ARRAY;
@@ -559,10 +562,10 @@ public class ArrayTools {
* @return 重复后的数组
*/
public static short[] repeat(short[] arr, int times, int maxLength) {
AssertTools.checkArgument(Objects.nonNull(arr));
AssertTools.checkArgument(times >= 0,
checkArgumentNotNull(arr);
checkArgument(times >= 0,
"The number of times must be greater than or equal to zero");
AssertTools.checkArgument(maxLength >= 0,
checkArgument(maxLength >= 0,
"The max length must be greater than or equal to zero");
if (times == 0) {
return EMPTY_SHORT_ARRAY;
@@ -594,10 +597,10 @@ public class ArrayTools {
* @return 重复后的数组
*/
public static int[] repeat(int[] arr, int times, int maxLength) {
AssertTools.checkArgument(Objects.nonNull(arr));
AssertTools.checkArgument(times >= 0,
checkArgumentNotNull(arr);
checkArgument(times >= 0,
"The number of times must be greater than or equal to zero");
AssertTools.checkArgument(maxLength >= 0,
checkArgument(maxLength >= 0,
"The max length must be greater than or equal to zero");
if (times == 0) {
return EMPTY_INT_ARRAY;
@@ -629,10 +632,10 @@ public class ArrayTools {
* @return 重复后的数组
*/
public static long[] repeat(long[] arr, int times, int maxLength) {
AssertTools.checkArgument(Objects.nonNull(arr));
AssertTools.checkArgument(times >= 0,
checkArgumentNotNull(arr);
checkArgument(times >= 0,
"The number of times must be greater than or equal to zero");
AssertTools.checkArgument(maxLength >= 0,
checkArgument(maxLength >= 0,
"The max length must be greater than or equal to zero");
if (times == 0) {
return EMPTY_LONG_ARRAY;
@@ -664,10 +667,10 @@ public class ArrayTools {
* @return 重复后的数组
*/
public static float[] repeat(float[] arr, int times, int maxLength) {
AssertTools.checkArgument(Objects.nonNull(arr));
AssertTools.checkArgument(times >= 0,
checkArgumentNotNull(arr);
checkArgument(times >= 0,
"The number of times must be greater than or equal to zero");
AssertTools.checkArgument(maxLength >= 0,
checkArgument(maxLength >= 0,
"The max length must be greater than or equal to zero");
if (times == 0) {
return EMPTY_FLOAT_ARRAY;
@@ -699,10 +702,10 @@ public class ArrayTools {
* @return 重复后的数组
*/
public static double[] repeat(double[] arr, int times, int maxLength) {
AssertTools.checkArgument(Objects.nonNull(arr));
AssertTools.checkArgument(times >= 0,
checkArgumentNotNull(arr);
checkArgument(times >= 0,
"The number of times must be greater than or equal to zero");
AssertTools.checkArgument(maxLength >= 0,
checkArgument(maxLength >= 0,
"The max length must be greater than or equal to zero");
if (times == 0) {
return EMPTY_DOUBLE_ARRAY;
@@ -748,7 +751,7 @@ public class ArrayTools {
* @param values 填充内容
*/
public static void fill(char[] a, int fromIndex, int toIndex, @Nullable char[] values) {
AssertTools.checkArgument(Objects.nonNull(a));
checkArgumentNotNull(a);
if (values == null || values.length == 0) {
return;
}
@@ -791,7 +794,7 @@ public class ArrayTools {
* @param values 填充内容
*/
public static void fill(byte[] a, int fromIndex, int toIndex, @Nullable byte[] values) {
AssertTools.checkArgument(Objects.nonNull(a));
checkArgumentNotNull(a);
if (values == null || values.length == 0) {
return;
}
@@ -834,7 +837,7 @@ public class ArrayTools {
* @param values 填充内容
*/
public static void fill(short[] a, int fromIndex, int toIndex, @Nullable short[] values) {
AssertTools.checkArgument(Objects.nonNull(a));
checkArgumentNotNull(a);
if (values == null || values.length == 0) {
return;
}
@@ -877,7 +880,7 @@ public class ArrayTools {
* @param values 填充内容
*/
public static void fill(int[] a, int fromIndex, int toIndex, @Nullable int[] values) {
AssertTools.checkArgument(Objects.nonNull(a));
checkArgumentNotNull(a);
if (values == null || values.length == 0) {
return;
}
@@ -920,7 +923,7 @@ public class ArrayTools {
* @param values 填充内容
*/
public static void fill(long[] a, int fromIndex, int toIndex, @Nullable long[] values) {
AssertTools.checkArgument(Objects.nonNull(a));
checkArgumentNotNull(a);
if (values == null || values.length == 0) {
return;
}
@@ -963,7 +966,7 @@ public class ArrayTools {
* @param values 填充内容
*/
public static void fill(float[] a, int fromIndex, int toIndex, @Nullable float[] values) {
AssertTools.checkArgument(Objects.nonNull(a));
checkArgumentNotNull(a);
if (values == null || values.length == 0) {
return;
}
@@ -1006,7 +1009,7 @@ public class ArrayTools {
* @param values 填充内容
*/
public static void fill(double[] a, int fromIndex, int toIndex, @Nullable double[] values) {
AssertTools.checkArgument(Objects.nonNull(a));
checkArgumentNotNull(a);
if (values == null || values.length == 0) {
return;
}
@@ -1061,7 +1064,7 @@ public class ArrayTools {
* @param values 填充内容
*/
private static <T> void fillInternal(T[] a, int fromIndex, int toIndex, @Nullable T[] values) {
AssertTools.checkArgument(Objects.nonNull(a));
checkArgumentNotNull(a);
if (values == null || values.length == 0) {
return;
}
@@ -1088,7 +1091,7 @@ public class ArrayTools {
// #region - indexOf
public static <T> int indexOf(@Nullable T[] arr, Predicate<? super T> predicate) {
AssertTools.checkNotNull(predicate);
checkNotNull(predicate);
if (arr == null || arr.length == 0) {
return NOT_FOUND_INDEX;
}
@@ -1193,7 +1196,7 @@ public class ArrayTools {
// #region - lastIndexOf
public static <T> int lastIndexOf(@Nullable T[] arr, Predicate<? super T> predicate) {
AssertTools.checkNotNull(predicate);
checkNotNull(predicate);
if (arr == null || arr.length == 0) {
return NOT_FOUND_INDEX;
}

View File

@@ -0,0 +1,684 @@
/*
* 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.util;
import java.util.Optional;
import java.util.function.Supplier;
import javax.annotation.Nullable;
import xyz.zhouxy.plusone.commons.exception.DataNotExistsException;
import xyz.zhouxy.plusone.commons.exception.system.DataOperationResultException;
/**
* 断言工具
*
* <p>
* 本工具类不封装过多判断逻辑,鼓励充分使用项目中的工具类进行逻辑判断。
*
* <pre>
* checkArgument(StringUtils.hasText(str), "The argument cannot be blank.");
* checkState(ArrayUtils.isNotEmpty(result), "The result cannot be empty.");
* checkCondition(!CollectionUtils.isEmpty(roles),
* () -> new InvalidInputException("The roles cannot be empty."));
* checkCondition(RegexTools.matches(email, PatternConsts.EMAIL),
* "must be a well-formed email address");
* </pre>
*
* @author ZhouXY108 <luquanlion@outlook.com>
*/
public class AssertTools {
// ================================
// #region - Argument
// ================================
/**
* 检查实参
*
* @param condition 判断参数是否符合条件的结果
* @throws IllegalArgumentException 当条件不满足时抛出
*/
public static void checkArgument(boolean condition) {
if (!condition) {
throw new IllegalArgumentException();
}
}
/**
* 检查实参
*
* @param condition 判断参数是否符合条件的结果
* @param errorMessage 异常信息
* @throws IllegalArgumentException 当条件不满足时抛出
*/
public static void checkArgument(boolean condition, @Nullable String errorMessage) {
if (!condition) {
throw new IllegalArgumentException(errorMessage);
}
}
/**
* 检查实参
*
* @param condition 判断参数是否符合条件的结果
* @param errorMessageSupplier 异常信息
* @throws IllegalArgumentException 当条件不满足时抛出
*/
public static void checkArgument(boolean condition, Supplier<String> errorMessageSupplier) {
if (!condition) {
throw new IllegalArgumentException(errorMessageSupplier.get());
}
}
/**
* 检查实参
*
* @param condition 判断参数是否符合条件的结果
* @param errorMessageTemplate 异常信息模板
* @param errorMessageArgs 异常信息参数
* @throws IllegalArgumentException 当条件不满足时抛出
*/
public static void checkArgument(boolean condition,
String errorMessageTemplate, Object... errorMessageArgs) {
if (!condition) {
throw new IllegalArgumentException(String.format(errorMessageTemplate, errorMessageArgs));
}
}
// ================================
// #endregion - Argument
// ================================
// ================================
// #region - ArgumentNotNull
// ================================
/**
* 判断入参不为 {@code null}
*
* @param <T> 入参类型
* @param obj 入参
* @throws IllegalArgumentException 当 {@code obj} 为 {@code null} 时抛出
*/
public static <T> T checkArgumentNotNull(@Nullable T obj) {
if (obj == null) {
throw new IllegalArgumentException();
}
return obj;
}
/**
* 判断入参不为 {@code null}
*
* @param <T> 入参类型
* @param obj 入参
* @param errorMessage 异常信息
* @throws IllegalArgumentException 当 {@code obj} 为 {@code null} 时抛出
*/
public static <T> T checkArgumentNotNull(@Nullable T obj, String errorMessage) {
if (obj == null) {
throw new IllegalArgumentException(errorMessage);
}
return obj;
}
/**
* 判断入参不为 {@code null}
*
* @param <T> 入参类型
* @param obj 入参
* @param errorMessageSupplier 异常信息
* @throws IllegalArgumentException 当 {@code obj} 为 {@code null} 时抛出
*/
public static <T> T checkArgumentNotNull(@Nullable T obj, Supplier<String> errorMessageSupplier) {
if (obj == null) {
throw new IllegalArgumentException(errorMessageSupplier.get());
}
return obj;
}
/**
* 判断入参不为 {@code null}
*
* @param <T> 入参类型
* @param obj 入参
* @param errorMessageTemplate 异常信息模板
* @param errorMessageArgs 异常信息参数
* @throws IllegalArgumentException 当 {@code obj} 为 {@code null} 时抛出
*/
public static <T> T checkArgumentNotNull(@Nullable T obj,
String errorMessageTemplate, Object... errorMessageArgs) {
if (obj == null) {
throw new IllegalArgumentException(String.format(errorMessageTemplate, errorMessageArgs));
}
return obj;
}
// ================================
// #endregion - ArgumentNotNull
// ================================
// ================================
// #region - State
// ================================
/**
* 检查状态
*
* @param condition 判断状态是否符合条件的结果
* @throws IllegalStateException 当条件不满足时抛出
*/
public static void checkState(boolean condition) {
if (!condition) {
throw new IllegalStateException();
}
}
/**
* 检查状态
*
* @param condition 判断状态是否符合条件的结果
* @param errorMessage 异常信息
* @throws IllegalStateException 当条件不满足时抛出
*/
public static void checkState(boolean condition, @Nullable String errorMessage) {
if (!condition) {
throw new IllegalStateException(errorMessage);
}
}
/**
* 检查状态
*
* @param condition 判断状态是否符合条件的结果
* @param errorMessageSupplier 异常信息
* @throws IllegalStateException 当条件不满足时抛出
*/
public static void checkState(boolean condition, Supplier<String> errorMessageSupplier) {
if (!condition) {
throw new IllegalStateException(errorMessageSupplier.get());
}
}
/**
* 检查状态
*
* @param condition 判断状态是否符合条件的结果
* @param errorMessageTemplate 异常信息模板
* @param errorMessageArgs 异常信息参数
* @throws IllegalStateException 当条件不满足时抛出
*/
public static void checkState(boolean condition,
String errorMessageTemplate, Object... errorMessageArgs) {
if (!condition) {
throw new IllegalStateException(String.format(errorMessageTemplate, errorMessageArgs));
}
}
// ================================
// #endregion - State
// ================================
// ================================
// #region - NotNull
// ================================
/**
* 判空
*
* @param <T> 入参类型
* @param obj 入参
* @throws NullPointerException 当 {@code obj} 为 {@code null} 时抛出
*/
public static <T> void checkNotNull(@Nullable T obj) {
if (obj == null) {
throw new NullPointerException();
}
}
/**
* 判空
*
* @param <T> 入参类型
* @param obj 入参
* @param errorMessage 异常信息
* @throws NullPointerException 当 {@code obj} 为 {@code null} 时抛出
*/
public static <T> void checkNotNull(@Nullable T obj, String errorMessage) {
if (obj == null) {
throw new NullPointerException(errorMessage);
}
}
/**
* 判空
*
* @param <T> 入参类型
* @param obj 入参
* @param errorMessageSupplier 异常信息
* @throws NullPointerException 当 {@code obj} 为 {@code null} 时抛出
*/
public static <T> void checkNotNull(@Nullable T obj, Supplier<String> errorMessageSupplier) {
if (obj == null) {
throw new NullPointerException(errorMessageSupplier.get());
}
}
/**
* 判空
*
* @param <T> 入参类型
* @param obj 入参
* @param errorMessageTemplate 异常信息模板
* @param errorMessageArgs 异常信息参数
* @throws NullPointerException 当 {@code obj} 为 {@code null} 时抛出
*/
public static <T> void checkNotNull(@Nullable T obj,
String errorMessageTemplate, Object... errorMessageArgs) {
if (obj == null) {
throw new NullPointerException(String.format(errorMessageTemplate, errorMessageArgs));
}
}
// ================================
// #endregion - NotNull
// ================================
// ================================
// #region - Exists
// ================================
/**
* 检查数据是否存在
*
* @param <T> 入参类型
* @param obj 入参
* @return 如果 {@code obj} 存在,返回 {@code obj} 本身
* @throws DataNotExistsException 当 {@code obj} 不存在时抛出
*/
public static <T> T checkExists(@Nullable T obj)
throws DataNotExistsException {
if (obj == null) {
throw new DataNotExistsException();
}
return obj;
}
/**
* 检查数据是否存在
*
* @param <T> 入参类型
* @param obj 入参
* @param errorMessage 异常信息
* @return 如果 {@code obj} 存在,返回 {@code obj} 本身
* @throws DataNotExistsException 当 {@code obj} 不存在时抛出
*/
public static <T> T checkExists(@Nullable T obj, String errorMessage)
throws DataNotExistsException {
if (obj == null) {
throw new DataNotExistsException(errorMessage);
}
return obj;
}
/**
* 检查数据是否存在
*
* @param <T> 入参类型
* @param obj 入参
* @param errorMessageSupplier 异常信息
* @return 如果 {@code obj} 存在,返回 {@code obj} 本身
* @throws DataNotExistsException 当 {@code obj} 不存在时抛出
*/
public static <T> T checkExists(@Nullable T obj, Supplier<String> errorMessageSupplier)
throws DataNotExistsException {
if (obj == null) {
throw new DataNotExistsException(errorMessageSupplier.get());
}
return obj;
}
/**
* 检查数据是否存在
*
* @param <T> 入参类型
* @param obj 入参
* @param errorMessageTemplate 异常信息模板
* @param errorMessageArgs 异常信息参数
* @return 如果 {@code obj} 存在,返回 {@code obj} 本身
* @throws DataNotExistsException 当 {@code obj} 不存在时抛出
*/
public static <T> T checkExists(@Nullable T obj,
String errorMessageTemplate, Object... errorMessageArgs)
throws DataNotExistsException {
if (obj == null) {
throw new DataNotExistsException(String.format(errorMessageTemplate, errorMessageArgs));
}
return obj;
}
/**
* 检查数据是否存在
*
* @param <T> 入参类型
* @param optional 入参
* @return 如果 {@code optional} 存在,返回 {@code optional} 包含的值
* @throws DataNotExistsException 当 {@code optional} 的值不存在时抛出
*/
public static <T> T checkExists(Optional<T> optional)
throws DataNotExistsException {
if (!optional.isPresent()) {
throw new DataNotExistsException();
}
return optional.get();
}
/**
* 检查数据是否存在
*
* @param <T> 入参类型
* @param optional 入参
* @param errorMessage 异常信息
* @return 如果 {@code optional} 存在,返回 {@code optional} 包含的值
* @throws DataNotExistsException 当 {@code optional} 的值不存在时抛出
*/
public static <T> T checkExists(Optional<T> optional, String errorMessage)
throws DataNotExistsException {
if (!optional.isPresent()) {
throw new DataNotExistsException(errorMessage);
}
return optional.get();
}
/**
* 检查数据是否存在
*
* @param <T> 入参类型
* @param optional 入参
* @param errorMessageSupplier 异常信息
* @return 如果 {@code optional} 存在,返回 {@code optional} 包含的值
* @throws DataNotExistsException 当 {@code optional} 的值不存在时抛出
*/
public static <T> T checkExists(Optional<T> optional, Supplier<String> errorMessageSupplier)
throws DataNotExistsException {
if (!optional.isPresent()) {
throw new DataNotExistsException(errorMessageSupplier.get());
}
return optional.get();
}
/**
* 检查数据是否存在
*
* @param <T> 入参类型
* @param optional 入参
* @param errorMessageTemplate 异常信息模板
* @param errorMessageArgs 异常信息参数
* @return 如果 {@code optional} 存在,返回 {@code optional} 包含的值
* @throws DataNotExistsException 当 {@code optional} 的值不存在时抛出
*/
public static <T> T checkExists(Optional<T> optional,
String errorMessageTemplate, Object... errorMessageArgs)
throws DataNotExistsException {
if (!optional.isPresent()) {
throw new DataNotExistsException(String.format(errorMessageTemplate, errorMessageArgs));
}
return optional.get();
}
// ================================
// #endregion - Exists
// ================================
// ================================
// #region - AffectedRows
// ================================
/**
* 当影响的数据量与预计不同时抛出 {@link DataOperationResultException}。
*
* @param expected 预期影响的行数
* @param actualRowCount 实际影响的行数
*/
public static void checkAffectedRows(int expected, int actualRowCount) {
if (expected != actualRowCount) {
throw new DataOperationResultException(expected, actualRowCount);
}
}
/**
* 当影响的数据量与预计不同时抛出 {@link DataOperationResultException}。
*
* @param expected 预期影响的行数
* @param actualRowCount 实际影响的行数
* @param errorMessage 异常信息
*/
public static void checkAffectedRows(int expected, int actualRowCount,
@Nullable String errorMessage) {
if (expected != actualRowCount) {
throw new DataOperationResultException(expected, actualRowCount, errorMessage);
}
}
/**
* 当影响的数据量与预计不同时抛出 {@link DataOperationResultException}。
*
* @param expected 预期影响的行数
* @param actualRowCount 实际影响的行数
* @param errorMessageSupplier 异常信息
*/
public static void checkAffectedRows(int expected, int actualRowCount,
Supplier<String> errorMessageSupplier) {
if (expected != actualRowCount) {
throw new DataOperationResultException(expected, actualRowCount, errorMessageSupplier.get());
}
}
/**
* 当影响的数据量与预计不同时抛出 {@link DataOperationResultException}。
*
* @param expected 预期影响的行数
* @param actualRowCount 实际影响的行数
* @param errorMessageTemplate 异常信息模板
* @param errorMessageArgs 异常信息参数
*/
public static void checkAffectedRows(int expected, int actualRowCount,
String errorMessageTemplate, Object... errorMessageArgs) {
if (expected != actualRowCount) {
throw new DataOperationResultException(expected, actualRowCount,
String.format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* 当影响的数据量与预计不同时抛出 {@link DataOperationResultException}。
*
* @param expected 预期影响的行数
* @param actualRowCount 实际影响的行数
*/
public static void checkAffectedRows(long expected, long actualRowCount) {
if (expected != actualRowCount) {
throw new DataOperationResultException(expected, actualRowCount);
}
}
/**
* 当影响的数据量与预计不同时抛出 {@link DataOperationResultException}。
*
* @param expected 预期影响的行数
* @param actualRowCount 实际影响的行数
* @param errorMessage 异常信息
*/
public static void checkAffectedRows(long expected, long actualRowCount,
@Nullable String errorMessage) {
if (expected != actualRowCount) {
throw new DataOperationResultException(expected, actualRowCount, errorMessage);
}
}
/**
* 当影响的数据量与预计不同时抛出 {@link DataOperationResultException}。
*
* @param expected 预期影响的行数
* @param actualRowCount 实际影响的行数
* @param errorMessageSupplier 异常信息
*/
public static void checkAffectedRows(long expected, long actualRowCount,
Supplier<String> errorMessageSupplier) {
if (expected != actualRowCount) {
throw new DataOperationResultException(expected, actualRowCount, errorMessageSupplier.get());
}
}
/**
* 当影响的数据量与预计不同时抛出 {@link DataOperationResultException}。
*
* @param expected 预期影响的行数
* @param actualRowCount 实际影响的行数
* @param errorMessageTemplate 异常信息模板
* @param errorMessageArgs 异常信息参数
*/
public static void checkAffectedRows(long expected, long actualRowCount,
String errorMessageTemplate, Object... errorMessageArgs) {
if (expected != actualRowCount) {
throw new DataOperationResultException(expected, actualRowCount,
String.format(errorMessageTemplate, errorMessageArgs));
}
}
/**
* 当影响的数据量不为 1 时抛出 {@link DataOperationResultException}。
*
* @param actualRowCount 实际影响的行数
*/
public static void checkAffectedOneRow(int actualRowCount) {
checkAffectedRows(1, actualRowCount);
}
/**
* 当影响的数据量不为 1 时抛出 {@link DataOperationResultException}。
*
* @param actualRowCount 实际影响的行数
* @param errorMessage 异常信息
*/
public static void checkAffectedOneRow(int actualRowCount, String errorMessage) {
checkAffectedRows(1, actualRowCount, errorMessage);
}
/**
* 当影响的数据量不为 1 时抛出 {@link DataOperationResultException}。
*
* @param actualRowCount 实际影响的行数
* @param errorMessageSupplier 异常信息
*/
public static void checkAffectedOneRow(int actualRowCount, Supplier<String> errorMessageSupplier) {
checkAffectedRows(1, actualRowCount, errorMessageSupplier);
}
/**
* 当影响的数据量不为 1 时抛出 {@link DataOperationResultException}。
*
* @param actualRowCount 实际影响的行数
* @param errorMessageTemplate 异常信息模板
* @param errorMessageArgs 异常信息参数
*/
public static void checkAffectedOneRow(int actualRowCount,
String errorMessageTemplate, Object... errorMessageArgs) {
checkAffectedRows(1, actualRowCount, errorMessageTemplate, errorMessageArgs);
}
/**
* 当影响的数据量不为 1 时抛出 {@link DataOperationResultException}。
*
* @param result 实际影响的数据量
*/
public static void checkAffectedOneRow(long result) {
checkAffectedRows(1L, result);
}
/**
* 当影响的数据量不为 1 时抛出 {@link DataOperationResultException}。
*
* @param actualRowCount 实际影响的行数
* @param errorMessage 异常信息
*/
public static void checkAffectedOneRow(long actualRowCount, String errorMessage) {
checkAffectedRows(1L, actualRowCount, errorMessage);
}
/**
* 当影响的数据量不为 1 时抛出 {@link DataOperationResultException}。
*
* @param actualRowCount 实际影响的行数
* @param errorMessageSupplier 异常信息
*/
public static void checkAffectedOneRow(long actualRowCount, Supplier<String> errorMessageSupplier) {
checkAffectedRows(1L, actualRowCount, errorMessageSupplier);
}
/**
* 当影响的数据量不为 1 时抛出 {@link DataOperationResultException}。
*
* @param actualRowCount 实际影响的行数
* @param errorMessageTemplate 异常信息模板
* @param errorMessageArgs 异常信息参数
*/
public static void checkAffectedOneRow(long actualRowCount,
String errorMessageTemplate, Object... errorMessageArgs) {
checkAffectedRows(1L, actualRowCount, errorMessageTemplate, errorMessageArgs);
}
// ================================
// #endregion - AffectedRows
// ================================
// ================================
// #region - Condition
// ================================
/**
* 当条件不满足时抛出异常。
*
* @param <T> 异常类型
* @param condition 条件
* @param e 异常
* @throws T 当条件不满足时抛出异常
*/
public static <T extends Exception> void checkCondition(boolean condition, Supplier<T> e)
throws T {
if (!condition) {
throw e.get();
}
}
// ================================
// #endregion
// ================================
// ================================
// #region - constructor
// ================================
private AssertTools() {
throw new IllegalStateException("Utility class");
}
// ================================
// #endregion
// ================================
}

View File

@@ -16,6 +16,8 @@
package xyz.zhouxy.plusone.commons.util;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkNotNull;
import java.math.BigDecimal;
import javax.annotation.Nonnull;
@@ -28,9 +30,8 @@ import xyz.zhouxy.plusone.commons.annotation.StaticFactoryMethod;
*
* <p>
* BigDecimal 工具类
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
public class BigDecimals {
@@ -54,8 +55,8 @@ public class BigDecimals {
* @return {@code a} 大于 {@code b} 时返回 {@code true}
*/
public static boolean gt(BigDecimal a, BigDecimal b) {
AssertTools.checkNotNull(a, "Parameter could not be null.");
AssertTools.checkNotNull(b, "Parameter could not be null.");
checkNotNull(a, "Parameter could not be null.");
checkNotNull(b, "Parameter could not be null.");
return (a != b) && (a.compareTo(b) > 0);
}
@@ -67,8 +68,8 @@ public class BigDecimals {
* @return {@code a} 大于等于 {@code b} 时返回 {@code true}
*/
public static boolean ge(BigDecimal a, BigDecimal b) {
AssertTools.checkNotNull(a, "Parameter could not be null.");
AssertTools.checkNotNull(b, "Parameter could not be null.");
checkNotNull(a, "Parameter could not be null.");
checkNotNull(b, "Parameter could not be null.");
return (a == b) || (a.compareTo(b) >= 0);
}
@@ -80,8 +81,8 @@ public class BigDecimals {
* @return {@code a} 小于 {@code b} 时返回 {@code true}
*/
public static boolean lt(BigDecimal a, BigDecimal b) {
AssertTools.checkNotNull(a, "Parameter could not be null.");
AssertTools.checkNotNull(b, "Parameter could not be null.");
checkNotNull(a, "Parameter could not be null.");
checkNotNull(b, "Parameter could not be null.");
return (a != b) && (a.compareTo(b) < 0);
}
@@ -93,8 +94,8 @@ public class BigDecimals {
* @return {@code a} 小于等于 {@code b} 时返回 {@code true}
*/
public static boolean le(BigDecimal a, BigDecimal b) {
AssertTools.checkNotNull(a, "Parameter could not be null.");
AssertTools.checkNotNull(b, "Parameter could not be null.");
checkNotNull(a, "Parameter could not be null.");
checkNotNull(b, "Parameter could not be null.");
return (a == b) || (a.compareTo(b) <= 0);
}
@@ -105,7 +106,7 @@ public class BigDecimals {
* @return 求和结果
*/
public static BigDecimal sum(final BigDecimal... numbers) {
if (ArrayTools.isNullOrEmpty(numbers)) {
if (ArrayTools.isEmpty(numbers)) {
return BigDecimal.ZERO;
}
BigDecimal result = BigDecimals.nullToZero(numbers[0]);

View File

@@ -27,11 +27,11 @@ import java.time.Year;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.chrono.IsoChronology;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import com.google.common.collect.BoundType;
import com.google.common.collect.Range;
import xyz.zhouxy.plusone.commons.time.Quarter;
@@ -40,7 +40,7 @@ import xyz.zhouxy.plusone.commons.time.YearQuarter;
/**
* 日期时间工具类
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
public class DateTimeTools {
@@ -215,7 +215,6 @@ public class DateTimeTools {
* <p>
* 传入不同 {@link ZoneId}获取到的 {@link ZonedDateTime} 对象实际上还是同一时间戳
* 只是不同时区的表示
* </p>
*
* @param timeMillis 时间戳
* @param zone 时区
@@ -230,7 +229,6 @@ public class DateTimeTools {
* <p>
* 传入不同 {@link ZoneId}获取到的 {@link ZonedDateTime} 对象实际上还是同一时间戳
* 只是不同时区的表示
* </p>
*
* @param dateTime {@link Date} 对象
* @param zone 时区
@@ -245,7 +243,6 @@ public class DateTimeTools {
* <p>
* 传入不同 {@link ZoneId}获取到的 {@link ZonedDateTime} 对象实际上表示的还是还是同一时间戳的时间
* 只是不同时区的表示
* </p>
*
* @param dateTime {@link Date} 对象
* @param timeZone 时区
@@ -377,258 +374,6 @@ public class DateTimeTools {
// #endregion
// ================================
// ================================
// #region - toJodaInstant
// ================================
/**
* {@link java.time.Instant} 转换为 {@link org.joda.time.Instant}
*
* @param instant {@link java.time.Instant} 对象
* @return {@link org.joda.time.Instant} 对象
*/
public static org.joda.time.Instant toJodaInstant(java.time.Instant instant) {
return new org.joda.time.Instant(instant.toEpochMilli());
}
/**
* {@link java.time.ZonedDateTime} 转换为 {@link org.joda.time.Instant}
*
* @param zonedDateTime {@link java.time.ZonedDateTime} 对象
* @return {@link org.joda.time.Instant} 对象
*/
public static org.joda.time.Instant toJodaInstant(java.time.ZonedDateTime zonedDateTime) {
return toJodaInstant(zonedDateTime.toInstant());
}
/**
* 计算指定时区的地区时间对应的时间戳结果为 {@link org.joda.time.Instant} 对象
*
* @param localDateTime {@link java.time.LocalDateTime} 对象
* @param zone 时区
* @return {@link org.joda.time.Instant} 对象
*/
public static org.joda.time.Instant toJodaInstant(java.time.LocalDateTime localDateTime, java.time.ZoneId zone) {
return toJodaInstant(java.time.ZonedDateTime.of(localDateTime, zone));
}
// ================================
// #endregion
// ================================
// ================================
// #region - toJavaInstant
// ================================
/**
* {@link org.joda.time.Instant} 对象转换为 {@link java.time.Instant} 对象
*
* @param instant {@link org.joda.time.Instant} 对象
* @return {@link java.time.Instant} 对象
*/
public static java.time.Instant toJavaInstant(org.joda.time.Instant instant) {
return toInstant(instant.getMillis());
}
/**
* joda-time 中的 {@link org.joda.time.DateTime} 对象转换为 Java
* {@link java.time.Instant} 对象
*
* @param dateTime joda-time 中表示日期时间的 {@link org.joda.time.DateTime} 对象
* @return Java 表示时间戳的 {@link java.time.Instant} 对象
*/
public static java.time.Instant toJavaInstant(org.joda.time.DateTime dateTime) {
return toInstant(dateTime.getMillis());
}
/**
* joda-time 中的 {@link org.joda.time.LocalDateTime} 对象和
* {@link org.joda.time.DateTimeZone} 对象
* 转换为 Java 中的 {@link java.time.Instant} 对象
*
* @param localDateTime
* @param zone
* @return
*/
public static java.time.Instant toJavaInstant(
org.joda.time.LocalDateTime localDateTime,
org.joda.time.DateTimeZone zone) {
return toJavaInstant(localDateTime.toDateTime(zone));
}
// ================================
// #endregion
// ================================
// ================================
// #region - toJodaDateTime
// ================================
/**
* Java 中表示日期时间的 {@link java.time.ZonedDateTime} 对象
* 转换为 joda-time {@link org.joda.time.DateTime} 对象
*
* @param zonedDateTime 日期时间
* @return joda-time 中对应的 {@link org.joda.time.DateTime} 对象
*/
public static org.joda.time.DateTime toJodaDateTime(java.time.ZonedDateTime zonedDateTime) {
org.joda.time.DateTimeZone zone = org.joda.time.DateTimeZone.forID(zonedDateTime.getZone().getId());
return toJodaInstant(zonedDateTime.toInstant()).toDateTime(zone);
}
/**
* java.time 中表示日期时间的 {@link java.time.LocalDateTime} 对象和表示时区的
* {@link java.time.ZoneId} 对象转换为 joda-time 中对应的 {@link org.joda.time.DateTime}
* 对象
* 转换为 joda-time 中对应的 {@link org.joda.time.DateTime} 对象
*
* @param localDateTime 日期时间
* @param zone 时区
* @return joda-time 中对应的 {@link org.joda.time.DateTime} 对象
*/
public static org.joda.time.DateTime toJodaDateTime(
java.time.LocalDateTime localDateTime,
java.time.ZoneId zone) {
org.joda.time.DateTimeZone dateTimeZone = toJodaZone(zone);
return toJodaInstant(ZonedDateTime.of(localDateTime, zone).toInstant()).toDateTime(dateTimeZone);
}
/**
* 计算时间戳在指定时区对应的时间结果使用 {@link org.joda.time.DateTime} 表示
*
* @param instant java.time 中的时间戳
* @param zone java.time 中的时区
* @return joda-time 中带时区的日期时间
*/
public static org.joda.time.DateTime toJodaDateTime(
java.time.Instant instant,
java.time.ZoneId zone) {
org.joda.time.DateTimeZone dateTimeZone = toJodaZone(zone);
return toJodaInstant(instant).toDateTime(dateTimeZone);
}
// ================================
// #endregion
// ================================
// ================================
// #region - toZonedDateTime
// ================================
/**
* joda-time 中带时区的日期时间转换为 java.time 中带时区的日期时间
*
* @param dateTime joda-time 中带时区的日期时间
* @return java.time 中带时区的日期时间
*/
public static java.time.ZonedDateTime toZonedDateTime(org.joda.time.DateTime dateTime) {
java.time.ZoneId zone = dateTime.getZone().toTimeZone().toZoneId();
return toJavaInstant(dateTime.toInstant()).atZone(zone);
}
/**
* joda-time 中的 {@link org.joda.time.LocalDateTime}
* {@link org.joda.time.DateTimeZone}
* 转换为 java.time 中的 {@link java.time.ZonedDateTime}
*
* @param localDateTime joda-time 中的地区时间
* @param dateTimeZone joda-time 中的时区
* @return java.time 中带时区的日期时间
*/
public static java.time.ZonedDateTime toZonedDateTime(
org.joda.time.LocalDateTime localDateTime,
org.joda.time.DateTimeZone dateTimeZone) {
java.time.ZoneId zone = toJavaZone(dateTimeZone);
return toJavaInstant(localDateTime, dateTimeZone).atZone(zone);
}
/**
* 获取 joda-time 中的 {@link org.joda.time.Instant} 在指定时区的时间 Java 8+
* {@link java.time.ZonedDateTime} 表示
*
* @param instant joda-time 中的时间戳
* @param dateTimeZone joda-time 中的时区
* @return
*/
public static java.time.ZonedDateTime toZonedDateTime(
org.joda.time.Instant instant,
org.joda.time.DateTimeZone dateTimeZone) {
java.time.ZoneId zone = toJavaZone(dateTimeZone);
return toJavaInstant(instant).atZone(zone);
}
// ================================
// #endregion
// ================================
// ================================
// #region - toJodaLocalDateTime
// ================================
/**
* {@link java.time.LocalDateTime} 转换为 {@link org.joda.time.LocalDateTime}
*
* @param localDateTime Java 8 LocalDateTime
* @return joda-time LocalDateTime
*/
public static org.joda.time.LocalDateTime toJodaLocalDateTime(java.time.LocalDateTime localDateTime) {
java.time.ZoneId javaZone = java.time.ZoneId.systemDefault();
org.joda.time.DateTimeZone jodaZone = toJodaZone(javaZone);
return toJodaInstant(localDateTime, javaZone).toDateTime(jodaZone).toLocalDateTime();
}
// ================================
// #endregion
// ================================
// ================================
// #region - toJavaLocalDateTime
// ================================
/**
* {@link org.joda.time.LocalDateTime} 转换为 {@link java.time.LocalDateTime}
*
* @param localDateTime joda-time LocalDateTime
* @return Java 8 LocalDateTime
*/
public static java.time.LocalDateTime toJavaLocalDateTime(org.joda.time.LocalDateTime localDateTime) {
org.joda.time.DateTimeZone jodaZone = org.joda.time.DateTimeZone.getDefault();
java.time.ZoneId javaZone = toJavaZone(jodaZone);
return toJavaInstant(localDateTime, jodaZone).atZone(javaZone).toLocalDateTime();
}
// ================================
// #endregion
// ================================
// ================================
// #region - ZoneId <--> DateTimeZone
// ================================
/**
* 转换 Java API joda-time API 表示时区的对象
*
* @param jodaZone joda-time API 中表示时区的对象
* @return Java API 中表示时区的对象
*/
public static java.time.ZoneId toJavaZone(org.joda.time.DateTimeZone jodaZone) {
return jodaZone.toTimeZone().toZoneId();
}
/**
* 转换 Java API joda-time API 表示时区的对象
*
* @param zone Java API 中表示时区的对象
* @return joda-time API 中表示时区的对象
*/
public static org.joda.time.DateTimeZone toJodaZone(java.time.ZoneId zone) {
return org.joda.time.DateTimeZone.forID(zone.getId());
}
// ================================
// #endregion
// ================================
// ================================
// #region - YearQuarter & Quarter
// ================================
@@ -904,7 +649,7 @@ public class DateTimeTools {
// ================================
// ================================
// #region - others
// #region - range
// ================================
/**
@@ -928,6 +673,52 @@ public class DateTimeTools {
return Range.closedOpen(date.atStartOfDay(zone), startOfNextDate(date, zone));
}
/**
* 将指定日期范围转为日期时间范围
*
* @param dateRange 日期范围
* @return 对应的日期时间范围
*/
public static Range<LocalDateTime> toDateTimeRange(Range<LocalDate> dateRange) {
BoundType lowerBoundType = dateRange.lowerBoundType();
LocalDateTime lowerEndpoint = lowerBoundType == BoundType.CLOSED
? dateRange.lowerEndpoint().atStartOfDay()
: dateRange.lowerEndpoint().plusDays(1).atStartOfDay();
BoundType upperBoundType = dateRange.upperBoundType();
LocalDateTime upperEndpoint = upperBoundType == BoundType.CLOSED
? dateRange.upperEndpoint().plusDays(1).atStartOfDay()
: dateRange.upperEndpoint().atStartOfDay();
return Range.closedOpen(lowerEndpoint, upperEndpoint);
}
/**
* 将指定日期范围转为日期时间范围
*
* @param dateRange 日期范围
* @return 对应的日期时间范围
*/
public static Range<ZonedDateTime> toDateTimeRange(Range<LocalDate> dateRange, ZoneId zone) {
BoundType lowerBoundType = dateRange.lowerBoundType();
ZonedDateTime lowerEndpoint = lowerBoundType == BoundType.CLOSED
? dateRange.lowerEndpoint().atStartOfDay(zone)
: dateRange.lowerEndpoint().plusDays(1).atStartOfDay(zone);
BoundType upperBoundType = dateRange.upperBoundType();
ZonedDateTime upperEndpoint = upperBoundType == BoundType.CLOSED
? dateRange.upperEndpoint().plusDays(1).atStartOfDay(zone)
: dateRange.upperEndpoint().atStartOfDay(zone);
return Range.closedOpen(lowerEndpoint, upperEndpoint);
}
// ================================
// #endregion - range
// ================================
// ================================
// #region - others
// ================================
/**
* 判断指定年份是否为闰年
*
@@ -935,7 +726,7 @@ public class DateTimeTools {
* @return 指定年份是否为闰年
*/
public static boolean isLeapYear(int year) {
return IsoChronology.INSTANCE.isLeapYear(year);
return Year.isLeap(year);
}
// ================================

View File

@@ -16,6 +16,9 @@
package xyz.zhouxy.plusone.commons.util;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkCondition;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkNotNull;
import java.util.function.Supplier;
import javax.annotation.Nullable;
@@ -23,7 +26,7 @@ import javax.annotation.Nullable;
/**
* 枚举工具类
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
public final class EnumTools {
@@ -43,7 +46,7 @@ public final class EnumTools {
@Deprecated
private static <E extends Enum<?>> E valueOfInternal(Class<E> enumType, int ordinal) { // NOSONAR 该方法弃用但不删掉
E[] values = enumType.getEnumConstants();
AssertTools.checkCondition((ordinal >= 0 && ordinal < values.length),
checkCondition((ordinal >= 0 && ordinal < values.length),
() -> new EnumConstantNotPresentException(enumType, Integer.toString(ordinal)));
return values[ordinal];
}
@@ -59,7 +62,7 @@ public final class EnumTools {
*/
@Deprecated
public static <E extends Enum<?>> E valueOf(Class<E> enumType, int ordinal) { // NOSONAR 该方法弃用但不删掉
AssertTools.checkNotNull(enumType, "Enum type must not be null.");
checkNotNull(enumType, "Enum type must not be null.");
return valueOfInternal(enumType, ordinal);
}
@@ -76,7 +79,7 @@ public final class EnumTools {
@Deprecated
public static <E extends Enum<?>> E valueOf(Class<E> enumType, // NOSONAR 该方法弃用但不删掉
@Nullable Integer ordinal, @Nullable E defaultValue) {
AssertTools.checkNotNull(enumType);
checkNotNull(enumType);
return null == ordinal ? defaultValue : valueOfInternal(enumType, ordinal);
}
@@ -95,8 +98,8 @@ public final class EnumTools {
Class<E> enumType,
@Nullable Integer ordinal,
Supplier<E> defaultValue) {
AssertTools.checkNotNull(enumType);
AssertTools.checkNotNull(defaultValue);
checkNotNull(enumType);
checkNotNull(defaultValue);
return null == ordinal ? defaultValue.get() : valueOfInternal(enumType, ordinal);
}
@@ -112,7 +115,7 @@ public final class EnumTools {
@Deprecated
public static <E extends Enum<?>> E getValueOrDefault(Class<E> enumType, @Nullable Integer ordinal) { // NOSONAR 该方法弃用但不删掉
return getValueOrDefault(enumType, ordinal, () -> {
AssertTools.checkNotNull(enumType, "Enum type must not be null.");
checkNotNull(enumType, "Enum type must not be null.");
E[] values = enumType.getEnumConstants();
return values[0];
});
@@ -133,10 +136,10 @@ public final class EnumTools {
}
public static <E extends Enum<?>> Integer checkOrdinal(Class<E> enumType, Integer ordinal) {
AssertTools.checkNotNull(enumType, "Enum type must not be null.");
AssertTools.checkNotNull(ordinal, "Ordinal must not be null.");
checkNotNull(enumType, "Enum type must not be null.");
checkNotNull(ordinal, "Ordinal must not be null.");
E[] values = enumType.getEnumConstants();
AssertTools.checkCondition(ordinal >= 0 && ordinal < values.length,
checkCondition(ordinal >= 0 && ordinal < values.length,
() -> new EnumConstantNotPresentException(enumType, Integer.toString(ordinal)));
return ordinal;
}
@@ -151,7 +154,7 @@ public final class EnumTools {
*/
@Nullable
public static <E extends Enum<?>> Integer checkOrdinalNullable(Class<E> enumType, @Nullable Integer ordinal) {
return checkOrdinalOrDefault(enumType, ordinal, (Integer) null);
return checkOrdinalOrDefault(enumType, ordinal, null);
}
/**
@@ -180,7 +183,7 @@ public final class EnumTools {
Class<E> enumType,
@Nullable Integer ordinal,
@Nullable Integer defaultValue) {
AssertTools.checkNotNull(enumType);
checkNotNull(enumType);
return checkOrdinalOrGetInternal(enumType, ordinal, () -> checkOrdinalOrDefaultInternal(enumType, defaultValue, null));
}

View File

@@ -16,6 +16,8 @@
package xyz.zhouxy.plusone.commons.util;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkArgument;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
@@ -31,9 +33,11 @@ import xyz.zhouxy.plusone.commons.annotation.StaticFactoryMethod;
/**
* 枚举类
*
* <p>
* 参考 <a href="https://lostechies.com/jimmybogard/2008/08/12/enumeration-classes/">Enumeration classes</a>
*
* @deprecated 设计 Enumeration 的灵感来自于 .net 社区因为 C# 的枚举不带行为
* @author ZhouXY108 <luquanlion@outlook.com>
* @deprecated 设计 Enumeration 的灵感来自于 .net 社区因为 C&num; 的枚举不带行为
* Java 的枚举可以带行为故大多数情况下不需要这种设计
*/
@Deprecated
@@ -43,7 +47,7 @@ public abstract class Enumeration<T extends Enumeration<T>> // NOSONAR 暂不移
protected final String name;
protected Enumeration(final int id, final String name) {
AssertTools.checkArgument(StringTools.isNotBlank(name), "Name of enumeration must has text.");
checkArgument(StringTools.isNotBlank(name), "Name of enumeration must has text.");
this.id = id;
this.name = name;
}
@@ -125,7 +129,7 @@ public abstract class Enumeration<T extends Enumeration<T>> // NOSONAR 暂不移
* @return 枚举对象
*/
public T get(int id) {
AssertTools.checkArgument(this.valueMap.containsKey(id), "[%s] 对应的值不存在", id);
checkArgument(this.valueMap.containsKey(id), "[%s] 对应的值不存在", id);
return this.valueMap.get(id);
}

View File

@@ -16,8 +16,9 @@
package xyz.zhouxy.plusone.commons.util;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkArgumentNotNull;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@@ -26,11 +27,10 @@ import java.util.concurrent.ConcurrentHashMap;
*
* <p>
* 生成 UUID 修改版雪花IDSeata 版本
* </p>
*
* @see UUID
* @see IdWorker
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
public class IdGenerator {
@@ -70,7 +70,7 @@ public class IdGenerator {
* @return UUID 字符串
*/
public static String toSimpleString(UUID uuid) {
AssertTools.checkArgument(Objects.nonNull(uuid));
checkArgumentNotNull(uuid);
return (uuidDigits(uuid.getMostSignificantBits() >> 32, 8) +
uuidDigits(uuid.getMostSignificantBits() >> 16, 4) +
uuidDigits(uuid.getMostSignificantBits(), 4) +

View File

@@ -27,14 +27,18 @@ import javax.annotation.Nullable;
import xyz.zhouxy.plusone.commons.exception.system.NoAvailableMacFoundException;
/**
* Seata 提供的修改版雪花ID
* 修改版雪花 ID 生成器
*
* <p>
* 来自 Seata (https://seata.apache.org) {@code org.apache.seata.common.util.IdWorker}
*
* <p>
* 大体思路为
* <ol>
* <li>每个机器线程安全地生成序列前面加上机器的id这样就不会与其它机器的id相冲突</li>
* <li>时间戳作为序列的预留位它更像是应用启动时最开始的序列的一部分在一个时间戳里生成 4096 id 之后直接生成下一个时间戳的 id</li>
* </ol>
* </p>
*
* <p>
* 详情见以下介绍
* <ul>
@@ -43,7 +47,6 @@ import xyz.zhouxy.plusone.commons.exception.system.NoAvailableMacFoundException;
* <li><a href="https://juejin.cn/post/7264387737276203065">在开源项目中看到一个改良版的雪花算法现在它是你的了</a></li>
* <li><a href="https://juejin.cn/post/7265516484029743138">关于若干读者阅读改良版雪花算法后提出的几个共性问题的回复</a></li>
* </ul>
* </p>
*/
public class IdWorker {

View File

@@ -0,0 +1,299 @@
/*
* 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.util;
/**
* Joda-Time 工具类
*
* @author ZhouXY108 <luquanlion@outlook.com>
*/
public class JodaTimeTools {
// ================================
// #region - toJodaInstant
// ================================
/**
* 将 {@link java.time.Instant} 转换为 {@link org.joda.time.Instant}
*
* @param instant {@link java.time.Instant} 对象
* @return {@link org.joda.time.Instant} 对象
*/
public static org.joda.time.Instant toJodaInstant(java.time.Instant instant) {
return new org.joda.time.Instant(instant.toEpochMilli());
}
/**
* 将 {@link java.time.ZonedDateTime} 转换为 {@link org.joda.time.Instant}
*
* @param zonedDateTime {@link java.time.ZonedDateTime} 对象
* @return {@link org.joda.time.Instant} 对象
*/
public static org.joda.time.Instant toJodaInstant(java.time.ZonedDateTime zonedDateTime) {
return toJodaInstant(zonedDateTime.toInstant());
}
/**
* 计算指定时区的地区时间,对应的时间戳。结果为 {@link org.joda.time.Instant} 对象
*
* @param localDateTime {@link java.time.LocalDateTime} 对象
* @param zone 时区
* @return {@link org.joda.time.Instant} 对象
*/
public static org.joda.time.Instant toJodaInstant(
java.time.LocalDateTime localDateTime,
java.time.ZoneId zone) {
return toJodaInstant(java.time.ZonedDateTime.of(localDateTime, zone));
}
// ================================
// #endregion
// ================================
// ================================
// #region - toJavaInstant
// ================================
/**
* 将 {@link org.joda.time.Instant} 对象转换为 {@link java.time.Instant} 对象
*
* @param instant {@link org.joda.time.Instant} 对象
* @return {@link java.time.Instant} 对象
*/
public static java.time.Instant toJavaInstant(org.joda.time.Instant instant) {
return DateTimeTools.toInstant(instant.getMillis());
}
/**
* 将 joda-time 中的 {@link org.joda.time.DateTime} 对象转换为 Java 的
* {@link java.time.Instant} 对象
*
* @param dateTime joda-time 中表示日期时间的 {@link org.joda.time.DateTime} 对象
* @return Java 表示时间戳的 {@link java.time.Instant} 对象
*/
public static java.time.Instant toJavaInstant(org.joda.time.DateTime dateTime) {
return DateTimeTools.toInstant(dateTime.getMillis());
}
/**
* 将 joda-time 中的 {@link org.joda.time.LocalDateTime} 对象和
* {@link org.joda.time.DateTimeZone} 对象
* 转换为 Java 中的 {@link java.time.Instant} 对象
*
* @param localDateTime {@link org.joda.time.LocalDateTime} 对象
* @param zone {@link org.joda.time.DateTimeZone} 对象
* @return Java 表示时间戳的 {@link java.time.Instant} 对象
*/
public static java.time.Instant toJavaInstant(
org.joda.time.LocalDateTime localDateTime,
org.joda.time.DateTimeZone zone) {
return toJavaInstant(localDateTime.toDateTime(zone));
}
// ================================
// #endregion
// ================================
// ================================
// #region - toJodaDateTime
// ================================
/**
* 将 Java 中表示日期时间的 {@link java.time.ZonedDateTime} 对象
* 转换为 joda-time 的 {@link org.joda.time.DateTime} 对象
*
* @param zonedDateTime 日期时间
* @return joda-time 中对应的 {@link org.joda.time.DateTime} 对象
*/
public static org.joda.time.DateTime toJodaDateTime(java.time.ZonedDateTime zonedDateTime) {
org.joda.time.DateTimeZone zone = org.joda.time.DateTimeZone.forID(zonedDateTime.getZone().getId());
return toJodaInstant(zonedDateTime.toInstant()).toDateTime(zone);
}
/**
* 将 java.time 中表示日期时间的 {@link java.time.LocalDateTime} 对象和表示时区的
* {@link java.time.ZoneId} 对象转换为 joda-time 中对应的 {@link org.joda.time.DateTime}
* 对象
* 转换为 joda-time 中对应的 {@link org.joda.time.DateTime} 对象
*
* @param localDateTime 日期时间
* @param zone 时区
* @return joda-time 中对应的 {@link org.joda.time.DateTime} 对象
*/
public static org.joda.time.DateTime toJodaDateTime(
java.time.LocalDateTime localDateTime,
java.time.ZoneId zone) {
org.joda.time.LocalDateTime jodaLocalDateTime = toJodaLocalDateTime(localDateTime);
org.joda.time.DateTimeZone jodaZone = toJodaZone(zone);
return jodaLocalDateTime.toDateTime(jodaZone);
}
/**
* 计算时间戳在指定时区对应的时间,结果使用 {@link org.joda.time.DateTime} 表示
*
* @param instant java.time 中的时间戳
* @param zone java.time 中的时区
* @return joda-time 中带时区的日期时间
*/
public static org.joda.time.DateTime toJodaDateTime(
java.time.Instant instant,
java.time.ZoneId zone) {
org.joda.time.DateTimeZone dateTimeZone = toJodaZone(zone);
return toJodaInstant(instant).toDateTime(dateTimeZone);
}
// ================================
// #endregion
// ================================
// ================================
// #region - toZonedDateTime
// ================================
/**
* 将 joda-time 中带时区的日期时间,转换为 java.time 中带时区的日期时间
*
* @param dateTime joda-time 中带时区的日期时间
* @return java.time 中带时区的日期时间
*/
public static java.time.ZonedDateTime toZonedDateTime(org.joda.time.DateTime dateTime) {
java.time.ZoneId zone = dateTime.getZone().toTimeZone().toZoneId();
return toJavaInstant(dateTime.toInstant()).atZone(zone);
}
/**
* 将 joda-time 中的 {@link org.joda.time.LocalDateTime} 和
* {@link org.joda.time.DateTimeZone}
* 转换为 java.time 中的 {@link java.time.ZonedDateTime}
*
* @param localDateTime joda-time 中的地区时间
* @param dateTimeZone joda-time 中的时区
* @return java.time 中带时区的日期时间
*/
public static java.time.ZonedDateTime toZonedDateTime(
org.joda.time.LocalDateTime localDateTime,
org.joda.time.DateTimeZone dateTimeZone) {
java.time.ZoneId zone = toJavaZone(dateTimeZone);
return toJavaInstant(localDateTime, dateTimeZone).atZone(zone);
}
/**
* 获取 joda-time 中的 {@link org.joda.time.Instant} 在指定时区的时间,用 Java 8+ 的
* {@link java.time.ZonedDateTime} 表示
*
* @param instant joda-time 中的时间戳
* @param dateTimeZone joda-time 中的时区
* @return
*/
public static java.time.ZonedDateTime toZonedDateTime(
org.joda.time.Instant instant,
org.joda.time.DateTimeZone dateTimeZone) {
java.time.ZoneId zone = toJavaZone(dateTimeZone);
return toJavaInstant(instant).atZone(zone);
}
// ================================
// #endregion
// ================================
// ================================
// #region - toJodaLocalDateTime
// ================================
/**
* 将 {@link java.time.LocalDateTime} 转换为 {@link org.joda.time.LocalDateTime}
*
* @param localDateTime Java 8 LocalDateTime
* @return joda-time LocalDateTime
*/
public static org.joda.time.LocalDateTime toJodaLocalDateTime(java.time.LocalDateTime localDateTime) {
return new org.joda.time.LocalDateTime(
localDateTime.getYear(),
localDateTime.getMonthValue(),
localDateTime.getDayOfMonth(),
localDateTime.getHour(),
localDateTime.getMinute(),
localDateTime.getSecond(),
localDateTime.getNano() / 1_000_000 // 毫秒转纳秒
);
}
// ================================
// #endregion
// ================================
// ================================
// #region - toJavaLocalDateTime
// ================================
/**
* 将 {@link org.joda.time.LocalDateTime} 转换为 {@link java.time.LocalDateTime}
*
* @param localDateTime joda-time LocalDateTime
* @return Java 8 LocalDateTime
*/
public static java.time.LocalDateTime toJavaLocalDateTime(org.joda.time.LocalDateTime localDateTime) {
return java.time.LocalDateTime.of(
localDateTime.getYear(),
localDateTime.getMonthOfYear(),
localDateTime.getDayOfMonth(),
localDateTime.getHourOfDay(),
localDateTime.getMinuteOfHour(),
localDateTime.getSecondOfMinute(),
localDateTime.getMillisOfSecond() * 1_000_000 // 毫秒转纳秒
);
}
// ================================
// #endregion
// ================================
// ================================
// #region - ZoneId <--> DateTimeZone
// ================================
/**
* 转换 Java API 和 joda-time API 表示时区的对象
*
* @param jodaZone joda-time API 中表示时区的对象
* @return Java API 中表示时区的对象
*/
public static java.time.ZoneId toJavaZone(org.joda.time.DateTimeZone jodaZone) {
return jodaZone.toTimeZone().toZoneId();
}
/**
* 转换 Java API 和 joda-time API 表示时区的对象
*
* @param zone Java API 中表示时区的对象
* @return joda-time API 中表示时区的对象
*/
public static org.joda.time.DateTimeZone toJodaZone(java.time.ZoneId zone) {
return org.joda.time.DateTimeZone.forID(zone.getId());
}
// ================================
// #endregion
// ================================
/**
* 私有构造方法
*/
private JodaTimeTools() {
throw new IllegalStateException("Utility class");
}
}

View File

@@ -25,11 +25,13 @@ import javax.annotation.Nullable;
/**
* 数字工具类
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
public class Numbers {
// ================================
// #region - sum
// ================================
/**
* 求和
@@ -108,7 +110,7 @@ public class Numbers {
* @return 求和结果
*/
public static BigInteger sum(final BigInteger... numbers) {
if (ArrayTools.isNullOrEmpty(numbers)) {
if (ArrayTools.isEmpty(numbers)) {
return BigInteger.ZERO;
}
BigInteger result = Numbers.nullToZero(numbers[0]);
@@ -131,9 +133,13 @@ public class Numbers {
return BigDecimals.sum(numbers);
}
// ================================
// #endregion
// ================================
// ================================
// #region - nullToZero
// ================================
/**
* {@code null} 转换为 {@code 0}
@@ -217,7 +223,122 @@ public class Numbers {
return BigDecimals.nullToZero(val);
}
// #endregion
// ================================
// #endregion - nullToZero
// ================================
// ================================
// #region - parse
// ================================
/**
* 将字符串转为对应 {@link Short}转换失败时返回 {@code defaultValue}允许为 {@code null}
*
* @param str 要转换的字符串
* @param defaultValue 默认值
* @return 转换结果
*/
@Nullable
public static Short parseShort(@Nullable String str, @Nullable Short defaultValue) {
if (StringTools.isBlank(str)) {
return defaultValue;
}
try {
return Short.parseShort(str);
}
catch (NumberFormatException ignore) {
// ignore
}
return defaultValue;
}
/**
* 将字符串转为 {@link Integer}转换失败时返回 {@code defaultValue}允许为 {@code null}
*
* @param str 要转换的字符串
* @param defaultValue 默认值
* @return 转换结果
*/
@Nullable
public static Integer parseInteger(@Nullable String str, @Nullable Integer defaultValue) {
if (StringTools.isBlank(str)) {
return defaultValue;
}
try {
return Integer.parseInt(str);
}
catch (NumberFormatException ignore) {
// ignore
}
return defaultValue;
}
/**
* 将字符串转为 {@link Long}转换失败时返回 {@code defaultValue}允许为 {@code null}
*
* @param str 要转换的字符串
* @param defaultValue 默认值
* @return 转换结果
*/
@Nullable
public static Long parseLong(@Nullable String str, @Nullable Long defaultValue) {
if (StringTools.isBlank(str)) {
return defaultValue;
}
try {
return Long.parseLong(str);
}
catch (NumberFormatException ignore) {
// ignore
}
return defaultValue;
}
/**
* 将字符串转为 {@link Float}转换失败时返回 {@code defaultValue}允许为 {@code null}
*
* @param str 要转换的字符串
* @param defaultValue 默认值
* @return 转换结果
*/
@Nullable
public static Float parseFloat(@Nullable String str, @Nullable Float defaultValue) {
if (StringTools.isBlank(str)) {
return defaultValue;
}
try {
return Float.parseFloat(str);
}
catch (NumberFormatException ignore) {
// ignore
}
return defaultValue;
}
/**
* 将字符串转为 {@link Double}转换失败时返回 {@code defaultValue}允许为 {@code null}
*
* @param str 要转换的字符串
* @param defaultValue 默认值
* @return 转换结果
*/
@Nullable
public static Double parseDouble(@Nullable String str, @Nullable Double defaultValue) {
if (StringTools.isBlank(str)) {
return defaultValue;
}
try {
return Double.parseDouble(str);
}
catch (NumberFormatException ignore) {
// ignore
}
return defaultValue;
}
// ================================
// #endregion - parse
// ================================
private Numbers() {
throw new IllegalStateException("Utility class");

View File

@@ -31,7 +31,7 @@ import com.google.common.annotations.Beta;
* <p>
* 提供一些 Optional 相关的方法
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
* @see Optional
* @see OptionalInt
@@ -45,7 +45,6 @@ public class OptionalTools {
* <p>
* 包装类为 {@code null} 表示值的缺失转为 {@link OptionalInt}
* {@link OptionalInt#empty()} 表示值的缺失
* </p>
*
* @param value 包装对象
* @return {@link OptionalInt} 实例
@@ -58,7 +57,6 @@ public class OptionalTools {
* {@code Optional<Integer>} 对象转为 {@link OptionalInt} 对象
* <p>
* {@code Optional<Integer>} 将整数包装了两次改为使用 {@link OptionalInt} 包装其中的整数数据
* </p>
*
* @param optionalObj {@code Optional<Integer>} 对象
* @return {@link OptionalInt} 实例
@@ -72,7 +70,6 @@ public class OptionalTools {
* <p>
* 包装类为 {@code null} 表示值的缺失转为 {@link OptionalLong}
* {@link OptionalLong#empty()} 表示值的缺失
* </p>
*
* @param value 包装对象
* @return {@link OptionalLong} 实例
@@ -85,7 +82,6 @@ public class OptionalTools {
* {@code Optional<Long>} 转为 {@link OptionalLong}
* <p>
* {@code Optional<Long>} 将整数包装了两次改为使用 {@link OptionalLong} 包装其中的整数数据
* </p>
*
* @param optionalObj 包装对象
* @return {@link OptionalLong} 实例
@@ -99,7 +95,6 @@ public class OptionalTools {
* <p>
* 包装类为 {@code null} 表示值的缺失转为 {@link OptionalDouble}
* {@link OptionalDouble#empty()} 表示值的缺失
* </p>
*
* @param value 包装对象
* @return {@link OptionalDouble} 实例
@@ -112,7 +107,6 @@ public class OptionalTools {
* {@code Optional<Double>} 转为 {@link OptionalDouble}
* <p>
* {@code Optional<Double>} 将整数包装了两次改为使用 {@link OptionalDouble} 包装其中的整数数据
* </p>
*
* @param optionalObj 包装对象
* @return {@link OptionalDouble} 实例

View File

@@ -0,0 +1,344 @@
/*
* Copyright 2023-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.util;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkArgument;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkArgumentNotNull;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import com.google.common.collect.BoundType;
import com.google.common.collect.Range;
/**
* 随机工具类
*
* @author ZhouXY108 <luquanlion@outlook.com>
*/
public final class RandomTools {
private static final SecureRandom DEFAULT_SECURE_RANDOM;
static {
SecureRandom secureRandom;
try {
secureRandom = SecureRandom.getInstanceStrong(); // 获取高强度安全随机数生成器
}
catch (NoSuchAlgorithmException e) {
secureRandom = new SecureRandom(); // 获取普通的安全随机数生成器
}
DEFAULT_SECURE_RANDOM = secureRandom;
}
/**
* 大写字母
*/
public static final String CAPITAL_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/**
* 小写字母
*/
public static final String LOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz";
/**
* 数字
*/
public static final String NUMBERS = "0123456789";
/**
* 默认的 {@code SecureRandom}
*
* @return 默认的 {@code SecureRandom}
*/
public static SecureRandom defaultSecureRandom() {
return DEFAULT_SECURE_RANDOM;
}
/**
* 当前线程的 {@code ThreadLocalRandom}
*
* @return 当前线程的 {@code ThreadLocalRandom}
*/
public static ThreadLocalRandom currentThreadLocalRandom() {
return ThreadLocalRandom.current();
}
// ================================
// #region - randomStr
// ================================
/**
* 使用传入的随机数生成器,生成指定长度的字符串
*
* @param random 随机数生成器。根据需要可以传入
* {@link java.util.concurrent.ThreadLocalRandom}、{@link java.security.SecureRandom}
* 等,不为空
* @param sourceCharacters 字符池。字符串的字符将在数组中选,不为空
* @param length 字符串长度
* @return 随机字符串
*/
public static String randomStr(Random random, char[] sourceCharacters, int length) {
checkArgumentNotNull(random, "Random cannot be null.");
checkArgumentNotNull(sourceCharacters, "Source characters cannot be null.");
checkArgument(length >= 0, "The length should be greater than or equal to zero.");
return randomStrInternal(random, sourceCharacters, length);
}
/**
* 使用当前线程的 {@code ThreadLocalRandom},生成指定长度的字符串
*
* @param sourceCharacters 字符池。字符串的字符将在数组中选,不为空
* @param length 字符串长度
* @return 随机字符串
*/
public static String randomStr(char[] sourceCharacters, int length) {
checkArgumentNotNull(sourceCharacters, "Source characters cannot be null.");
checkArgument(length >= 0, "The length should be greater than or equal to zero.");
return randomStrInternal(ThreadLocalRandom.current(), sourceCharacters, length);
}
/**
* 使用默认的 {@code SecureRandom},生成指定长度的字符串
*
* @param sourceCharacters 字符池。字符串的字符将在数组中选,不为空
* @param length 字符串长度
* @return 随机字符串
*/
public static String secureRandomStr(char[] sourceCharacters, int length) {
checkArgumentNotNull(sourceCharacters, "Source characters cannot be null.");
checkArgument(length >= 0, "The length should be greater than or equal to zero.");
return randomStrInternal(DEFAULT_SECURE_RANDOM, sourceCharacters, length);
}
/**
* 使用传入的随机数生成器,生成指定长度的字符串
*
* @param random 随机数生成器。根据需要可以传入
* {@link java.util.concurrent.ThreadLocalRandom}、{@link java.security.SecureRandom}
* 等,不为空
* @param sourceCharacters 字符池。字符串的字符将在数组中选,不为空
* @param length 字符串长度
* @return 随机字符串
*/
public static String randomStr(Random random, String sourceCharacters, int length) {
checkArgumentNotNull(random, "Random cannot be null.");
checkArgumentNotNull(sourceCharacters, "Source characters cannot be null.");
checkArgument(length >= 0, "The length should be greater than or equal to zero.");
return randomStrInternal(random, sourceCharacters, length);
}
/**
* 使用当前线程的 {@code ThreadLocalRandom},生成指定长度的字符串
*
* @param sourceCharacters 字符池。字符串的字符将在数组中选,不为空
* @param length 字符串长度
* @return 随机字符串
*/
public static String randomStr(String sourceCharacters, int length) {
checkArgumentNotNull(sourceCharacters, "Source characters cannot be null.");
checkArgument(length >= 0, "The length should be greater than or equal to zero.");
return randomStrInternal(ThreadLocalRandom.current(), sourceCharacters, length);
}
/**
* 使用默认的 {@code SecureRandom},生成指定长度的字符串
*
* @param sourceCharacters 字符池。字符串的字符将在数组中选,不为空
* @param length 字符串长度
* @return 随机字符串
*/
public static String secureRandomStr(String sourceCharacters, int length) {
checkArgumentNotNull(sourceCharacters, "Source characters cannot be null.");
checkArgument(length >= 0, "The length should be greater than or equal to zero.");
return randomStrInternal(DEFAULT_SECURE_RANDOM, sourceCharacters, length);
}
// ================================
// #endregion - randomStr
// ================================
// ================================
// #region - randomInt
// ================================
/**
* 使用传入的随机数生成器,生成随机整数
*
* @param startInclusive 最小值(包含)
* @param endExclusive 最大值(不包含)
* @return 在区间 {@code [min, max)} 内的随机整数
*
* @since 1.1.0
*/
public static int randomInt(Random random, int startInclusive, int endExclusive) {
checkArgumentNotNull(random, "Random cannot be null.");
checkArgument(startInclusive < endExclusive, "Start value must be less than end value.");
return randomIntInternal(random, startInclusive, endExclusive);
}
/**
* 使用当前线程的 {@code ThreadLocalRandom},生成随机整数
*
* @param startInclusive 最小值(包含)
* @param endExclusive 最大值(不包含)
* @return 在区间 {@code [min, max)} 内的随机整数
*
* @since 1.1.0
*/
public static int randomInt(int startInclusive, int endExclusive) {
checkArgument(startInclusive < endExclusive, "Start value must be less than end value.");
return randomIntInternal(ThreadLocalRandom.current(), startInclusive, endExclusive);
}
/**
* 使用默认的 {@code SecureRandom},生成随机整数
*
* @param startInclusive 最小值(包含)
* @param endExclusive 最大值(不包含)
* @return 在区间 {@code [min, max)} 内的随机整数
*
* @since 1.1.0
*/
public static int secureRandomInt(int startInclusive, int endExclusive) {
checkArgument(startInclusive < endExclusive, "Start value must be less than end value.");
return randomIntInternal(DEFAULT_SECURE_RANDOM, startInclusive, endExclusive);
}
/**
* 使用传入的随机数生成器,生成随机整数
*
* @param range 整数区间
* @return 在指定区间内的随机整数
*
* @since 1.1.0
*/
public static int randomInt(Random random, Range<Integer> range) {
checkArgumentNotNull(random, "Random cannot be null.");
checkArgumentNotNull(range, "Range cannot be null.");
return randomIntInternal(random, range);
}
/**
* 使用当前线程的 {@code ThreadLocalRandom},生成随机整数
*
* @param range 整数区间
* @return 在指定区间内的随机整数
*
* @since 1.1.0
*/
public static int randomInt(Range<Integer> range) {
checkArgumentNotNull(range, "Range cannot be null.");
return randomIntInternal(ThreadLocalRandom.current(), range);
}
/**
* 使用默认的 {@code SecureRandom},生成随机整数
*
* @param range 整数区间
* @return 在指定区间内的随机整数
*
* @since 1.1.0
*/
public static int secureRandomInt(Range<Integer> range) {
checkArgumentNotNull(range, "Range cannot be null.");
return randomIntInternal(DEFAULT_SECURE_RANDOM, range);
}
// ================================
// #endregion - randomInt
// ================================
// ================================
// #region - private methods
// ================================
/**
* 使用传入的随机数生成器,生成指定长度的字符串
*
* @param random 随机数生成器。根据需要可以传入
* {@link java.util.concurrent.ThreadLocalRandom}、{@link java.security.SecureRandom}
* 等,不为空
* @param sourceCharacters 字符池。字符串的字符将在数组中选,不为空
* @param length 字符串长度
* @return 随机字符串
*/
private static String randomStrInternal(Random random, char[] sourceCharacters, int length) {
if (length == 0) {
return StringTools.EMPTY_STRING;
}
final char[] result = new char[length];
for (int i = 0; i < length; i++) {
result[i] = sourceCharacters[random.nextInt(sourceCharacters.length)];
}
return String.valueOf(result);
}
/**
* 使用传入的随机数生成器,生成指定长度的字符串
*
* @param random 随机数生成器。根据需要可以传入
* {@link java.util.concurrent.ThreadLocalRandom}、{@link java.security.SecureRandom}
* 等,不为空
* @param sourceCharacters 字符池。字符串的字符将在数组中选,不为空
* @param length 字符串长度
* @return 随机字符串
*/
private static String randomStrInternal(Random random, String sourceCharacters, int length) {
if (length == 0) {
return StringTools.EMPTY_STRING;
}
final char[] result = new char[length];
for (int i = 0; i < length; i++) {
result[i] = sourceCharacters.charAt(random.nextInt(sourceCharacters.length()));
}
return String.valueOf(result);
}
/**
* 使用传入的随机数生成器,生成随机整数
*
* @param startInclusive 最小值(包含)
* @param endExclusive 最大值(不包含)
* @return 在区间 {@code [min, max)} 内的随机整数
*/
private static int randomIntInternal(Random random, int startInclusive, int endExclusive) {
return random.nextInt(endExclusive - startInclusive) + startInclusive;
}
/**
* 使用传入的随机数生成器,生成随机整数
*
* @param range 整数区间
* @return 在指定区间内的随机整数
*/
private static int randomIntInternal(Random random, Range<Integer> range) {
Integer lowerEndpoint = range.lowerEndpoint();
Integer upperEndpoint = range.upperEndpoint();
int min = range.lowerBoundType() == BoundType.CLOSED ? lowerEndpoint : lowerEndpoint + 1;
int max = range.upperBoundType() == BoundType.OPEN ? upperEndpoint : upperEndpoint + 1;
return random.nextInt(max - min) + min;
}
// ================================
// #endregion - private methods
// ================================
private RandomTools() {
throw new IllegalStateException("Utility class");
}
}

View File

@@ -14,7 +14,7 @@
* limitations under the License.
*/
package xyz.zhouxy.plusone.commons.base;
package xyz.zhouxy.plusone.commons.util;
import java.util.Objects;
import java.util.function.Consumer;
@@ -27,7 +27,7 @@ import javax.annotation.Nullable;
/**
* {@link Ref} 包装了一个值表示对该值的应用
*
* <p>灵感来自于 C# {@value ref} 参数修饰符C# 允许通过以下方式将值返回给调用端</p>
* <p>灵感来自于 C&num; {@code ref} 参数修饰符C&num; 允许通过以下方式将值返回给调用端</p>
* <pre>
* void Method(ref int refArgument)
* {
@@ -51,7 +51,7 @@ import javax.annotation.Nullable;
* <p>
* 当一个方法需要产生多个结果时无法有多个返回值可以使用 {@link Ref} 作为参数传入方法内部修改 {@link Ref} 的值
* 调用方在调用方法之后使用 {@code getValue()} 获取结果
* </p>
*
* <pre>
* String method(final Ref&lt;Integer&gt; intRefArgument, final Ref&lt;String&gt; strRefArgument) {
* intRefArgument.transformValue(i -&gt; i + 44);
@@ -67,7 +67,7 @@ import javax.annotation.Nullable;
* System.out.println(result); // Output: Return string
* </pre>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
public final class Ref<T> {

View File

@@ -16,27 +16,44 @@
package xyz.zhouxy.plusone.commons.util;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkArgument;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkNotNull;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Objects;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
/**
* 封装一些常用的正则操作并可以缓存 {@link Pattern} 实例以复用最多缓存大概 256
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* 封装一些常用的正则操作并可以缓存 {@link Pattern} 实例以复用
*
* @author ZhouXY108 <luquanlion@outlook.com>
*/
public final class RegexTools {
private static final int DEFAULT_CACHE_INITIAL_CAPACITY = 64;
private static final int MAX_CACHE_SIZE = 256;
private static final Map<String, Pattern> PATTERN_CACHE
= new ConcurrentHashMap<>(DEFAULT_CACHE_INITIAL_CAPACITY);
private static final int DEFAULT_FLAG = 0;
private static final LoadingCache<RegexAndFlags, Pattern> PATTERN_CACHE = CacheBuilder
.newBuilder()
.maximumSize(MAX_CACHE_SIZE)
.build(new CacheLoader<RegexAndFlags, Pattern>() {
@SuppressWarnings("null")
public Pattern load(@Nonnull RegexAndFlags regexAndFlags) {
return regexAndFlags.compilePattern();
}
});
// ================================
// #region - getPattern
// ================================
/**
* 获取 {@link Pattern} 实例
@@ -46,8 +63,20 @@ public final class RegexTools {
* @return {@link Pattern} 实例
*/
public static Pattern getPattern(final String pattern, final boolean cachePattern) {
AssertTools.checkNotNull(pattern);
return cachePattern ? cacheAndGetPatternInternal(pattern) : getPatternInternal(pattern);
return getPattern(pattern, DEFAULT_FLAG, cachePattern);
}
/**
* 获取 {@link Pattern} 实例
*
* @param pattern 正则表达式
* @param flags 正则表达式匹配标识
* @param cachePattern 是否缓存 {@link Pattern} 实例
* @return {@link Pattern} 实例
*/
public static Pattern getPattern(final String pattern, final int flags, final boolean cachePattern) {
checkNotNull(pattern);
return cachePattern ? cacheAndGetPatternInternal(pattern, flags) : getPatternInternal(pattern, flags);
}
/**
@@ -57,34 +86,29 @@ public final class RegexTools {
* @return {@link Pattern} 实例
*/
public static Pattern getPattern(final String pattern) {
AssertTools.checkNotNull(pattern);
return getPatternInternal(pattern);
return getPattern(pattern, DEFAULT_FLAG);
}
/**
* 将各个正则表达式转为 {@link Pattern} 实例
* 获取 {@link Pattern} 实例不缓存
*
* @param patterns 正则表达式
* @param cachePattern 是否缓存 {@link Pattern} 实例
* @return {@link Pattern} 实例数组
* @param pattern 正则表达式
* @param flags 正则表达式匹配标识
* @return {@link Pattern} 实例
*/
public static Pattern[] getPatterns(final String[] patterns, final boolean cachePattern) {
AssertTools.checkArgument(ArrayTools.isAllElementsNotNull(patterns));
return cachePattern
? cacheAndGetPatternsInternal(patterns)
: getPatternsInternal(patterns);
@Nonnull
public static Pattern getPattern(final String pattern, final int flags) {
checkNotNull(pattern);
return getPatternInternal(pattern, flags);
}
/**
* 将各个正则表达式转为 {@link Pattern} 实例不缓存
*
* @param patterns 正则表达式
* @return {@link Pattern} 实例数组
*/
public static Pattern[] getPatterns(final String[] patterns) {
AssertTools.checkArgument(ArrayTools.isAllElementsNotNull(patterns));
return getPatternsInternal(patterns);
}
// ================================
// #endregion - getPattern
// ================================
// ================================
// #region - matches
// ================================
/**
* 判断 {@code input} 是否匹配 {@code pattern}
@@ -94,7 +118,7 @@ public final class RegexTools {
* @return 判断结果
*/
public static boolean matches(@Nullable final CharSequence input, final Pattern pattern) {
AssertTools.checkNotNull(pattern);
checkNotNull(pattern);
return matchesInternal(input, pattern);
}
@@ -105,9 +129,9 @@ public final class RegexTools {
* @param patterns 正则
* @return 判断结果
*/
public static boolean matchesOne(@Nullable final CharSequence input, final Pattern[] patterns) {
AssertTools.checkArgument(ArrayTools.isAllElementsNotNull(patterns));
return matchesOneInternal(input, patterns);
public static boolean matchesAny(@Nullable final CharSequence input, final Pattern[] patterns) {
checkArgument(ArrayTools.isAllElementsNotNull(patterns));
return matchesAnyInternal(input, patterns);
}
/**
@@ -118,7 +142,7 @@ public final class RegexTools {
* @return 判断结果
*/
public static boolean matchesAll(@Nullable final CharSequence input, final Pattern[] patterns) {
AssertTools.checkArgument(ArrayTools.isAllElementsNotNull(patterns));
checkArgument(ArrayTools.isAllElementsNotNull(patterns));
return matchesAllInternal(input, patterns);
}
@@ -132,11 +156,21 @@ public final class RegexTools {
*/
public static boolean matches(@Nullable final CharSequence input, final String pattern,
final boolean cachePattern) {
AssertTools.checkNotNull(pattern);
Pattern p = cachePattern
? cacheAndGetPatternInternal(pattern)
: getPatternInternal(pattern);
return matchesInternal(input, p);
return matches(input, pattern, DEFAULT_FLAG, cachePattern);
}
/**
* 判断 {@code input} 是否匹配 {@code pattern}
*
* @param input 输入
* @param pattern 正则表达式
* @param flags 正则表达式匹配标识
* @param cachePattern 是否缓存 {@link Pattern} 实例
* @return 判断结果
*/
public static boolean matches(@Nullable final CharSequence input, final String pattern, final int flags,
final boolean cachePattern) {
return matchesInternal(input, getPattern(pattern, flags, cachePattern));
}
/**
@@ -147,69 +181,29 @@ public final class RegexTools {
* @return 判断结果
*/
public static boolean matches(@Nullable final CharSequence input, final String pattern) {
AssertTools.checkNotNull(pattern);
return matchesInternal(input, getPatternInternal(pattern));
return matches(input, pattern, DEFAULT_FLAG);
}
/**
* 判断 {@code input} 是否匹配 {@code patterns} 中的一个
* 判断 {@code input} 是否匹配 {@code pattern}不缓存 {@link Pattern} 实例
*
* @param input 输入
* @param patterns 正则表达式
* @param cachePattern 是否缓存 {@link Pattern} 实例
* @param input 输入
* @param pattern 正则表达式
* @param flags 正则表达式匹配标识
* @return 判断结果
*/
public static boolean matchesOne(@Nullable final CharSequence input, final String[] patterns,
final boolean cachePattern) {
AssertTools.checkArgument(ArrayTools.isAllElementsNotNull(patterns));
final Pattern[] patternSet = cachePattern
? cacheAndGetPatternsInternal(patterns)
: getPatternsInternal(patterns);
return matchesOneInternal(input, patternSet);
public static boolean matches(@Nullable final CharSequence input,
final String pattern, final int flags) {
return matchesInternal(input, getPattern(pattern, flags));
}
/**
* 判断 {@code input} 是否匹配 {@code patterns} 中的一个不缓存 {@link Pattern} 实例
*
* @param input 输入
* @param patterns 正则表达式
* @return 判断结果
*/
public static boolean matchesOne(@Nullable final CharSequence input, final String[] patterns) {
AssertTools.checkArgument(ArrayTools.isAllElementsNotNull(patterns));
final Pattern[] patternSet = getPatternsInternal(patterns);
return matchesOneInternal(input, patternSet);
}
// ================================
// #endregion - matches
// ================================
/**
* 判断 {@code input} 是否匹配全部正则
*
* @param input 输入
* @param patterns 正则表达式
* @param cachePattern 是否缓存 {@link Pattern} 实例
* @return 判断结果
*/
public static boolean matchesAll(@Nullable final CharSequence input, final String[] patterns,
final boolean cachePattern) {
AssertTools.checkArgument(ArrayTools.isAllElementsNotNull(patterns));
final Pattern[] patternSet = cachePattern
? cacheAndGetPatternsInternal(patterns)
: getPatternsInternal(patterns);
return matchesAllInternal(input, patternSet);
}
/**
* 判断 {@code input} 是否匹配全部正则不缓存 {@link Pattern} 实例
*
* @param input 输入
* @param patterns 正则表达式
* @return 判断结果
*/
public static boolean matchesAll(@Nullable final CharSequence input, final String[] patterns) {
AssertTools.checkArgument(ArrayTools.isAllElementsNotNull(patterns));
final Pattern[] patternSet = getPatternsInternal(patterns);
return matchesAllInternal(input, patternSet);
}
// ================================
// #region - getMatcher
// ================================
/**
* 生成 Matcher
@@ -219,8 +213,8 @@ public final class RegexTools {
* @return 结果
*/
public static Matcher getMatcher(final CharSequence input, final Pattern pattern) {
AssertTools.checkNotNull(input);
AssertTools.checkNotNull(pattern);
checkNotNull(input);
checkNotNull(pattern);
return pattern.matcher(input);
}
@@ -233,12 +227,21 @@ public final class RegexTools {
* @return 结果
*/
public static Matcher getMatcher(final CharSequence input, final String pattern, boolean cachePattern) {
AssertTools.checkNotNull(input);
AssertTools.checkNotNull(pattern);
final Pattern p = cachePattern
? cacheAndGetPatternInternal(pattern)
: getPatternInternal(pattern);
return p.matcher(input);
return getMatcher(input, pattern, DEFAULT_FLAG, cachePattern);
}
/**
* 生成 Matcher
*
* @param input 输入
* @param pattern 正则表达式
* @param flags 正则表达式匹配标识
* @param cachePattern 是否缓存 {@link Pattern} 实例
* @return 结果
*/
public static Matcher getMatcher(final CharSequence input,
final String pattern, final int flags, boolean cachePattern) {
return getMatcher(input, getPattern(pattern, flags, cachePattern));
}
/**
@@ -249,70 +252,56 @@ public final class RegexTools {
* @return 结果
*/
public static Matcher getMatcher(final CharSequence input, final String pattern) {
AssertTools.checkNotNull(input);
AssertTools.checkNotNull(pattern);
return getPatternInternal(pattern).matcher(input);
return getMatcher(input, pattern, DEFAULT_FLAG);
}
// ========== internal methods ==========
/**
* 生成 Matcher不缓存 {@link Pattern} 实例
*
* @param input 输入
* @param pattern 正则表达式
* @param flags 正则表达式匹配标识
* @return 结果
*/
public static Matcher getMatcher(final CharSequence input, final String pattern, final int flags) {
checkNotNull(input);
checkNotNull(pattern);
return getPatternInternal(pattern, flags).matcher(input);
}
// ================================
// #endregion - getMatcher
// ================================
// ================================
// #region - internal methods
// ================================
/**
* 获取 {@link Pattern} 实例
*
* @param pattern 正则表达式
* @param flags 正则表达式匹配标识
* @return {@link Pattern} 实例
*/
@Nonnull
private static Pattern cacheAndGetPatternInternal(final String pattern) {
if (PATTERN_CACHE.size() < MAX_CACHE_SIZE) {
return PATTERN_CACHE.computeIfAbsent(pattern, Pattern::compile);
}
Pattern result = PATTERN_CACHE.get(pattern);
if (result != null) {
return result;
}
return Pattern.compile(pattern);
private static Pattern cacheAndGetPatternInternal(final String pattern, final int flags) {
final RegexAndFlags regexAndFlags = new RegexAndFlags(pattern, flags);
return PATTERN_CACHE.getUnchecked(regexAndFlags);
}
/**
* 获取 {@link Pattern} 实例不缓存
*
* @param pattern 正则表达式
* @param flags 正则表达式匹配标识
* @return {@link Pattern} 实例
*/
@Nonnull
private static Pattern getPatternInternal(final String pattern) {
Pattern result = PATTERN_CACHE.get(pattern);
if (result == null) {
result = Pattern.compile(pattern);
}
return result;
}
/**
* 将各个正则表达式转为 {@link Pattern} 实例
*
* @param patterns 正则表达式
* @return {@link Pattern} 实例数组
*/
@Nonnull
private static Pattern[] cacheAndGetPatternsInternal(final String[] patterns) {
return Arrays.stream(patterns)
.map(RegexTools::cacheAndGetPatternInternal)
.toArray(Pattern[]::new);
}
/**
* 将各个正则表达式转为 {@link Pattern} 实例
*
* @param patterns 正则表达式
* @return {@link Pattern} 实例数组
*/
@Nonnull
private static Pattern[] getPatternsInternal(final String[] patterns) {
return Arrays.stream(patterns)
.map(RegexTools::getPatternInternal)
.toArray(Pattern[]::new);
private static Pattern getPatternInternal(final String pattern, final int flags) {
final RegexAndFlags regexAndFlags = new RegexAndFlags(pattern, flags);
return Optional.ofNullable(PATTERN_CACHE.getIfPresent(regexAndFlags))
.orElseGet(regexAndFlags::compilePattern);
}
/**
@@ -333,7 +322,7 @@ public final class RegexTools {
* @param patterns 正则表达式
* @return 判断结果
*/
private static boolean matchesOneInternal(@Nullable final CharSequence input, final Pattern[] patterns) {
private static boolean matchesAnyInternal(@Nullable final CharSequence input, final Pattern[] patterns) {
return input != null
&& Arrays.stream(patterns)
.anyMatch(pattern -> pattern.matcher(input).matches());
@@ -352,8 +341,49 @@ public final class RegexTools {
.allMatch(pattern -> pattern.matcher(input).matches());
}
// ================================
// #endregion - internal methods
// ================================
private RegexTools() {
// 不允许实例化
throw new IllegalStateException("Utility class");
}
// ================================
// #region - RegexAndFlags
// ================================
private static final class RegexAndFlags {
private final String regex;
private final int flags;
private RegexAndFlags(String regex, int flags) {
this.regex = regex;
this.flags = flags;
}
private Pattern compilePattern() {
return Pattern.compile(regex, flags);
}
@Override
public int hashCode() {
return Objects.hash(regex, flags);
}
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj)
return true;
if (!(obj instanceof RegexAndFlags))
return false;
RegexAndFlags other = (RegexAndFlags) obj;
return Objects.equals(regex, other.regex) && flags == other.flags;
}
}
// ================================
// #endregion - RegexAndFlags
// ================================
}

View File

@@ -16,6 +16,8 @@
package xyz.zhouxy.plusone.commons.util;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkArgument;
import java.util.concurrent.TimeUnit;
/**
@@ -73,9 +75,9 @@ public class SnowflakeIdGenerator {
* @param datacenterId 数据中心ID (0~31)
*/
public SnowflakeIdGenerator(final long workerId, final long datacenterId) {
AssertTools.checkArgument((workerId <= MAX_WORKER_ID && workerId >= 0),
checkArgument((workerId <= MAX_WORKER_ID && workerId >= 0),
"WorkerId can't be greater than %s or less than 0.", MAX_WORKER_ID);
AssertTools.checkArgument((datacenterId <= MAX_DATACENTER_ID && datacenterId >= 0),
checkArgument((datacenterId <= MAX_DATACENTER_ID && datacenterId >= 0),
"DatacenterId can't be greater than %s or less than 0.", MAX_DATACENTER_ID);
this.datacenterIdAndWorkerId
= (datacenterId << DATACENTER_ID_SHIFT) | (workerId << WORKER_ID_SHIFT);

View File

@@ -16,9 +16,11 @@
package xyz.zhouxy.plusone.commons.util;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkArgument;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkArgumentNotNull;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Objects;
import javax.annotation.Nullable;
@@ -31,9 +33,8 @@ import xyz.zhouxy.plusone.commons.constant.PatternConsts;
*
* <p>
* 字符串工具类
* </p>
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
public class StringTools {
@@ -111,7 +112,7 @@ public class StringTools {
* @return 结果
*/
public static String repeat(final String str, int times, int maxLength) {
AssertTools.checkArgument(Objects.nonNull(str));
checkArgumentNotNull(str);
return String.valueOf(ArrayTools.repeat(str.toCharArray(), times, maxLength));
}
@@ -176,6 +177,9 @@ public class StringTools {
*/
@Beta
public static boolean isURL(@Nullable final String cs) {
if (cs == null) {
return false;
}
try {
new URL(cs);
} catch (MalformedURLException e) {
@@ -211,8 +215,8 @@ public class StringTools {
if (src == null || src.isEmpty()) {
return EMPTY_STRING;
}
AssertTools.checkArgument(front >= 0 && end >= 0);
AssertTools.checkArgument((front + end) <= src.length(), "需要截取的长度不能大于原字符串长度");
checkArgument(front >= 0 && end >= 0);
checkArgument((front + end) <= src.length(), "需要截取的长度不能大于原字符串长度");
final char[] charArray = src.toCharArray();
for (int i = front; i < charArray.length - end; i++) {
charArray[i] = replacedChar;
@@ -220,6 +224,23 @@ public class StringTools {
return String.valueOf(charArray);
}
/**
* 转换为带引号的字符串
*
* @param value
* @return 带引号的字符串
* @since 1.1.0
*/
public static String toQuotedString(@Nullable String value) {
if (value == null) {
return "null";
}
if (value.isEmpty()) {
return "\"\"";
}
return "\"" + value + "\"";
}
private StringTools() {
throw new IllegalStateException("Utility class");
}

View File

@@ -16,6 +16,8 @@
package xyz.zhouxy.plusone.commons.util;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkNotNull;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
@@ -30,7 +32,7 @@ import javax.annotation.Nullable;
/**
* TreeBuilder
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
* @since 1.0.0
*/
public class TreeBuilder<T, TSubTree extends T, TIdentity> {
@@ -76,7 +78,7 @@ public class TreeBuilder<T, TSubTree extends T, TIdentity> {
* @param nodes 平铺的节点列表
*/
public List<T> buildTree(Collection<T> nodes) {
AssertTools.checkNotNull(nodes);
checkNotNull(nodes);
return buildTreeInternal(nodes, this.defaultComparator);
}
@@ -93,7 +95,7 @@ public class TreeBuilder<T, TSubTree extends T, TIdentity> {
* <b>仅影响调用 addChild 的顺序如果操作对象本身对应的控制了子节点的顺序无法影响其相关逻辑</b>
*/
public List<T> buildTree(Collection<T> nodes, @Nullable Comparator<? super T> comparator) {
AssertTools.checkNotNull(nodes);
checkNotNull(nodes);
final Comparator<? super T> c = (comparator != null) ? comparator : this.defaultComparator;
return buildTreeInternal(nodes, c);
}

View File

@@ -0,0 +1,108 @@
/*
* 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.util;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkArgument;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterOutputStream;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
/**
* zip 工具类
*
* <p>
* 提供最基础的数据压缩/解压方法
*
* @author ZhouXY108 <luquanlion@outlook.com>
*
* @see Deflater
* @see Inflater
*/
public class ZipTools {
/**
* 使用默认压缩级别压缩数据
*
* @param input 输入
* @param level 压缩级别
* @return 压缩后的数据
*
* @throws IOException 发生 I/O 错误时抛出
*/
public static byte[] zip(@Nullable byte[] input) throws IOException {
return zipInternal(input, Deflater.DEFAULT_COMPRESSION);
}
/**
* 使用指定压缩级别压缩数据
*
* @param input 输入
* @param level 压缩级别
* @return 压缩后的数据
*
* @throws IOException 发生 I/O 错误时抛出
*/
public static byte[] zip(@Nullable byte[] input, int level) throws IOException {
checkArgument((level >= 0 && level <= 9) || level == Deflater.DEFAULT_COMPRESSION,
"invalid compression level");
return zipInternal(input, level);
}
@CheckForNull
private static byte[] zipInternal(@Nullable byte[] input, int level) throws IOException {
if (input == null) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (DeflaterOutputStream dos = new DeflaterOutputStream(out, new Deflater(level))) {
dos.write(input);
dos.finish();
return out.toByteArray();
}
}
/**
* 解压数据
*
* @param input 输入
* @return 解压后的数据
*
* @throws IOException 发生 I/O 错误时抛出
*/
@CheckForNull
public static byte[] unzip(@Nullable byte[] input) throws IOException {
if (input == null) {
return null;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (InflaterOutputStream dos = new InflaterOutputStream(out, new Inflater())) {
dos.write(input);
dos.finish();
return out.toByteArray();
}
}
private ZipTools() {
throw new IllegalStateException("Utility class");
}
}

View File

@@ -17,10 +17,10 @@
/**
* <h2>工具类</h2>
* <p>
* 包含树构建器{@link TreeBuilder}断言工具{@link AssertTools}ID 生成器{@link IdGenerator}及其它实用工具类
* </p>
* 包含树构建器{@link TreeBuilder}断言工具{@link AssertTools}
* ID 生成器{@link IdGenerator}及其它实用工具类
*
* @author <a href="http://zhouxy.xyz:3000/ZhouXY108">ZhouXY</a>
* @author ZhouXY108 <luquanlion@outlook.com>
*/
@ParametersAreNonnullByDefault
package xyz.zhouxy.plusone.commons.util;

View File

@@ -17,12 +17,12 @@
package xyz.zhouxy.plusone.commons.base;
import static org.junit.jupiter.api.Assertions.*;
import static xyz.zhouxy.plusone.commons.util.AssertTools.checkNotNull;
import javax.annotation.Nonnull;
import org.junit.jupiter.api.Test;
import xyz.zhouxy.plusone.commons.util.AssertTools;
class IWithCodeTests {
@@ -91,7 +91,7 @@ class IWithCodeTests {
private final String code;
WithCode(String code) {
AssertTools.checkNotNull(code);
checkNotNull(code);
this.code = code;
}

View File

@@ -0,0 +1,316 @@
/*
* 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.collection;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.Nullable;
import org.junit.jupiter.api.Test;
import com.google.common.collect.ImmutableMap;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class MapModifierTests {
private static final String APP_START_ID = UUID.randomUUID().toString();
private static final String LOCKED = "LOCKED";
private static final Map<String, String> commonProperties = ImmutableMap.<String, String>builder()
.put("channel", "MOBILE")
.put("appStartId", APP_START_ID)
.build();
@Test
void demo() {
Map<String, String> expected = new HashMap<String, String>() {
{
put("channel", "MOBILE");
put("appStartId", APP_START_ID);
put("username", "Ben");
put("accountStatus", LOCKED);
}
};
// MapModifier
MapModifier<String, String> modifier = new MapModifier<String, String>()
.putAll(commonProperties)
.put("username", "Ben")
.put("accountStatus", LOCKED);
// 从 Supplier 中获取 Map并修改数据
HashMap<String, String> hashMap1 = modifier.getAndModify(HashMap::new);
assertEquals(expected, hashMap1);
// 可以灵活使用不同 Map 类型的不同构造器
HashMap<String, String> hashMap2 = modifier.getAndModify(() -> new HashMap<>(8));
assertEquals(expected, hashMap2);
// HashMap<String, String> hashMap3 = modifier.getAndModify(() -> new HashMap<>(anotherMap));
TreeMap<String, String> treeMap = modifier.getAndModify(TreeMap::new);
assertEquals(expected, treeMap);
ConcurrentHashMap<String, String> concurrentHashMap = modifier.getAndModify(ConcurrentHashMap::new);
assertEquals(expected, concurrentHashMap);
assertNull(modifier.getAndModify(() -> (Map<String, String>) null));
// 修改已有的 Map
Map<String, String> srcMap = new HashMap<>();
srcMap.put("srcKey1", "srcValue1");
srcMap.put("srcKey2", "srcValue2");
modifier.modify(srcMap);
assertEquals(new HashMap<String, String>() {
{
putAll(commonProperties);
put("username", "Ben");
put("accountStatus", LOCKED);
put("srcKey1", "srcValue1");
put("srcKey2", "srcValue2");
}
}, srcMap);
assertDoesNotThrow(() -> modifier.modify((Map<String, String>) null));
// 创建一个有初始化数据的不可变的 {@code Map}
Map<String, String> unmodifiableMap = modifier.getUnmodifiableMap();
assertEquals(expected, unmodifiableMap);
assertThrows(UnsupportedOperationException.class,
() -> unmodifiableMap.put("key", "value"));
}
@Test
void createAndInitData() {
// 链式调用创建并初始化数据
HashMap<String, String> map = new MapModifier<String, String>()
.putAll(commonProperties)
.put("username", "Ben")
.put("accountStatus", LOCKED)
.getAndModify(HashMap::new);
HashMap<String, String> expected = new HashMap<String, String>() {
{
put("channel", "MOBILE");
put("appStartId", APP_START_ID);
put("username", "Ben");
put("accountStatus", LOCKED);
}
};
assertEquals(expected, map);
}
@Test
void put() {
Map<String, String> map = new MapModifier<String, String>()
.put("key1", "value0")
.put("key1", "value1")
.getAndModify(HashMap::new);
assertEquals(new HashMap<String, String>() {
{
put("key1", "value0");
put("key1", "value1");
}
}, map);
new MapModifier<String, String>()
.put("key1", "newValue1")
.put("key2", null)
.modify(map);
assertEquals("newValue1", map.get("key1"));
assertTrue(map.containsKey("key2"));
assertNull(map.get("key2"));
}
@Test
void putIfAbsent() {
Map<String, String> map = new MapModifier<String, String>()
.putIfAbsent("key1", null)
.putIfAbsent("key1", "value1")
.putIfAbsent("key1", "value2")
.getAndModify(HashMap::new);
assertEquals(new HashMap<String, String>() {
{
putIfAbsent("key1", null);
putIfAbsent("key1", "value1");
putIfAbsent("key1", "value2");
}
}, map);
new MapModifier<String, String>()
.putIfAbsent("key1", "newValue1")
.modify(map);
assertTrue(map.containsKey("key1"));
assertEquals("value1", map.get("key1"));
}
@Test
void putAll_map() {
Map<String, String> entries = new HashMap<String, String>() {
{
put("key1", "value1");
put("key2", "value2");
}
};
Map<String, String> map = new MapModifier<String, String>()
.putAll((Map<String, String>) null)
.putAll(Collections.emptyMap())
.putAll(entries)
.getAndModify(HashMap::new);
assertEquals(entries, map);
new MapModifier<String, String>()
.putAll(new HashMap<String, String>() {
{
put("key2", "newValue2");
put("key3", "value3");
}
})
.modify(map);
assertEquals(new HashMap<String, String>() {
{
put("key1", "value1");
put("key2", "value2");
put("key2", "newValue2");
put("key3", "value3");
}
}, map);
}
@Test
void putAll_entries() {
Map<String, String> entries = new HashMap<String, String>() {
{
put("key1", "value1");
put("key2", "value2");
}
};
Map<String, String> map = new MapModifier<String, String>()
.putAll(new SimpleEntry<>("key1", "value1"),
new SimpleEntry<>("key2", "value2"))
.getAndModify(HashMap::new);
assertEquals(entries, map);
new MapModifier<String, String>()
.putAll()
.putAll(new SimpleEntry<>("key2", "newValue2"),
new SimpleEntry<>("key3", "value3"))
.modify(map);
assertEquals(new HashMap<String, String>() {
{
put("key1", "value1");
put("key2", "value2");
put("key2", "newValue2");
put("key3", "value3");
}
}, map);
}
@Test
void computeIfAbsent_keyAndFunction() {
Map<String, String> map = new MapModifier<String, String>()
.computeIfAbsent("key1", k -> null)
.computeIfAbsent("key1", k -> "value1")
.computeIfAbsent("key1", k -> "value2")
.getAndModify(HashMap::new);
assertEquals(new HashMap<String, String>() {
{
computeIfAbsent("key1", k -> null);
computeIfAbsent("key1", k -> "value1");
computeIfAbsent("key1", k -> "value2");
}
}, map);
new MapModifier<String, String>()
.computeIfAbsent("key1", k -> "newValue1")
.modify(map);
assertTrue(map.containsKey("key1"));
assertEquals("value1", map.get("key1"));
}
@Test
void computeIfPresent_keyAndBiFunction() {
Map<String, String> map = new HashMap<String, String>() {{
put("key1", "value1");
}};
new MapModifier<String, String>()
.computeIfPresent("key1", (k, v) -> k + v)
.computeIfPresent("key2", (k, v) -> k + v)
.modify(map);
assertEquals(new HashMap<String, String>() {{
put("key1", "key1value1");
}}, map);
}
@Test
void remove() {
Map<String, String> map = new HashMap<String, String>() {{
put("key1", "value1");
put("key2", "value2");
}};
new MapModifier<String, String>()
.remove("key2")
.modify(map);
assertEquals(new HashMap<String, String>() {{
put("key1", "value1");
}}, map);
}
@Test
void clear() {
Map<String, String> map = new HashMap<String, String>() {{
put("key1", "value1");
put("key2", "value2");
}};
new MapModifier<String, String>()
.clear()
.modify(map);
assertTrue(map.isEmpty());
}
@Getter
static class SimpleEntry<K, V> implements Map.Entry<K, V> {
private final K key;
private final V value;
public SimpleEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public V setValue(@Nullable V value) {
throw new UnsupportedOperationException("Unimplemented method 'setValue'");
}
}
}

View File

@@ -38,7 +38,6 @@ public class InvalidInputExceptionTests {
throw InvalidInputException.Type.CONTAINS_ILLEGAL_AND_MALICIOUS_LINKS.create();
});
assertSame(InvalidInputException.Type.CONTAINS_ILLEGAL_AND_MALICIOUS_LINKS, e.getType());
assertEquals(InvalidInputException.Type.CONTAINS_ILLEGAL_AND_MALICIOUS_LINKS.getCode(), e.getTypeCode());
assertEquals(InvalidInputException.Type.CONTAINS_ILLEGAL_AND_MALICIOUS_LINKS.getDefaultMessage(), e.getMessage());
assertNull(e.getCause());
}
@@ -50,7 +49,6 @@ public class InvalidInputExceptionTests {
throw InvalidInputException.Type.CONTAINS_ILLEGAL_WORDS.create(message);
});
assertSame(InvalidInputException.Type.CONTAINS_ILLEGAL_WORDS, e.getType());
assertEquals(InvalidInputException.Type.CONTAINS_ILLEGAL_WORDS.getCode(), e.getTypeCode());
assertEquals(message, e.getMessage());
assertNull(e.getCause());
}
@@ -62,7 +60,6 @@ public class InvalidInputExceptionTests {
throw InvalidInputException.Type.PICTURE_CONTAINS_ILLEGAL_INFORMATION.create(message);
});
assertSame(InvalidInputException.Type.PICTURE_CONTAINS_ILLEGAL_INFORMATION, e.getType());
assertEquals(InvalidInputException.Type.PICTURE_CONTAINS_ILLEGAL_INFORMATION.getCode(), e.getTypeCode());
assertNull(e.getMessage());
assertNull(e.getCause());
}
@@ -77,7 +74,6 @@ public class InvalidInputExceptionTests {
});
assertSame(InvalidInputException.Type.INFRINGE_COPYRIGHT, e.getType());
assertEquals(InvalidInputException.Type.INFRINGE_COPYRIGHT.getCode(), e.getTypeCode());
log.info("{}", e.getMessage());
assertEquals(nfe.toString(), e.getMessage());
assertSame(nfe, e.getCause());
@@ -92,7 +88,6 @@ public class InvalidInputExceptionTests {
});
assertSame(InvalidInputException.Type.DEFAULT, e.getType());
assertEquals(InvalidInputException.Type.DEFAULT.getCode(), e.getTypeCode());
assertNull(e.getMessage());
assertNull(e.getCause());
}
@@ -106,7 +101,6 @@ public class InvalidInputExceptionTests {
throw InvalidInputException.Type.CONTAINS_ILLEGAL_AND_MALICIOUS_LINKS.create(message, nfe);
});
assertSame(InvalidInputException.Type.CONTAINS_ILLEGAL_AND_MALICIOUS_LINKS, e.getType());
assertEquals(InvalidInputException.Type.CONTAINS_ILLEGAL_AND_MALICIOUS_LINKS.getCode(), e.getTypeCode());
assertEquals(message, e.getMessage());
assertSame(nfe, e.getCause());
}
@@ -120,7 +114,6 @@ public class InvalidInputExceptionTests {
throw InvalidInputException.Type.CONTAINS_ILLEGAL_WORDS.create(message, nfe);
});
assertSame(InvalidInputException.Type.CONTAINS_ILLEGAL_WORDS, e.getType());
assertEquals(InvalidInputException.Type.CONTAINS_ILLEGAL_WORDS.getCode(), e.getTypeCode());
assertNull(e.getMessage());
assertSame(nfe, e.getCause());
}
@@ -134,7 +127,6 @@ public class InvalidInputExceptionTests {
throw InvalidInputException.Type.CONTAINS_ILLEGAL_WORDS.create(message, npe);
});
assertSame(InvalidInputException.Type.CONTAINS_ILLEGAL_WORDS, e.getType());
assertEquals(InvalidInputException.Type.CONTAINS_ILLEGAL_WORDS.getCode(), e.getTypeCode());
assertEquals(message, e.getMessage());
assertNull(e.getCause());
}
@@ -148,7 +140,6 @@ public class InvalidInputExceptionTests {
throw InvalidInputException.Type.CONTAINS_ILLEGAL_WORDS.create(message, nfe);
});
assertSame(InvalidInputException.Type.CONTAINS_ILLEGAL_WORDS, e.getType());
assertEquals(InvalidInputException.Type.CONTAINS_ILLEGAL_WORDS.getCode(), e.getTypeCode());
assertNull(e.getMessage());
assertNull(e.getCause());
}
@@ -167,7 +158,6 @@ public class InvalidInputExceptionTests {
throw new InvalidInputException();
});
assertSame(InvalidInputException.Type.DEFAULT, e.getType());
assertEquals(InvalidInputException.Type.DEFAULT.getCode(), e.getTypeCode());
assertEquals(InvalidInputException.Type.DEFAULT.getDefaultMessage(), e.getMessage());
assertNull(e.getCause());
}
@@ -179,7 +169,6 @@ public class InvalidInputExceptionTests {
throw new InvalidInputException(message);
});
assertSame(InvalidInputException.Type.DEFAULT, e.getType());
assertEquals(InvalidInputException.Type.DEFAULT.getCode(), e.getTypeCode());
assertEquals(message, e.getMessage());
assertNull(e.getCause());
}
@@ -191,7 +180,6 @@ public class InvalidInputExceptionTests {
throw new InvalidInputException(message);
});
assertSame(InvalidInputException.Type.DEFAULT, e.getType());
assertEquals(InvalidInputException.Type.DEFAULT.getCode(), e.getTypeCode());
assertNull(e.getMessage());
assertNull(e.getCause());
}
@@ -206,7 +194,6 @@ public class InvalidInputExceptionTests {
});
assertSame(InvalidInputException.Type.DEFAULT, e.getType());
assertEquals(InvalidInputException.Type.DEFAULT.getCode(), e.getTypeCode());
log.info("{}", e.getMessage());
assertEquals(nfe.toString(), e.getMessage());
assertSame(nfe, e.getCause());
@@ -221,7 +208,6 @@ public class InvalidInputExceptionTests {
});
assertSame(InvalidInputException.Type.DEFAULT, e.getType());
assertEquals(InvalidInputException.Type.DEFAULT.getCode(), e.getTypeCode());
assertNull(e.getMessage());
assertNull(e.getCause());
}
@@ -235,7 +221,6 @@ public class InvalidInputExceptionTests {
throw new InvalidInputException(message, nfe);
});
assertSame(InvalidInputException.Type.DEFAULT, e.getType());
assertEquals(InvalidInputException.Type.DEFAULT.getCode(), e.getTypeCode());
assertEquals(message, e.getMessage());
assertSame(nfe, e.getCause());
}
@@ -249,7 +234,6 @@ public class InvalidInputExceptionTests {
throw new InvalidInputException(message, nfe);
});
assertSame(InvalidInputException.Type.DEFAULT, e.getType());
assertEquals(InvalidInputException.Type.DEFAULT.getCode(), e.getTypeCode());
assertNull(e.getMessage());
assertSame(nfe, e.getCause());
}
@@ -263,7 +247,6 @@ public class InvalidInputExceptionTests {
throw new InvalidInputException(message, npe);
});
assertSame(InvalidInputException.Type.DEFAULT, e.getType());
assertEquals(InvalidInputException.Type.DEFAULT.getCode(), e.getTypeCode());
assertEquals(message, e.getMessage());
assertNull(e.getCause());
}
@@ -277,7 +260,6 @@ public class InvalidInputExceptionTests {
throw new InvalidInputException(message, nfe);
});
assertSame(InvalidInputException.Type.DEFAULT, e.getType());
assertEquals(InvalidInputException.Type.DEFAULT.getCode(), e.getTypeCode());
assertNull(e.getMessage());
assertNull(e.getCause());
}

View File

@@ -41,7 +41,6 @@ public class ParsingFailureExceptionTests {
throw ParsingFailureException.DATE_TIME_PARSING_FAILURE.create();
});
assertSame(ParsingFailureException.DATE_TIME_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.DATE_TIME_PARSING_FAILURE.getCode(), e.getTypeCode());
assertEquals(ParsingFailureException.DATE_TIME_PARSING_FAILURE.getDefaultMessage(), e.getMessage());
assertNull(e.getCause());
}
@@ -53,7 +52,6 @@ public class ParsingFailureExceptionTests {
throw ParsingFailureException.JSON_PARSING_FAILURE.create(message);
});
assertSame(ParsingFailureException.Type.JSON_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.Type.JSON_PARSING_FAILURE.getCode(), e.getTypeCode());
assertEquals(message, e.getMessage());
assertNull(e.getCause());
}
@@ -65,7 +63,6 @@ public class ParsingFailureExceptionTests {
throw ParsingFailureException.XML_PARSING_FAILURE.create(message);
});
assertSame(ParsingFailureException.XML_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.XML_PARSING_FAILURE.getCode(), e.getTypeCode());
assertNull(e.getMessage());
assertNull(e.getCause());
}
@@ -80,7 +77,6 @@ public class ParsingFailureExceptionTests {
});
assertSame(ParsingFailureException.NUMBER_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.NUMBER_PARSING_FAILURE.getCode(), e.getTypeCode());
log.info("{}", e.getMessage());
assertEquals(nfe.toString(), e.getMessage());
assertSame(nfe, e.getCause());
@@ -95,7 +91,6 @@ public class ParsingFailureExceptionTests {
});
assertSame(ParsingFailureException.NUMBER_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.NUMBER_PARSING_FAILURE.getCode(), e.getTypeCode());
assertNull(e.getMessage());
assertNull(e.getCause());
}
@@ -109,7 +104,6 @@ public class ParsingFailureExceptionTests {
throw ParsingFailureException.NUMBER_PARSING_FAILURE.create(message, nfe);
});
assertSame(ParsingFailureException.NUMBER_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.NUMBER_PARSING_FAILURE.getCode(), e.getTypeCode());
assertEquals(message, e.getMessage());
assertSame(nfe, e.getCause());
}
@@ -123,7 +117,6 @@ public class ParsingFailureExceptionTests {
throw ParsingFailureException.DATE_TIME_PARSING_FAILURE.create(message, nfe);
});
assertSame(ParsingFailureException.DATE_TIME_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.DATE_TIME_PARSING_FAILURE.getCode(), e.getTypeCode());
assertNull(e.getMessage());
assertSame(nfe, e.getCause());
}
@@ -137,7 +130,6 @@ public class ParsingFailureExceptionTests {
throw ParsingFailureException.DATE_TIME_PARSING_FAILURE.create(message, npe);
});
assertSame(ParsingFailureException.DATE_TIME_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.DATE_TIME_PARSING_FAILURE.getCode(), e.getTypeCode());
assertEquals(message, e.getMessage());
assertNull(e.getCause());
}
@@ -151,7 +143,6 @@ public class ParsingFailureExceptionTests {
throw ParsingFailureException.DATE_TIME_PARSING_FAILURE.create(message, nfe);
});
assertSame(ParsingFailureException.DATE_TIME_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.DATE_TIME_PARSING_FAILURE.getCode(), e.getTypeCode());
assertNull(e.getMessage());
assertNull(e.getCause());
}
@@ -175,7 +166,6 @@ public class ParsingFailureExceptionTests {
});
assertSame(ParsingFailureException.DATE_TIME_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.DATE_TIME_PARSING_FAILURE.getCode(), e.getTypeCode());
assertEquals(dtpe.getMessage(), e.getMessage());
assertSame(dtpe, e.getCause());
}
@@ -189,7 +179,6 @@ public class ParsingFailureExceptionTests {
});
assertSame(ParsingFailureException.DATE_TIME_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.DATE_TIME_PARSING_FAILURE.getCode(), e.getTypeCode());
assertEquals(ParsingFailureException.DATE_TIME_PARSING_FAILURE.getDefaultMessage(), e.getMessage());
assertNull(e.getCause());
}
@@ -206,7 +195,6 @@ public class ParsingFailureExceptionTests {
});
assertSame(ParsingFailureException.DATE_TIME_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.DATE_TIME_PARSING_FAILURE.getCode(), e.getTypeCode());
assertEquals(message, e.getMessage());
assertSame(dtpe, e.getCause());
}
@@ -223,7 +211,6 @@ public class ParsingFailureExceptionTests {
});
assertSame(ParsingFailureException.DATE_TIME_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.DATE_TIME_PARSING_FAILURE.getCode(), e.getTypeCode());
assertNull(e.getMessage());
assertSame(dtpe, e.getCause());
}
@@ -238,7 +225,6 @@ public class ParsingFailureExceptionTests {
});
assertSame(ParsingFailureException.DATE_TIME_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.DATE_TIME_PARSING_FAILURE.getCode(), e.getTypeCode());
assertEquals(message, e.getMessage());
assertNull(e.getCause());
}
@@ -253,7 +239,6 @@ public class ParsingFailureExceptionTests {
});
assertSame(ParsingFailureException.DATE_TIME_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.DATE_TIME_PARSING_FAILURE.getCode(), e.getTypeCode());
assertNull(e.getMessage());
assertNull(e.getCause());
}
@@ -277,7 +262,6 @@ public class ParsingFailureExceptionTests {
});
assertSame(ParsingFailureException.NUMBER_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.NUMBER_PARSING_FAILURE.getCode(), e.getTypeCode());
assertEquals(dtpe.getMessage(), e.getMessage());
assertSame(dtpe, e.getCause());
}
@@ -291,7 +275,6 @@ public class ParsingFailureExceptionTests {
});
assertSame(ParsingFailureException.NUMBER_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.NUMBER_PARSING_FAILURE.getCode(), e.getTypeCode());
assertEquals(ParsingFailureException.NUMBER_PARSING_FAILURE.getDefaultMessage(), e.getMessage());
assertNull(e.getCause());
}
@@ -308,7 +291,6 @@ public class ParsingFailureExceptionTests {
});
assertSame(ParsingFailureException.NUMBER_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.NUMBER_PARSING_FAILURE.getCode(), e.getTypeCode());
assertEquals(message, e.getMessage());
assertSame(dtpe, e.getCause());
}
@@ -325,7 +307,6 @@ public class ParsingFailureExceptionTests {
});
assertSame(ParsingFailureException.NUMBER_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.NUMBER_PARSING_FAILURE.getCode(), e.getTypeCode());
assertNull(e.getMessage());
assertSame(dtpe, e.getCause());
}
@@ -340,7 +321,6 @@ public class ParsingFailureExceptionTests {
});
assertSame(ParsingFailureException.NUMBER_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.NUMBER_PARSING_FAILURE.getCode(), e.getTypeCode());
assertEquals(message, e.getMessage());
assertNull(e.getCause());
}
@@ -355,7 +335,6 @@ public class ParsingFailureExceptionTests {
});
assertSame(ParsingFailureException.NUMBER_PARSING_FAILURE, e.getType());
assertEquals(ParsingFailureException.NUMBER_PARSING_FAILURE.getCode(), e.getTypeCode());
assertNull(e.getMessage());
assertNull(e.getCause());
}

Some files were not shown because too many files have changed in this diff Show More