Compare commits

..
15 Commits
Author SHA1 Message Date
minglipro ae41240806 v5.5.5
Gitea Actions Build / Build (push) Canceled after 0s
2026-11-18 19:46:57 +08:00
minglipro cb7fdb4f19 添加 import org.springframework.context.event.EventListener 2026-11-18 19:46:10 +08:00
minglipro 3d1896bd64 删除
import com.mingliqiye.utils.springboot.annotation.ContextClosedEventListener
2026-11-18 19:46:00 +08:00
minglipro 0e0d2b03cc 修复
Okhttp3AutoConfiguration->handleContextClosed
不触发
2026-11-18 19:45:21 +08:00
minglipro 2e54e3d651 chore(release): 发布 5.5.4
Gitea Actions Build / Build (push) Canceled after 0s
版本号升级至 5.5.4,CHANGELOG 记录 hash 哈希体系、springboot 注解
迁移、Log4j2 XSD、MediaType 格式化与 signing 笔误修复。
2026-11-18 18:57:59 +08:00
minglipro 528802d881 fix(build): 修正 signing.secretKeyRingFile 属性名笔误 2026-11-18 18:57:59 +08:00
minglipro 487f956f4f style(http): MediaType 枚举项之间补充空行 2026-11-18 18:57:59 +08:00
minglipro 64e3af50ed test(resources): 新增 Log4j2 配置 XSD 并接入 Schema 校验
非官方 Log4j2 配置 Schema,覆盖 21 种 Appender、13 种 Layout、
11 种 Filter、滚动策略与清理条件等;未知插件元素以开放内容模型放行。
2026-11-18 18:57:59 +08:00
minglipro 7760201639 refactor(springboot): 事件监听注解迁移为 Java 实现
新增 ApplicationReadyEventListener、ContextClosedEventListener;
ApplicationStartedRunner、ApplicationDestroyedRunner 标记废弃;
移除 Kotlin 版注解与 ApplicationListener、ApplicationRunnerData;
Okhttp3AutoConfiguration 改用 @ContextClosedEventListener。
2026-11-18 18:57:51 +08:00
minglipro 713342bbc6 feat(hash): 新增 HashCodec 哈希体系与 13 种 JDK 标准算法实现
HashCodec 接口只需重写 hash(InputStream),其余重载、十六进制输出与
常量时间校验均由默认实现提供;MessageDigestCodec 流式基类 8KB 缓冲、
恒定内存、不关闭调用方流;提供 HashUtils 懒加载单例与 HashType 枚举,
TestHash 覆盖已知向量、算法一致性、流生命周期与文件/路径重载。
2026-11-18 18:57:46 +08:00
minglipro 988a0c0dc1 v5.5.3
Gitea Actions Build / Build (push) Canceled after 0s
2026-11-18 00:03:40 +08:00
minglipro 44ea9b114d v5.4.5 修复 java.lang.NoClassDefFoundError: com/google/gson/JsonParseException 2026-11-18 00:03:21 +08:00
minglipro 3bacf90940 v5.4.5 修复 java.lang.NoClassDefFoundError: com/google/gson/JsonParseException
Gitea Actions Build / Build (push) Canceled after 0s
2026-11-18 00:02:34 +08:00
minglipro 28a2987dc3 fix(json): 修正 BaseJsonWriter 中 BaseJsonJudgment 的导入路径
Gitea Actions Build / Build (push) Canceled after 0s
2026-11-17 21:18:25 +08:00
minglipro 8069de37f2 feat(tuple): 实现 Tuple.compareTo 字典序比较并发布 5.5.2
替换原 TODO 占位实现:同类型可比较元素按自然顺序逐位比较,其余按
字符串形式回退,公共前缀相等时短元组在前;新增 TestTuple 6 个用例
全部通过;CHANGELOG 增加 5.5.2 条目,VERSIONS 5.5.1 -> 5.5.2。
2026-11-17 21:17:01 +08:00
37 changed files with 4804 additions and 297 deletions
+49 -1
View File
@@ -1,10 +1,52 @@
# Changelog
![Maven Central](https://img.shields.io/maven-metadata/v.svg?metadataUrl=https://repository.mingliqiye.com/repository/maven-public/com/mingliqiye/utils/mingli-utils/maven-metadata.xml&label=Mingliqiye%20Maven%20Public)
本文件记录 mingli-utils 各版本的主要变更。
## [5.5.4] - 2026-11-18
### 新增
- **hash**:新增 `HashCodec` 哈希编解码器接口——实现类只需重写 `hash(InputStream)` 一个方法,
字节数组/字符串/文件/路径重载、十六进制输出(`hashHex`)与基于 `MessageDigest.isEqual`
的常量时间校验(`verifyHash`)均由默认实现提供;新增 `MessageDigestCodec` 流式基类
(8KB 缓冲、恒定内存、不关闭调用方流)及 13 种 JDK 标准算法实现
(MD2、MD5、SHA-1、SHA-224/256/384/512、SHA-512/224、SHA-512/256、SHA3-224/256/384/512);
提供 `HashUtils` 懒加载单例(`MD2`~`SHA512256`)与 `HashType` 枚举;
新增 `TestHash` 测试覆盖已知向量、全部算法一致性、流生命周期与文件/路径重载。
- **test**:新增非官方 Log4j2 配置 XSD(覆盖 21 种 Appender、13 种 Layout、11 种 Filter、
滚动策略与清理条件等,未知插件元素以开放内容模型放行),`log4j2.xml` 接入 Schema 校验。
### 变更
- **springboot**:事件监听注解迁移为 Java 实现——新增 `ApplicationReadyEventListener`、
`ContextClosedEventListener`;`ApplicationStartedRunner`、`ApplicationDestroyedRunner`
标记为废弃;移除 Kotlin 版注解及 `ApplicationListener`、`ApplicationRunnerData`;
`Okhttp3AutoConfiguration` 改用 `@ContextClosedEventListener`。
- **http**:`MediaType` 枚举项之间补充空行(纯格式化,无内容变更)。
### 修复
- **build**:修正 `signing.secretKeyRingFile` 属性名笔误(误插入空格)。
### 文档
- hash 包全部接口、类、枚举与懒加载单例补全中文 KDoc;
4 个 Spring Boot 事件监听注解补全 Javadoc。
## [5.5.2] - 2026-11-17
### 新增
- **tuple**:实现 `Tuple.compareTo` 字典序比较——同类型可比较元素按自然顺序,
其余按字符串形式比较;公共前缀相等时元素个数较少的元组在前。
新增 `TestTuple` 测试覆盖 6 种比较场景。
## [5.5.1] - 2026-11-17
### 新增
- **json**:新增 `reader` / `witer` / `judgment` 三组抽象,为 Jackson2 与 Jackson3 分别提供
`JsonReader`、`JsonArrayReader`、`JsonObjectReader`、`JsonWriter`、`ArrayWriter`、`ObjectWriter`
与 `ReaderJudgment` 实现(`BaseJsonReader` / `BaseJsonWriter` / `BaseJsonJudgment` 等基类)。
@@ -13,32 +55,38 @@
`toString()` 输出包含 `zoneId`。
### 变更
- **json**:重构转换器体系——移除按类型划分的 `BaseJsonIntConverter`、`BaseJsonStringConverter`
等 10 个转换器及 `JsonConverter` 接口,统一由 `BaseJsonConverter` 与 `JsonConverterUtils` 处理;
简化 `DateTimeJsonConverter`、`UUIDJsonConverter`、`NetworkEndpointJsonConverter` 与
Jackson2/Jackson3 序列化/反序列化桥接实现;精简 `JSONA` 与 `JsonApi` 门面。
- **tuple**:`Tuple` 实现 `Comparable<Tuple>`,迭代器改为基于 `toMutableList()` 的简化实现。
- **tuple**:`Tuple` 声明实现 `Comparable<Tuple>`;迭代器改为基于 `toMutableList()` 的简化实现。
- **springboot**:`JsonAutoConfiguration` 与 `JacksonJsonBuilder` / `JacksonJsonBuilderImpl`
同步适配新的 JSON 转换器体系。
### 文档
- 补全 src 下全部 Kotlin 文件的中文 KDoc 与 Java 文件的 Javadoc(约 1.3 万处),
覆盖 exception、json、springboot、mybatis/mybatisplus、thread/netty/http、
Tuple1~Tuple100 生成类、MediaType 全部枚举项及测试代码;已有文档保持不变。
## [5.4.4] - 2026-11-17
- 构建脚本调整(build.gradle.kts 发布配置完善)。
- SpringBoot 自动配置重构:新增 `JsonAutoConfiguration` 与 `JacksonBuilder`,
精简 Jackson2/Jackson3 JsonApi 自动配置。
## [5.4.3] - 2026-11-17
- 新增 `JacksonJsonBuilder` / `JacksonJsonBuilderImpl` 构建器。
- `DateTime`、`UUID` 小幅调整;补充 log4j2 测试配置。
## [5.4.2] - 2026-11
- 修复 `JSONA.jsonApi` 编译错误。
- **mybatisplus**:新增 `FastBaseIServiceNew3518`(适配 MyBatis-Plus 3.5.18)。
## [5.4.0] - 2026-11
- **mybatisplus**:新增 `FastBaseIService`。
- 全项目统一 Tab 缩进并补全尾随逗号。
+1 -2
View File
@@ -16,13 +16,12 @@
* ProjectName mingli-utils
* ModuleName mingli-utils
* CurrentFile build.gradle.kts
* LastUpdate 2026-11-17 10:19:02
* LastUpdate 2026-11-18 08:42:41
* UpdateUser MingLiPro
*/
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import kotlin.math.sign
/*
* Copyright 2026 mingliqiye
+2 -2
View File
@@ -16,10 +16,10 @@
# ProjectName mingli-utils
# ModuleName mingli-utils
# CurrentFile gradle.properties
# LastUpdate 2026-11-17 09:07:20
# LastUpdate 2026-11-18 19:46:50
# UpdateUser MingLiPro
#
JDKVERSIONS=17
GROUPSID=com.mingliqiye.utils
ARTIFACTID=mingli-utils
VERSIONS=5.5.1
VERSIONS=5.5.5
@@ -0,0 +1,83 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ApplicationDestroyedRunner.java
* LastUpdate 2026-11-18 08:21:37
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AliasFor;
import org.springframework.core.annotation.Order;
import java.lang.annotation.*;
/**
* 应用销毁(上下文关闭)事件监听注解。
*
* <p>标注在 Spring Bean 的方法上,当 Spring 应用上下文关闭
* ({@link ContextClosedEvent} 发布)时自动调用该方法。</p>
*
* @deprecated 已弃用,请改用 {@link ContextClosedEventListener}(监听相同事件,命名更规范)。
* @see ContextClosedEventListener
* @see EventListener
* @see ContextClosedEvent
*/
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@EventListener(ContextClosedEvent.class)
@Order
@Deprecated(since = "use ApplicationReadyEventListener")
public @interface ApplicationDestroyedRunner {
/**
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
*
* @return 条件表达式,默认为空字符串(无条件执行)
*/
@AliasFor(annotation = EventListener.class, attribute = "condition")
String condition() default "";
/**
* 当事件不是 {@link ContextClosedEvent} 类型时是否仍默认执行监听方法。
*
* @return 是否默认执行,默认为 true
*/
@AliasFor(annotation = EventListener.class, attribute = "defaultExecution")
boolean defaultExecution() default true;
/**
* 监听器的唯一标识,用于注册可指定 id 的监听器。
*
* @return 监听器 id,默认为空字符串(自动生成)
*/
@AliasFor(annotation = EventListener.class, attribute = "id")
String id() default "";
/**
* 监听器的执行顺序,值越小优先级越高。
*
* @return 顺序值,默认为 {@link Ordered#LOWEST_PRECEDENCE}
* @see Ordered#getOrder()
*/
@AliasFor(annotation = Order.class, attribute = "value")
int order() default Ordered.LOWEST_PRECEDENCE;
}
@@ -0,0 +1,95 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ApplicationReadyEventListener.java
* LastUpdate 2026-11-18 08:21:57
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AliasFor;
import org.springframework.core.annotation.Order;
import java.lang.annotation.*;
/**
* 应用就绪事件监听注解。
*
* <p>标注在 Spring Bean 的方法上,当 Spring Boot 应用完成启动并就绪
* ({@link ApplicationReadyEvent} 发布)时自动调用该方法,
* 等价于 {@code @EventListener(ApplicationReadyEvent.class)} 的组合简化写法。</p>
*
* <p>使用示例:</p>
* <pre>{@code
* @Component
* public class InitTask {
* @ApplicationReadyEventListener(order = 0)
* public void onReady() {
* // 应用就绪后执行的初始化逻辑
* }
* }
* }</pre>
*
* @see EventListener
* @see ApplicationReadyEvent
*/
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@EventListener(ApplicationReadyEvent.class)
@Order
public @interface ApplicationReadyEventListener {
/**
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
*
* @return 条件表达式,默认为空字符串(无条件执行)
*/
@AliasFor(annotation = EventListener.class, attribute = "condition")
String condition() default "";
/**
* 当事件不是 {@link ApplicationReadyEvent} 类型时是否仍默认执行监听方法。
*
* @return 是否默认执行,默认为 true
*/
@AliasFor(annotation = EventListener.class, attribute = "defaultExecution")
boolean defaultExecution() default true;
/**
* 监听器的唯一标识,用于注册可指定 id 的监听器。
*
* @return 监听器 id,默认为空字符串(自动生成)
*/
@AliasFor(annotation = EventListener.class, attribute = "id")
String id() default "";
/**
* 监听器的执行顺序,值越小优先级越高。
*
* @return 顺序值,默认为 {@link Ordered#LOWEST_PRECEDENCE}
* @see Ordered#getOrder()
*/
@AliasFor(annotation = Order.class, attribute = "value")
int order() default Ordered.LOWEST_PRECEDENCE;
}
@@ -0,0 +1,84 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ApplicationStartedRunner.java
* LastUpdate 2026-11-18 08:21:57
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AliasFor;
import org.springframework.core.annotation.Order;
import java.lang.annotation.*;
/**
* 应用启动完成事件监听注解。
*
* <p>标注在 Spring Bean 的方法上,当 Spring Boot 应用完成启动并就绪
* ({@link ApplicationReadyEvent} 发布)时自动调用该方法。</p>
*
* @deprecated 已弃用,请改用 {@link ApplicationReadyEventListener}(功能完全一致,命名更规范)。
* @see ApplicationReadyEventListener
* @see EventListener
* @see ApplicationReadyEvent
*/
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@EventListener(ApplicationReadyEvent.class)
@Order
@Deprecated(since = "use ApplicationReadyEventListener")
public @interface ApplicationStartedRunner {
/**
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
*
* @return 条件表达式,默认为空字符串(无条件执行)
*/
@AliasFor(annotation = EventListener.class, attribute = "condition")
String condition() default "";
/**
* 当事件不是 {@link ApplicationReadyEvent} 类型时是否仍默认执行监听方法。
*
* @return 是否默认执行,默认为 true
*/
@AliasFor(annotation = EventListener.class, attribute = "defaultExecution")
boolean defaultExecution() default true;
/**
* 监听器的唯一标识,用于注册可指定 id 的监听器。
*
* @return 监听器 id,默认为空字符串(自动生成)
*/
@AliasFor(annotation = EventListener.class, attribute = "id")
String id() default "";
/**
* 监听器的执行顺序,值越小优先级越高。
*
* @return 顺序值,默认为 {@link Ordered#LOWEST_PRECEDENCE}
* @see Ordered#getOrder()
*/
@AliasFor(annotation = Order.class, attribute = "value")
int order() default Ordered.LOWEST_PRECEDENCE;
}
@@ -0,0 +1,93 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ContextClosedEventListener.java
* LastUpdate 2026-11-18 08:21:23
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AliasFor;
import org.springframework.core.annotation.Order;
import java.lang.annotation.*;
/**
* 应用上下文关闭事件监听注解。
*
* <p>标注在 Spring Bean 的方法上,当 Spring 应用上下文关闭
* ({@link ContextClosedEvent} 发布)时自动调用该方法,
* 等价于 {@code @EventListener(ContextClosedEvent.class)} 的组合简化写法,
* 适用于应用停机前的资源清理、状态保存等场景。</p>
*
* <p>使用示例:</p>
* <pre>{@code
* @Component
* public class CleanupTask {
* @ContextClosedEventListener
* public void onClosed() {
* // 上下文关闭前执行的清理逻辑
* }
* }
* }</pre>
*
* @see EventListener
* @see ContextClosedEvent
*/
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@EventListener(ContextClosedEvent.class)
@Order
public @interface ContextClosedEventListener {
/**
* SpEL 条件表达式,仅当表达式求值为 true 时才执行监听方法。
*
* @return 条件表达式,默认为空字符串(无条件执行)
*/
@AliasFor(annotation = EventListener.class, attribute = "condition")
String condition() default "";
/**
* 当事件不是 {@link ContextClosedEvent} 类型时是否仍默认执行监听方法。
*
* @return 是否默认执行,默认为 true
*/
@AliasFor(annotation = EventListener.class, attribute = "defaultExecution")
boolean defaultExecution() default true;
/**
* 监听器的唯一标识,用于注册可指定 id 的监听器。
*
* @return 监听器 id,默认为空字符串(自动生成)
*/
@AliasFor(annotation = EventListener.class, attribute = "id")
String id() default "";
/**
* 监听器的执行顺序,值越小优先级越高。
*
* @return 顺序值,默认为 {@link Ordered#LOWEST_PRECEDENCE}
* @see Ordered#getOrder()
*/
@AliasFor(annotation = Order.class, attribute = "value")
int order() default Ordered.LOWEST_PRECEDENCE;
}
@@ -0,0 +1,81 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile HashType.kt
* LastUpdate 2026-11-18 18:48:01
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash
import com.mingliqiye.utils.hash.code.HashCodec
import java.io.InputStream
/**
* 哈希算法类型枚举。
*
* 每个枚举项持有一个哈希编解码器的工厂函数,枚举本身实现了 [HashCodec],
* 可直接作为编解码器使用,哈希操作委托给对应的编解码器实例。
*
* @param codec 哈希编解码器的工厂函数,每次访问 [code] 时调用以创建实例
*/
enum class HashType(private val codec: () -> HashCodec) : HashCodec {
/** MD2 哈希(输出 128 位,已过时,仅用于兼容遗留系统)。 */
MD2(::MD2),
/** MD5 哈希(输出 128 位,存在碰撞漏洞,不得用于安全场景)。 */
MD5(::MD5),
/** SHA-1 哈希(输出 160 位,存在碰撞攻击,不得用于安全场景)。 */
SHA1(::SHA1),
/** SHA-224 哈希(SHA-2 家族,输出 224 位)。 */
SHA224(::SHA224),
/** SHA-256 哈希(SHA-2 家族,输出 256 位)。 */
SHA256(::SHA256),
/** SHA-384 哈希(SHA-2 家族,输出 384 位)。 */
SHA384(::SHA384),
/** SHA-512 哈希(SHA-2 家族,输出 512 位)。 */
SHA512(::SHA512),
/** SHA3-224 哈希(SHA-3 家族,输出 224 位)。 */
SHA3224(::SHA3224),
/** SHA3-256 哈希(SHA-3 家族,输出 256 位)。 */
SHA3256(::SHA3256),
/** SHA3-384 哈希(SHA-3 家族,输出 384 位)。 */
SHA3384(::SHA3384),
/** SHA3-512 哈希(SHA-3 家族,输出 512 位)。 */
SHA3512(::SHA3512),
/** SHA-512/224 哈希(SHA-2 家族,输出 224 位)。 */
SHA512224(::SHA512224),
/** SHA-512/256 哈希(SHA-2 家族,输出 256 位)。 */
SHA512256(::SHA512256);
/**
* 获取当前类型对应的哈希编解码器实例(每次访问都会通过工厂函数新建)。
*/
val code get() = codec()
/**
* 计算输入流内容的哈希值,委托给 [code] 对应的编解码器。
*
* @param input 待计算哈希的输入流
* @return 哈希结果字节数组
*/
override fun hash(input: InputStream): ByteArray {
return code.hash(input)
}
}
@@ -16,71 +16,103 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile HashUtils.kt
* LastUpdate 2026-01-11 09:09:52
* LastUpdate 2026-11-18 18:53:11
* UpdateUser MingLiPro
*/
@file:JvmName("HashUtils")
package com.mingliqiye.utils.hash
import com.mingliqiye.utils.hash.code.*
import com.mingliqiye.utils.bcrypt.checkpw
import com.mingliqiye.utils.bcrypt.hashpw
import com.mingliqiye.utils.bytes.bytesToHex
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
/**
* 计算指定文件的哈希值。
*
* @param file 要计算哈希值的文件对象
* @param algorithm 使用的哈希算法名称(如 SHA-256、MD5 等)
* @return 文件的十六进制格式哈希值字符串
* @throws IOException 当文件不存在或读取过程中发生 I/O 错误时抛出
* @throws NoSuchAlgorithmException 当指定的哈希算法不可用时抛出
* 提供 MD2 哈希器的懒加载实例。
* 该哈希器输出 128 位摘要,算法已过时,仅用于兼容遗留系统。
*/
@Throws(IOException::class, NoSuchAlgorithmException::class)
fun calculateFileHash(file: File, algorithm: String): String {
// 检查文件是否存在
if (!file.exists()) {
throw IOException("File not found: " + file.absolutePath)
}
val digest = MessageDigest.getInstance(algorithm)
FileInputStream(file).use { fis ->
val buffer = ByteArray(8192)
var bytesRead: Int
// 分块读取文件内容并更新摘要
while (fis.read(buffer).also { bytesRead = it } != -1) {
digest.update(buffer, 0, bytesRead)
}
}
return bytesToHex(digest.digest())
}
@get:JvmName("getMd2Codec")
val MD2 by lazy(::Md2Codec)
/**
* 使用 BCrypt 算法对字符串进行加密。
*
* @param string 需要加密的明文字符串
* @return 加密后的 BCrypt 哈希字符串
* 提供 MD5 哈希器的懒加载实例。
* 该哈希器输出 128 位摘要,存在碰撞漏洞,不得用于安全场景,仅建议非安全性校验。
*/
fun bcrypt(string: String): String {
return hashpw(string)
}
@get:JvmName("getMd5Codec")
val MD5 by lazy(::Md5Codec)
/**
* 验证给定字符串与 BCrypt 哈希是否匹配。
*
* @param string 明文字符串
* @param bcrypted 已经使用 BCrypt 加密的哈希字符串
* @return 如果匹配返回 true,否则返回 false
* 提供 SHA-1 哈希器的懒加载实例。
* 该哈希器输出 160 位摘要,存在碰撞攻击,不得用于安全场景,仅建议非安全性校验。
*/
fun checkBcrypt(string: String, bcrypted: String): Boolean {
return checkpw(string, bcrypted)
}
@get:JvmName("getSha1Codec")
val SHA1 by lazy(::Sha1Codec)
/**
* 提供 SHA-224 哈希器的懒加载实例。
* 该哈希器属于 SHA-2 家族,输出 224 位摘要。
*/
@get:JvmName("getSha224Codec")
val SHA224 by lazy(::Sha224Codec)
/**
* 提供 SHA-256 哈希器的懒加载实例。
* 该哈希器属于 SHA-2 家族,输出 256 位摘要,适用于文件校验、数字签名等场景。
*/
@get:JvmName("getSha256Codec")
val SHA256 by lazy(::Sha256Codec)
/**
* 提供 SHA-384 哈希器的懒加载实例。
* 该哈希器属于 SHA-2 家族,输出 384 位摘要。
*/
@get:JvmName("getSha384Codec")
val SHA384 by lazy(::Sha384Codec)
/**
* 提供 SHA-512 哈希器的懒加载实例。
* 该哈希器属于 SHA-2 家族,输出 512 位摘要,在 64 位平台上通常比 SHA-256 更快。
*/
@get:JvmName("getSha512Codec")
val SHA512 by lazy(::Sha512Codec)
/**
* 提供 SHA3-224 哈希器的懒加载实例。
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 224 位摘要。
*/
@get:JvmName("getSha3224Codec")
val SHA3224 by lazy(::Sha3224Codec)
/**
* 提供 SHA3-256 哈希器的懒加载实例。
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 256 位摘要。
*/
@get:JvmName("getSha3256Codec")
val SHA3256 by lazy(::Sha3256Codec)
/**
* 提供 SHA3-384 哈希器的懒加载实例。
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 384 位摘要。
*/
@get:JvmName("getSha3384Codec")
val SHA3384 by lazy(::Sha3384Codec)
/**
* 提供 SHA3-512 哈希器的懒加载实例。
* 该哈希器属于 SHA-3 家族(Keccak 结构),输出 512 位摘要。
*/
@get:JvmName("getSha3512Codec")
val SHA3512 by lazy(::Sha3512Codec)
/**
* 提供 SHA-512/224 哈希器的懒加载实例。
* 该哈希器以 SHA-512 的运算结构截断输出至 224 位,在 64 位平台上性能优于 SHA-224。
*/
@get:JvmName("getSha512224Codec")
val SHA512224 by lazy(::Sha512224Codec)
/**
* 提供 SHA-512/256 哈希器的懒加载实例。
* 该哈希器以 SHA-512 的运算结构截断输出至 256 位,在 64 位平台上性能优于 SHA-256。
*/
@get:JvmName("getSha512256Codec")
val SHA512256 by lazy(::Sha512256Codec)
@@ -0,0 +1,176 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile HashCodec.kt
* LastUpdate 2026-11-18 18:36:00
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
import com.mingliqiye.utils.base.BaseType
import java.io.File
import java.io.InputStream
import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.Path
import java.security.MessageDigest
/**
* 哈希编解码器接口。
*
* 实现类只需重写 [hash](InputStream 版本)一个方法,
* 其余字节数组、字符串、文件、路径的重载以及十六进制输出、
* 哈希校验均由接口提供默认实现。
*
* 使用示例(以 SHA-256 为例):
* ```
* val sha256 = Sha256Codec()
* val hex = sha256.hashHex("hello")
* val ok = sha256.verifyHash("hello", hex)
* ```
*/
interface HashCodec {
/**
* 计算输入流内容的哈希值(唯一需要实现的方法)。
*
* 实现不需要关闭输入流,由调用方负责流的生命周期。
*
* @param input 待计算哈希的输入流
* @return 哈希结果字节数组
*/
fun hash(input: InputStream): ByteArray
/**
* 计算字节数组的哈希值。
*
* @param bytes 待计算哈希的字节数组
* @return 哈希结果字节数组
*/
fun hash(bytes: ByteArray): ByteArray = hash(bytes.inputStream())
/**
* 计算字符串的哈希值。
*
* @param string 待计算哈希的字符串
* @param charset 字符串编码字符集,默认 UTF-8
* @return 哈希结果字节数组
*/
fun hash(string: String, charset: Charset = Charsets.UTF_8): ByteArray = hash(string.toByteArray(charset))
/**
* 计算文件内容的哈希值。
*
* @param file 待计算哈希的文件
* @return 哈希结果字节数组
*/
fun hash(file: File): ByteArray = file.inputStream().use { hash(it) }
/**
* 计算路径指向文件内容的哈希值。
*
* @param path 待计算哈希的文件路径
* @return 哈希结果字节数组
*/
fun hash(path: Path): ByteArray = Files.newInputStream(path).use { hash(it) }
/**
* 计算输入流内容的哈希值并以小写十六进制字符串返回。
*
* @param input 待计算哈希的输入流
* @return 十六进制格式的哈希字符串
*/
fun hashHex(input: InputStream): String = BaseType.BASE16.encode(hash(input))
/**
* 计算字节数组的哈希值并以小写十六进制字符串返回。
*
* @param bytes 待计算哈希的字节数组
* @return 十六进制格式的哈希字符串
*/
fun hashHex(bytes: ByteArray): String = BaseType.BASE16.encode(hash(bytes))
/**
* 计算字符串的哈希值并以小写十六进制字符串返回。
*
* @param string 待计算哈希的字符串
* @param charset 字符串编码字符集,默认 UTF-8
* @return 十六进制格式的哈希字符串
*/
fun hashHex(string: String, charset: Charset = Charsets.UTF_8): String =
BaseType.BASE16.encode(hash(string, charset))
/**
* 计算文件内容的哈希值并以小写十六进制字符串返回。
*
* @param file 待计算哈希的文件
* @return 十六进制格式的哈希字符串
*/
fun hashHex(file: File): String = BaseType.BASE16.encode(hash(file))
/**
* 计算路径指向文件内容的哈希值并以小写十六进制字符串返回。
*
* @param path 待计算哈希的文件路径
* @return 十六进制格式的哈希字符串
*/
fun hashHex(path: Path): String = BaseType.BASE16.encode(hash(path))
/**
* 校验输入流内容的哈希值是否与期望值一致。
*
* 使用 [java.security.MessageDigest.isEqual] 进行常量时间比较,避免时序攻击。
*
* @param input 待校验的输入流
* @param hashed 期望的哈希值字节数组
* @return 一致返回 true,否则返回 false
*/
fun verifyHash(input: InputStream, hashed: ByteArray): Boolean = MessageDigest.isEqual(hash(input), hashed)
/**
* 校验字节数组的哈希值是否与期望值一致。
*
* @param bytes 待校验的字节数组
* @param hashed 期望的哈希值字节数组
* @return 一致返回 true,否则返回 false
*/
fun verifyHash(bytes: ByteArray, hashed: ByteArray): Boolean = MessageDigest.isEqual(hash(bytes), hashed)
/**
* 校验字符串的哈希值是否与期望值一致。
*
* @param string 待校验的字符串
* @param hashed 期望的哈希值字节数组
* @param charset 字符串编码字符集,默认 UTF-8
* @return 一致返回 true,否则返回 false
*/
fun verifyHash(string: String, hashed: ByteArray, charset: Charset = Charsets.UTF_8): Boolean =
MessageDigest.isEqual(hash(string, charset), hashed)
/**
* 校验字符串的哈希值是否与期望的十六进制字符串一致(忽略大小写)。
*
* @param string 待校验的字符串
* @param hashedHex 期望的十六进制哈希字符串
* @param charset 字符串编码字符集,默认 UTF-8
* @return 一致返回 true,否则返回 false
*/
fun verifyHash(string: String, hashedHex: String, charset: Charset = Charsets.UTF_8): Boolean =
MessageDigest.isEqual(hash(string, charset), BaseType.BASE16.decode(hashedHex.lowercase()))
}
@@ -15,22 +15,16 @@
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ApplicationDestroyedRunner.kt
* LastUpdate 2026-03-10 09:04:02
* CurrentFile Md2Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation
package com.mingliqiye.utils.hash.code
/**
* 标记在 Spring 上下文关闭时执行的方法。
* 被标注的方法会在 ContextClosedEvent 触发时由
* [com.mingliqiye.utils.springboot.listener.ApplicationListener] 反射调用,
* 多个方法按 [order] 升序执行。
* MD2 哈希编解码器(输出 128 位 / 16 字节)。
*
* @property order 执行顺序,值越小越先执行,默认为 [Int.MIN_VALUE]
* MD2 已过时且存在安全缺陷,仅用于兼容遗留系统,不建议在任何新场景使用。
*/
@Target(AnnotationTarget.FUNCTION)
annotation class ApplicationDestroyedRunner(
val order: Int = Int.MIN_VALUE,
)
class Md2Codec : MessageDigestCodec("MD2")
@@ -15,22 +15,17 @@
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ApplicationStartedRunner.kt
* LastUpdate 2026-03-11 08:46:40
* CurrentFile Md5Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation
package com.mingliqiye.utils.hash.code
/**
* 标记在 Spring Boot 应用启动完成后执行的方法。
* 被标注的方法会在 ApplicationStartedEvent 触发时由
* [com.mingliqiye.utils.springboot.listener.ApplicationListener] 反射调用,
* 多个方法按 [order] 升序执行。
* MD5 哈希编解码器(输出 128 位 / 16 字节)。
*
* @property order 执行顺序,值越小越先执行,默认为 [Int.MIN_VALUE]
* MD5 已被证实存在碰撞漏洞,不得用于数字签名、密码存储等安全场景,
* 仅建议用于兼容遗留系统或非安全性校验(如文件完整性粗检)。
*/
@Target(AnnotationTarget.FUNCTION)
annotation class ApplicationStartedRunner(
val order: Int = Int.MIN_VALUE,
)
class Md5Codec : MessageDigestCodec("MD5")
@@ -0,0 +1,63 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile MessageDigestCodec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
import java.io.InputStream
import java.security.MessageDigest
/**
* 基于 JDK [MessageDigest] 的哈希编解码器抽象基类。
*
* 以固定 8KB 缓冲区流式读取输入,内存占用恒定,适用于任意大小的文件与数据流。
* 每次调用 [hash] 都会新建 [MessageDigest] 实例(其本身非线程安全),
* 因此本类实例无状态、可安全地在多线程间共享。
*
* 遵循 [HashCodec] 契约:不关闭输入流,由调用方负责流的生命周期。
*
* 子类只需指定算法名称,也可借此扩展 JDK 默认提供者之外的算法
* (如 BouncyCastle 提供的 SM3),前提是相应 [java.security.Provider] 已注册。
*
* @param algorithm [MessageDigest.getInstance] 所用的算法名称
*/
abstract class MessageDigestCodec(private val algorithm: String) : HashCodec {
/**
* 以 8KB 缓冲区流式计算输入流内容的哈希值。
*
* 不关闭输入流;每次调用新建 [MessageDigest] 实例,线程安全。
*
* @param input 待计算哈希的输入流
* @return 哈希结果字节数组
* @throws java.security.NoSuchAlgorithmException 当前环境无指定算法的提供者时抛出
*/
override fun hash(input: InputStream): ByteArray {
val digest = MessageDigest.getInstance(algorithm)
val buffer = ByteArray(8192)
while (true) {
val n = input.read(buffer)
if (n == -1) break
digest.update(buffer, 0, n)
}
return digest.digest()
}
}
@@ -15,25 +15,17 @@
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Listener.kt
* LastUpdate 2026-03-10 09:04:02
* CurrentFile Sha1Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation
import org.springframework.core.annotation.AliasFor
import org.springframework.stereotype.Component
package com.mingliqiye.utils.hash.code
/**
* 监听器组件注解,组合了 [Component] 的语义。
* 被标注的类会被组件扫描注册为 Spring Bean,
* [value] 通过 [AliasFor] 别名到 [Component.value],用于指定 Bean 名称。
* SHA-1 哈希编解码器(输出 160 位 / 20 字节)。
*
* @property value Bean 名称,默认为空字符串(由 Spring 按类名生成)
* SHA-1 已被证实存在碰撞攻击(SHAttered),不得用于安全场景,
* 仅建议用于兼容遗留系统或非安全性校验。
*/
@Component
annotation class Listener(
@get:AliasFor(annotation = Component::class)
val value: String = "",
)
class Sha1Codec : MessageDigestCodec("SHA-1")
@@ -0,0 +1,28 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha224Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-224 哈希编解码器(SHA-2 家族,输出 224 位 / 28 字节)。
*/
class Sha224Codec : MessageDigestCodec("SHA-224")
@@ -0,0 +1,37 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha256Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-256 哈希编解码器(SHA-2 家族,输出 256 位 / 32 字节)。
*
* 目前广泛使用的安全哈希算法,适用于文件校验、数字签名、消息摘要等场景。
*
* 使用示例:
* ```
* val sha256 = Sha256Codec()
* val hex = sha256.hashHex("hello")
* val ok = sha256.verifyHash("hello", hex)
* ```
*/
class Sha256Codec : MessageDigestCodec("SHA-256")
@@ -0,0 +1,28 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha3224Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA3-224 哈希编解码器(SHA-3 家族,Keccak 结构,输出 224 位 / 28 字节)。
*/
class Sha3224Codec : MessageDigestCodec("SHA3-224")
@@ -0,0 +1,28 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha3256Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA3-256 哈希编解码器(SHA-3 家族,Keccak 结构,输出 256 位 / 32 字节)。
*/
class Sha3256Codec : MessageDigestCodec("SHA3-256")
@@ -0,0 +1,28 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha3384Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA3-384 哈希编解码器(SHA-3 家族,Keccak 结构,输出 384 位 / 48 字节)。
*/
class Sha3384Codec : MessageDigestCodec("SHA3-384")
@@ -0,0 +1,28 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha3512Codec.kt
* LastUpdate 2026-11-18 11:18:52
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA3-512 哈希编解码器(SHA-3 家族,Keccak 结构,输出 512 位 / 64 字节)。
*/
class Sha3512Codec : MessageDigestCodec("SHA3-512")
@@ -0,0 +1,28 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha384Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-384 哈希编解码器(SHA-2 家族,输出 384 位 / 48 字节)。
*/
class Sha384Codec : MessageDigestCodec("SHA-384")
@@ -0,0 +1,30 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha512224Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-512/224 哈希编解码器(SHA-2 家族,输出 224 位 / 28 字节)。
*
* 以 SHA-512 的运算结构截断输出至 224 位,在 64 位平台上性能优于 SHA-224。
*/
class Sha512224Codec : MessageDigestCodec("SHA-512/224")
@@ -0,0 +1,30 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha512256Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-512/256 哈希编解码器(SHA-2 家族,输出 256 位 / 32 字节)。
*
* 以 SHA-512 的运算结构截断输出至 256 位,在 64 位平台上性能优于 SHA-256。
*/
class Sha512256Codec : MessageDigestCodec("SHA-512/256")
@@ -0,0 +1,30 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Sha512Codec.kt
* LastUpdate 2026-11-18 11:18:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.hash.code
/**
* SHA-512 哈希编解码器(SHA-2 家族,输出 512 位 / 64 字节)。
*
* 在 64 位平台上通常比 SHA-256 更快,适用于大文件校验与高安全需求场景。
*/
class Sha512Codec : MessageDigestCodec("SHA-512")
File diff suppressed because it is too large Load Diff
@@ -16,14 +16,14 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile DateTimeJsonConverter.kt
* LastUpdate 2026-11-17 20:17:32
* LastUpdate 2026-11-18 00:03:07
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters
import com.google.gson.JsonParseException
import com.mingliqiye.utils.annotation.DateTimeJsonFormat
import com.mingliqiye.utils.exception.JsonParserException
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.converters.base.AnnotationGetter
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
@@ -68,12 +68,12 @@ class DateTimeJsonConverter : BaseJsonConverter<DateTime> {
/**
* 按 [DateTimeJsonFormat] 注解指定的格式从 JSON 字符串解析日期时间
*
* @throws JsonParseException 当节点不是字符串类型时抛出
* @throws JsonParserException 当节点不是字符串类型时抛出
*/
override fun deConvert(jsonReader: BaseJsonReader, annotationGetter: AnnotationGetter): DateTime? {
val dateTimeJsonFormat: DateTimeJsonFormat? = annotationGetter.getAnnotation<DateTimeJsonFormat>()
if (jsonReader.isNull) return null
if (!jsonReader.isString) throw JsonParseException("type item not string")
if (!jsonReader.isString) throw JsonParserException("type item not string")
val obj = jsonReader.getString()
return if (Formatter.NONE != dateTimeJsonFormat?.value && dateTimeJsonFormat != null) {
DateTime.parse(obj, dateTimeJsonFormat.value, dateTimeJsonFormat.repcZero)
@@ -16,13 +16,13 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile NetworkEndpointJsonConverter.kt
* LastUpdate 2026-11-17 20:01:08
* LastUpdate 2026-11-18 00:03:17
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters
import com.google.gson.JsonParseException
import com.mingliqiye.utils.exception.JsonParserException
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.converters.base.AnnotationGetter
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
@@ -58,14 +58,14 @@ class NetworkEndpointJsonConverter : BaseJsonConverter<NetworkEndpoint> {
/**
* 从 `host:port` 形式的 JSON 字符串还原网络端点
*
* @throws JsonParseException 当节点不是字符串类型时抛出
* @throws JsonParserException 当节点不是字符串类型时抛出
*/
override fun deConvert(
jsonReader: BaseJsonReader,
annotationGetter: AnnotationGetter,
): NetworkEndpoint? {
return if (jsonReader.isNotNull) {
if (!jsonReader.isString) throw JsonParseException("type item not string")
if (!jsonReader.isString) throw JsonParserException("type item not string")
NetworkEndpoint.of(jsonReader.getString())
} else null
}
@@ -16,15 +16,15 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile UUIDJsonConverter.kt
* LastUpdate 2026-11-17 20:01:08
* LastUpdate 2026-11-18 00:03:17
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters
import com.google.gson.JsonParseException
import com.mingliqiye.utils.annotation.UUIDJsonFormat
import com.mingliqiye.utils.base.BaseType
import com.mingliqiye.utils.exception.JsonParserException
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.converters.base.AnnotationGetter
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
@@ -72,14 +72,14 @@ class UUIDJsonConverter : BaseJsonConverter<UUID> {
/**
* 按 [UUIDJsonFormat] 注解指定的进制从 JSON 字符串解析 UUID
*
* @throws JsonParseException 当节点不是字符串类型时抛出
* @throws JsonParserException 当节点不是字符串类型时抛出
*/
override fun deConvert(
jsonReader: BaseJsonReader,
annotationGetter: AnnotationGetter,
): UUID? {
if (jsonReader.isNull) return null
if (!jsonReader.isString) throw JsonParseException("type item not string")
if (!jsonReader.isString) throw JsonParserException("type item not string")
val obj = jsonReader.getString()
@@ -16,13 +16,13 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonWriter.kt
* LastUpdate 2026-11-17 19:32:34
* LastUpdate 2026-11-17 21:10:29
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.witer.base
import com.mingliqiye.utils.json.judgment.BaseJsonJudgment
import com.mingliqiye.utils.json.judgment.base.BaseJsonJudgment
/**
@@ -35,30 +35,35 @@ interface BaseJsonWriter : BaseJsonJudgment {
* @param objCall 对象写入回调,接收对象写入器并返回它
*/
fun setObject(objCall: (BaseJsonObjectWriter) -> BaseJsonObjectWriter)
/**
* 写入一个 JSON 数组,通过回调填充数组元素
*
* @param arrayCall 数组写入回调,接收数组写入器并返回它
*/
fun setArray(arrayCall: (BaseJsonArrayWriter) -> BaseJsonArrayWriter)
/**
* 写入字符串值
*
* @param string 待写入的字符串
*/
fun setString(string: String)
/**
* 写入数值
*
* @param number 待写入的数值
*/
fun setNumber(number: Number)
/**
* 写入布尔值
*
* @param boolean 待写入的布尔值
*/
fun setBoolean(boolean: Boolean)
/**
* 写入 null 值
*/
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Okhttp3AutoConfiguration.kt
* LastUpdate 2026-11-16 11:29:35
* LastUpdate 2026-11-18 08:22:35
* UpdateUser MingLiPro
*/
@@ -118,6 +118,7 @@ open class Okhttp3AutoConfiguration {
* 仅当 [okhttp] 字段非空(即客户端由本配置创建)时执行;
* 调用方自行声明的客户端不会被清理。
*/
@EventListener(ContextClosedEvent::class)
open fun handleContextClosed() {
okhttp?.let {
@@ -1,132 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ApplicationListener.kt
* LastUpdate 2026-03-11 08:20:37
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.listener
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import com.mingliqiye.utils.springboot.annotation.ApplicationDestroyedRunner
import com.mingliqiye.utils.springboot.annotation.ApplicationStartedRunner
import com.mingliqiye.utils.springboot.annotation.Listener
import org.springframework.beans.factory.ListableBeanFactory
import org.springframework.boot.context.event.ApplicationStartedEvent
import org.springframework.context.event.ContextClosedEvent
import org.springframework.context.event.EventListener
/**
* 应用生命周期监听器。
* 在应用启动完成时扫描容器中所有 Bean 的方法,收集标注了
* [ApplicationStartedRunner] / [ApplicationDestroyedRunner] 的方法并按 order 排序,
* 分别在 ApplicationStartedEvent 和 ContextClosedEvent 触发时依次反射执行。
*/
@Listener
class ApplicationListener {
/**
* 已扫描到的待执行方法集合,键为注解类全名,值为按 order 升序排列的执行数据列表。
*/
val runningMap = HashMap<String, MutableList<ApplicationRunnerData>>()
/**
* 伴生对象,持有本监听器的日志记录器。
*/
companion object {
private val log = MingLiLoggerFactory.getLogger<ApplicationListener>()
}
/**
* 扫描容器中的 Bean 方法,收集生命周期回调并按 order 排序。
*
* 跳过 `org.springframework` 包下的 Bean;每次调用会先清空 [runningMap] 再重新扫描。
*
* @param applicationContext 用于遍历 Bean 定义与获取 Bean 实例的容器
*/
fun init(applicationContext: ListableBeanFactory) {
runningMap.clear()
for (beanName in applicationContext.beanDefinitionNames) {
val bean: Any = applicationContext.getBean(beanName)
val beanClass: Class<*> = bean.javaClass
if (beanClass.getName().startsWith("org.springframework")) {
continue
}
for (method in beanClass.getDeclaredMethods()) {
val annotation: Any =
method.getAnnotation(ApplicationStartedRunner::class.java) ?: method.getAnnotation(
ApplicationDestroyedRunner::class.java
) ?: continue
var order: Int
var key: Class<out Annotation>
when (annotation) {
is ApplicationStartedRunner -> {
order = annotation.order
key = ApplicationStartedRunner::class.java
}
is ApplicationDestroyedRunner -> {
order = annotation.order
key = ApplicationDestroyedRunner::class.java
}
else -> continue
}
log.debug("ApplicationListener Scaned [{} - {}] order: {} ", bean.javaClass.name, method, order)
val d = runningMap.getOrPut(key.name) {
ArrayList()
}
d.add(
ApplicationRunnerData(
beanName = beanName, order = order, bean = bean, method = method
)
)
}
}
runningMap.forEach { (string, data) ->
data.sortWith(compareBy(ApplicationRunnerData::order))
}
}
/**
* 应用启动完成事件回调:先执行 [init] 扫描,再按 order 升序执行所有 [ApplicationStartedRunner] 方法。
*
* @param event 应用启动完成事件
*/
@EventListener(ApplicationStartedEvent::class)
fun applicationStarted(event: ApplicationStartedEvent) {
init(event.applicationContext)
runningMap[ApplicationStartedRunner::class.java.name]?.forEach {
log.debug("Started Event Running {} {} {} - {}", it.beanName, it.bean, it.method, it.order)
it.run()
}
}
/**
* 上下文关闭事件回调:按 order 升序执行所有 [ApplicationDestroyedRunner] 方法。
*/
@EventListener(ContextClosedEvent::class)
fun applicationClosed() {
runningMap[ApplicationDestroyedRunner::class.java.name]?.forEach {
log.debug("Closed Event Running {} {} {} - {}", it.beanName, it.bean, it.method, it.order)
it.run()
}
}
}
@@ -1,44 +0,0 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ApplicationRunnerData.kt
* LastUpdate 2026-03-10 09:10:50
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.listener
import java.lang.reflect.Method
/**
* 生命周期回调的执行数据,记录一个待反射执行的方法及其宿主 Bean 与执行顺序。
*
* @property beanName Bean 在容器中的名称
* @property order 执行顺序,值越小越先执行
* @property bean 方法所属的 Bean 实例
* @property method 待执行的回调方法
*/
data class ApplicationRunnerData(
val beanName: String, val order: Int, val bean: Any, val method: Method,
) {
/**
* 反射调用 [method],以 [bean] 为宿主实例执行回调。
*/
fun run() {
method.invoke(bean)
}
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Tuples.kt
* LastUpdate 2026-11-17 20:29:54
* LastUpdate 2026-11-17 21:11:31
* UpdateUser MingLiPro
*/
@@ -34,6 +34,32 @@ import java.io.Serializable
*/
abstract class Tuple(val size: Int = 1) : Serializable, Iterable<Any>, Comparable<Tuple> {
/**
* 按字典序比较当前元组与另一个元组。
*
* 从第 1 个元素开始逐位比较:两个元素类型相同且都实现 [Comparable] 时按自然顺序比较,
* 否则按元素的字符串形式([toString])比较。
* 公共位置元素全部相等时,元素个数较少的元组视为较小。
*
* @param other 要比较的目标元组
* @return 负数、零或正数,分别表示当前元组小于、等于或大于 [other]
*/
override fun compareTo(other: Tuple): Int {
val minSize = minOf(size, other.size)
for (i in 0..<minSize) {
val a = get(i)
val b = other.get(i)
val result = if (a is Comparable<*> && b is Comparable<*> && a.javaClass == b.javaClass) {
@Suppress("UNCHECKED_CAST")
(a as Comparable<Any>).compareTo(b)
} else {
a.toString().compareTo(b.toString())
}
if (result != 0) return result
}
return size.compareTo(other.size)
}
override fun iterator(): Iterator<Any> {
return toMutableList().iterator()
}
@@ -0,0 +1,142 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.test
* CurrentFile TestHash.kt
* LastUpdate 2026-11-18 11:17:46
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils
import com.mingliqiye.utils.base.BaseType
import com.mingliqiye.utils.hash.code.Md2Codec
import com.mingliqiye.utils.hash.code.Md5Codec
import com.mingliqiye.utils.hash.code.MessageDigestCodec
import com.mingliqiye.utils.hash.code.Sha1Codec
import com.mingliqiye.utils.hash.code.Sha224Codec
import com.mingliqiye.utils.hash.code.Sha256Codec
import com.mingliqiye.utils.hash.code.Sha3224Codec
import com.mingliqiye.utils.hash.code.Sha3256Codec
import com.mingliqiye.utils.hash.code.Sha3384Codec
import com.mingliqiye.utils.hash.code.Sha3512Codec
import com.mingliqiye.utils.hash.code.Sha384Codec
import com.mingliqiye.utils.hash.code.Sha512224Codec
import com.mingliqiye.utils.hash.code.Sha512256Codec
import com.mingliqiye.utils.hash.code.Sha512Codec
import com.mingliqiye.utils.hash.code.HashCodec
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import java.io.FilterInputStream
import java.nio.file.Files
import java.security.MessageDigest
/**
* [HashCodec] 及其全部内置算法实现的测试。
*/
class TestHash {
private val codecs: List<Pair<HashCodec, String>> = listOf(
Md2Codec() to "MD2",
Md5Codec() to "MD5",
Sha1Codec() to "SHA-1",
Sha224Codec() to "SHA-224",
Sha256Codec() to "SHA-256",
Sha384Codec() to "SHA-384",
Sha512Codec() to "SHA-512",
Sha512224Codec() to "SHA-512/224",
Sha512256Codec() to "SHA-512/256",
Sha3224Codec() to "SHA3-224",
Sha3256Codec() to "SHA3-256",
Sha3384Codec() to "SHA3-384",
Sha3512Codec() to "SHA3-512",
)
/** 测试常见算法对 "hello" 的已知哈希向量 */
@Test
fun knownVectors() {
assertEquals("5d41402abc4b2a76b9719d911017c592", Md5Codec().hashHex("hello"))
assertEquals("aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d", Sha1Codec().hashHex("hello"))
assertEquals(
"2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
Sha256Codec().hashHex("hello")
)
}
/** 测试全部算法的流式结果与 MessageDigest 直接计算一致,且校验方法正确 */
@Test
fun allAlgorithmsMatchMessageDigest() {
val data = ByteArray(100_000) { (it % 251).toByte() }
for ((codec, algorithm) in codecs) {
val expected = MessageDigest.getInstance(algorithm).digest(data)
assertArrayEquals(expected, codec.hash(data), algorithm)
assertArrayEquals(expected, codec.hash(data.inputStream()), algorithm)
assertEquals(BaseType.BASE16.encode(expected), codec.hashHex(data), algorithm)
assertTrue(codec.verifyHash(data, expected), algorithm)
val tampered = expected.copyOf().also { it[0] = (it[0].toInt() xor 1).toByte() }
assertFalse(codec.verifyHash(data, tampered), algorithm)
assertTrue(codec.verifyHash("hello", codec.hashHex("hello")), algorithm)
assertFalse(codec.verifyHash("hello", codec.hashHex("world")), algorithm)
}
}
/** 测试实现不关闭调用方传入的输入流 */
@Test
fun doesNotCloseCallerStream() {
var closed = false
val stream = object : FilterInputStream("hello".byteInputStream()) {
override fun close() {
closed = true
super.close()
}
}
Sha256Codec().hash(stream)
assertFalse(closed)
}
/** 测试文件与路径重载结果和字节数组一致 */
@Test
fun fileAndPathOverloads() {
val data = ByteArray(20_000) { (it % 256).toByte() }
val path = Files.createTempFile("mingli-hash-test", ".bin")
try {
Files.write(path, data)
val codec = Sha256Codec()
assertArrayEquals(codec.hash(data), codec.hash(path))
assertArrayEquals(codec.hash(data), codec.hash(path.toFile()))
assertEquals(codec.hashHex(data), codec.hashHex(path))
assertEquals(codec.hashHex(data), codec.hashHex(path.toFile()))
} finally {
Files.deleteIfExists(path)
}
}
/** 测试自定义算法名称的扩展基类用法 */
@Test
fun customAlgorithmViaBaseClass() {
val codec = object : MessageDigestCodec("SHA-256") {}
assertArrayEquals(Sha256Codec().hash("hello"), codec.hash("hello"))
}
/** 测试空输入可正常计算哈希 */
@Test
fun emptyInput() {
val empty = ByteArray(0)
for ((codec, algorithm) in codecs) {
assertArrayEquals(MessageDigest.getInstance(algorithm).digest(empty), codec.hash(empty), algorithm)
}
}
}
@@ -0,0 +1,76 @@
/*
* Copyright 2026 mingliqiye
*
* 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.
*
* ProjectName mingli-utils
* ModuleName mingli-utils.test
* CurrentFile TestTuple.kt
* LastUpdate 2026-11-17 21:20:00
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils
import com.mingliqiye.utils.tuple.Tuple
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
/**
* [Tuple] 字典序比较(compareTo)测试。
*/
class TestTuple {
/** 测试首元素不同时按首元素自然顺序比较 */
@Test
fun compareByFirstElement() {
assertTrue(Tuple.of(2, "a") > Tuple.of(1, "z"))
assertTrue(Tuple.of(1, "z") < Tuple.of(2, "a"))
}
/** 测试首元素相同时按后续元素逐位比较 */
@Test
fun compareByLaterElement() {
assertTrue(Tuple.of(1, "b") > Tuple.of(1, "a"))
assertTrue(Tuple.of(1, 2, 3) < Tuple.of(1, 2, 4))
}
/** 测试公共前缀相等时元素个数少的元组较小 */
@Test
fun compareBySizeWhenPrefixEqual() {
assertTrue(Tuple.of(1) < Tuple.of(1, 0))
assertTrue(Tuple.of(1, 0, 0) > Tuple.of(1, 0))
}
/** 测试元素完全相同的元组比较结果为 0 */
@Test
fun compareEqualTuples() {
assertEquals(0, Tuple.of(1, "a").compareTo(Tuple.of(1, "a")))
}
/** 测试非 Comparable 元素按字符串形式比较且不抛异常 */
@Test
fun compareNonComparableElements() {
val a = Any()
val b = Any()
assertEquals(a.toString().compareTo(b.toString()), Tuple.of(a).compareTo(Tuple.of(b)))
}
/** 测试元组可直接使用 sorted 排序 */
@Test
fun sortedTuples() {
val sorted = listOf(Tuple.of(2, "a"), Tuple.of(1, "z"), Tuple.of(1, "a")).sorted()
assertEquals(listOf(listOf(1, "a"), listOf(1, "z"), listOf(2, "a")), sorted.map { it.toList() })
}
}
+3 -1
View File
@@ -21,7 +21,9 @@
~ UpdateUser MingLiPro
-->
<Configuration status="WARN">
<Configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="log4j2.xsd"
status="WARN">
<Appenders>
<Console name="CONSOLE" target="SYSTEM_OUT">
<PatternLayout
File diff suppressed because it is too large Load Diff