This commit is contained in:
2026-03-11 08:47:22 +08:00
parent 450b4e1a93
commit bc8927db26
71 changed files with 4474 additions and 2471 deletions
@@ -15,17 +15,18 @@
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile TestAnnotation.kt
* LastUpdate 2026-02-07 08:44:25
* CurrentFile Jackson3ApiJavaHelper.java
* LastUpdate 2026-02-26 12:02:13
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.annotation
package com.mingliqiye.utils.json;
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.SOURCE)
annotation class TestAnnotation(val value: String = "test")
import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.cfg.MapperBuilder;
@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.SOURCE)
annotation class TestFieldAnnotation(val required: Boolean = true)
public class Jackson3ApiJavaHelper {
static MapperBuilder rebuild(ObjectMapper objectMapper) {
return objectMapper.rebuild();
}
}
@@ -0,0 +1,120 @@
/*
* 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 Main.java
* LastUpdate 2026-02-26 15:04:49
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.main;
import java.io.IOException;
import java.io.InputStream;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public final static String BANNER =
"| $$\\ $$\\ $$\\ $$\\ $$\\ $$$$$$$$\\ $$$$$$\\ \n" +
"| $$$\\ $$$ |$$ | $$ | $$ |\\__$$ __|$$ __$$\\ \n" +
"| $$$$\\ $$$$ |$$ | $$ | $$ | $$ | $$ / \\__| \n" +
"| $$\\$$\\$$ $$ |$$ | $$ | $$ | $$ | \\$$$$$$\\ \n" +
"| $$ \\$$$ $$ |$$ | $$ | $$ | $$ | \\____$$\\ \n" +
"| $$ |\\$ /$$ |$$ | $$ | $$ | $$ | $$\\ $$ | \n" +
"| $$ | \\_/ $$ |$$$$$$$$\\\\$$$$$$ | $$ | \\$$$$$$ \n" +
"| \\__| \\__|\\________|\\______/ \\__| \\______/ \n|\n";
public static void main(String[] args) {
try {
printb();
} catch (IOException ignored) {
}
}
public static String getPid() {
try {
var name = ManagementFactory.getRuntimeMXBean().getName();
var index = name.indexOf('@');
if (index > 0) {
return name.substring(0, index);
} else {
return "-1";
}
} catch (Exception e) {
return "-1";
}
}
public static String getComputerName() {
try {
var name = System.getenv("COMPUTERNAME");
if (name == null || name.isEmpty()) {
name = System.getenv("HOSTNAME");
}
if (name == null || name.isEmpty()) {
name = InetAddress.getLocalHost().getHostName();
}
return name != null ? name : "unknown";
} catch (Exception e) {
return "unknown";
}
}
public static String getUserName() {
try {
String user = System.getenv("USERNAME");
if (user == null || user.isEmpty()) {
user = System.getenv("USER");
}
if (user == null || user.isEmpty()) {
user = System.getenv("user.name");
}
if (user == null || user.isEmpty()) {
user = "unknown";
}
return user;
} catch (Exception e) {
return "unknown";
}
}
public static void printb() throws IOException {
InputStream inputStream = Main.class.getResourceAsStream("/META-INF/meta-data");
if (inputStream == null) return;
String data = new String(inputStream.readAllBytes());
inputStream.close();
StringBuilder sb = new StringBuilder(BANNER);
for (String sz : data.split("\n")) {
var d = sz.split("=");
sb.append("| -> ").append(d[0]).append(": ").append(d[1]).append("\n");
}
sb.append("| -> jdkVersion: ").append(System.getProperty("java.specification.version")).append("\n");
sb.append("| -> pid: ").append(getPid()).append("\n");
sb.append("| -> computerName: ").append(getComputerName()).append("\n");
sb.append("| -> userName: ").append(getUserName()).append("\n");
sb.append("| -> time: ")
.append(LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSS")))
.append("\n");
System.out.println();
System.out.println(sb);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2025 mingliqiye
* 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.
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile AesUtils.kt
* LastUpdate 2025-09-19 21:35:53
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
@@ -25,7 +25,7 @@
package com.mingliqiye.utils.aes
import com.mingliqiye.utils.base.BASE64
import com.mingliqiye.utils.base.code.Base64
import java.nio.charset.StandardCharsets
import java.security.GeneralSecurityException
import java.security.MessageDigest
@@ -71,8 +71,8 @@ fun encrypt(sSrc: String, sKey: String?): String? {
val encrypted = cipher.doFinal(
sSrc.toByteArray(StandardCharsets.UTF_8)
)
return BASE64.encode(
"${BASE64.encode(iv)}:${BASE64.encode(encrypted)}".toByteArray()
return Base64.encode(
"${Base64.encode(iv)}:${Base64.encode(encrypted)}".toByteArray()
)
}
@@ -85,13 +85,13 @@ fun encrypt(sSrc: String, sKey: String?): String? {
fun decrypt(sSrc: String, sKey: String): String? {
try {
// 分割IV和加密数据
val sSrcs = String(BASE64.decode(sSrc))
val sSrcs = String(Base64.decode(sSrc))
val parts: Array<String?> = sSrcs.split(":".toRegex(), limit = 2).toTypedArray()
if (parts.size != 2) {
return null
}
val iv = BASE64.decode(parts[0]!!)
val encryptedData = BASE64.decode(parts[1]!!)
val iv = Base64.decode(parts[0]!!)
val encryptedData = Base64.decode(parts[1]!!)
if (iv.size != GCM_IV_LENGTH) {
return null
}
@@ -121,4 +121,3 @@ private fun createSecretKey(sKey: String): SecretKeySpec {
val digest = md.digest(key)
return SecretKeySpec(digest, ALGORITHM)
}
@@ -16,14 +16,13 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile AutoServiceProcessor.kt
* LastUpdate 2026-02-08 01:24:16
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.annotation.processor
import com.mingliqiye.utils.annotation.AutoService
import com.mingliqiye.utils.io.IO.println
import javax.annotation.processing.AbstractProcessor
import javax.annotation.processing.ProcessingEnvironment
import javax.annotation.processing.RoundEnvironment
@@ -42,7 +41,7 @@ class AutoServiceProcessor : AbstractProcessor() {
override fun process(
annotations: Set<TypeElement>,
roundEnv: RoundEnvironment
roundEnv: RoundEnvironment,
): Boolean {
val service = mutableMapOf<String, MutableList<String>>()
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ArrayUtils.kt
* LastUpdate 2026-02-06 14:01:56
* LastUpdate 2026-03-11 08:42:08
* UpdateUser MingLiPro
*/
@@ -25,7 +25,7 @@
package com.mingliqiye.utils.array
import com.mingliqiye.utils.base.BASE16
import com.mingliqiye.utils.base.code.Base16
/**
@@ -35,7 +35,7 @@ import com.mingliqiye.utils.base.BASE16
* @since 4.6.0
* @see toHexByteArray
*/
fun ByteArray.toHexString(): String = BASE16.encode(this).uppercase()
fun ByteArray.toHexString(): String = Base16.encode(this).uppercase()
/**
* 将十六进制字符串转换为字节数组
@@ -45,9 +45,7 @@ fun ByteArray.toHexString(): String = BASE16.encode(this).uppercase()
* @since 4.6.0
* @see toHexString
*/
fun String.toHexByteArray(): ByteArray = BASE16.decode(this.lowercase())
/* ==================== 数组复制扩展函数 ==================== */
fun String.toHexByteArray(): ByteArray = Base16.decode(this.lowercase())
/**
* 将当前数组的指定范围复制到目标数组
@@ -1,5 +1,5 @@
/*
* Copyright 2025 mingliqiye
* 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.
@@ -16,158 +16,163 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseCodec.kt
* LastUpdate 2025-09-18 14:07:35
* LastUpdate 2026-02-09 19:58:29
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.base
import com.mingliqiye.utils.exception.CodecException
import java.io.File
import java.io.IOException
import java.nio.file.Path
/**
* BaseCodec 接口定义了一组用于编码和解码数据的基本方法。
* 提供了对字节数组、字符串、文件和路径的编码与解码功能,
* 并支持安全操作(在发生异常时返回默认值或布尔状态)。
*/
interface BaseCodec {
/**
* 将字节数组编码为Base64字符串
* 对字节数组进行编码,并捕获可能发生的异常。
*
* @param bytes 需要编码的字节数组
* @return 编码后的Base64字符串
* @return 编码后的字符串结果
* @throws CodecException 如果编码过程中发生异常
*/
fun catchEncode(bytes: ByteArray) = try {
encode(bytes)
} catch (e: Exception) {
throw CodecException(e)
}
/**
* 对字符串进行解码,并捕获可能发生的异常。
*
* @param string 需要解码的字符串
* @return 解码后的字节数组结果
* @throws CodecException 如果解码过程中发生异常
*/
fun catchDecode(string: String) = try {
decode(string)
} catch (e: Exception) {
throw CodecException(e)
}
/**
* 将字节数组编码为字符串。
*
* @param bytes 需要编码的字节数组
* @return 编码后的字符串结果
*/
fun encode(bytes: ByteArray): String
/**
* 将Base64字符串解码为字节数组
* 将字符串解码为字节数组。
*
* @param string 需要解码的Base64字符串
* @return 解码后的字节数组
* @param string 需要解码的字符串
* @return 解码后的字节数组结果
*/
fun decode(string: String): ByteArray
/**
* 将文件内容编码为Base64字符串
* 对文件内容进行编码。
*
* @param file 需要编码的文件
* @return 文件内容的Base64编码字符串
* @throws IOException 当文件读取失败时抛出
* @param file 需要编码的文件对象
* @return 文件内容编码后的字符串结果
*/
@Throws(IOException::class)
fun encode(file: File): String {
return encode(file.readBytes())
fun encode(file: File) = catchEncode(file.readBytes())
/**
* 将字符串解码后写入指定文件。
*
* @param file 目标文件对象
* @param string 需要解码的字符串
*/
fun decode(file: File, string: String) =
file.writeBytes(catchDecode(string))
/**
* 安全地对文件内容进行编码,如果发生异常则返回 null。
*
* @param file 需要编码的文件对象
* @return 文件内容编码后的字符串结果,若失败则返回 null
*/
fun encodeSafe(file: File) = try {
encode(file)
} catch (_: Exception) {
null
}
/**
* 将Base64字符串解码并写入文件
* 安全地将字符串解码并写入指定文件,如果成功则返回 true,否则返回 false。
*
* @param file 目标文件
* @param string 需要解码的Base64字符串
* @throws IOException 当文件写入失败时抛出
* @param file 目标文件对象
* @param string 需要解码的字符串
* @return 操作是否成功的布尔值
*/
@Throws(IOException::class)
fun decode(file: File, string: String) {
file.writeBytes(decode(string))
fun decodeSafe(file: File, string: String) = try {
decode(file, string)
true
} catch (_: Exception) {
false
}
/**
* 安全地将文件内容编码为Base64字符串,出现异常时返回null
*
* @param file 需要编码的文件
* @return 文件内容的Base64编码字符串,失败时返回null
*/
fun encodeSafe(file: File): String? {
return try {
encode(file)
} catch (_: Exception) {
null
}
}
/**
* 安全地将Base64字符串解码并写入文件,返回操作是否成功
*
* @param file 目标文件
* @param string 需要解码的Base64字符串
* @return 操作成功返回true,失败返回false
*/
fun decodeSafe(file: File, string: String): Boolean {
return try {
decode(file, string)
true
} catch (_: Exception) {
false
}
}
/**
* 将路径对应的文件内容编码为Base64字符串
* 对路径指向的文件内容进行编码。
*
* @param path 需要编码的文件路径
* @return 文件内容的Base64编码字符串
* @throws IOException 当文件读取失败时抛出
* @return 文件内容编码后的字符串结果
*/
@Throws(IOException::class)
fun encode(path: Path): String {
return encode(path.toFile().readBytes())
}
fun encode(path: Path) = catchEncode(path.toFile().readBytes())
/**
* 将Base64字符串解码并写入路径指定的文件
* 将字符串解码后写入指定路径的文件。
*
* @param path 目标文件路径
* @param string 需要解码的Base64字符串
* @throws IOException 当文件写入失败时抛出
* @param string 需要解码的字符串
*/
@Throws(IOException::class)
fun decode(path: Path, string: String) {
path.toFile().writeBytes(decode(string))
}
fun decode(path: Path, string: String) = path.toFile().writeBytes(catchDecode(string))
/**
* 安全地将路径对应的文件内容编码为Base64字符串,出现异常时返回null
* 安全地对路径指向的文件内容进行编码,如果发生异常则返回 null。
*
* @param path 需要编码的文件路径
* @return 文件内容的Base64编码字符串,失败时返回null
* @return 文件内容编码后的字符串结果,若失败则返回 null
*/
fun encodeSafe(path: Path): String? {
return try {
encode(path)
} catch (_: Exception) {
null
}
fun encodeSafe(path: Path) = try {
encode(path)
} catch (_: Exception) {
null
}
/**
* 安全地将Base64字符串解码并写入路径指定的文件,返回操作是否成功
* 安全地将字符串解码并写入指定路径的文件,如果成功则返回 true,否则返回 false。
*
* @param path 目标文件路径
* @param string 需要解码的Base64字符串
* @return 操作成功返回true,失败返回false
* @param string 需要解码的字符串
* @return 操作是否成功的布尔值
*/
fun decodeSafe(path: Path, string: String): Boolean {
return try {
decode(path, string)
true
} catch (_: Exception) {
false
}
fun decodeSafe(path: Path, string: String) = try {
decode(path, string)
true
} catch (_: Exception) {
false
}
/**
* 将字符串编码为Base64字符串
* 对字符串进行编码。
*
* @param string 需要编码的字符串
* @return 编码后的Base64字符串
* @return 编码后的字符串结果
*/
fun encode(string: String): String {
return encode(string.toByteArray())
}
fun encode(string: String) = catchEncode(string.toByteArray())
/**
* 将Base64字符串解码为字符串
* 将字符串解码为 UTF-8 格式的字符串。
*
* @param string 需要解码的Base64字符串
* @return 解码后的字符串
* @param string 需要解码的字符串
* @return 解码后的 UTF-8 字符串结果
*/
fun decodetoString(string: String): String {
return decode(string).toString(Charsets.UTF_8)
}
fun decodetoString(string: String) = catchDecode(string).toString(Charsets.UTF_8)
}
@@ -16,15 +16,29 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseType.kt
* LastUpdate 2026-02-04 21:54:04
* LastUpdate 2026-02-09 19:54:38
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.base
enum class BaseType(val baseCodec: BaseCodec) {
BASE16(com.mingliqiye.utils.base.BASE16),
BASE64(com.mingliqiye.utils.base.BASE64),
BASE91(com.mingliqiye.utils.base.BASE91),
BASE256(com.mingliqiye.utils.base.BASE256),
import com.mingliqiye.utils.base.code.Base10
import com.mingliqiye.utils.base.code.Base16
import com.mingliqiye.utils.base.code.Base2
import com.mingliqiye.utils.base.code.Base256
import com.mingliqiye.utils.base.code.Base64
import com.mingliqiye.utils.base.code.Base91
enum class BaseType(val baseCodec: BaseCodec) : BaseCodec {
BASE2(Base2),
BASE10(Base10),
BASE16(Base16),
BASE64(Base64),
BASE91(Base91),
BASE256(Base256);
override fun encode(bytes: ByteArray) = baseCodec.encode(bytes)
override fun decode(string: String) = baseCodec.decode(string)
}
@@ -1,72 +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 BaseUtils.kt
* LastUpdate 2026-02-08 03:00:37
* UpdateUser MingLiPro
*/
@file:JvmName("BaseUtils")
package com.mingliqiye.utils.base
import com.mingliqiye.utils.base.code.Base10
import com.mingliqiye.utils.base.code.Base16
import com.mingliqiye.utils.base.code.Base256
import com.mingliqiye.utils.base.code.Base64
import com.mingliqiye.utils.base.code.Base91
@Deprecated(
"重命名", replaceWith = ReplaceWith(
expression = "Base10", imports = ["com.mingliqiye.utils.base.code"]
)
)
val BASE10: BaseCodec
get() = Base10
@Deprecated(
"重命名", replaceWith = ReplaceWith(
expression = "Base16", imports = ["com.mingliqiye.utils.base.code"]
)
)
val BASE16: BaseCodec
get() = Base16
@Deprecated(
"重命名", replaceWith = ReplaceWith(
expression = "Base64", imports = ["com.mingliqiye.utils.base.code"]
)
)
val BASE64: BaseCodec
get() = Base64
@Deprecated(
"重命名", replaceWith = ReplaceWith(
expression = "Base91", imports = ["com.mingliqiye.utils.base.code"]
)
)
val BASE91: BaseCodec
get() = Base91
@Deprecated(
"重命名", replaceWith = ReplaceWith(
expression = "Base256", imports = ["com.mingliqiye.utils.base.code"]
)
)
val BASE256: BaseCodec
get() = Base256
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ByteBufferUtils.kt
* LastUpdate 2026-01-11 09:44:19
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
@@ -26,6 +26,7 @@ package com.mingliqiye.utils.bytes
import java.io.IOException
import java.io.OutputStream
import java.nio.BufferUnderflowException
import java.nio.ByteBuffer
import java.nio.charset.Charset
@@ -0,0 +1,50 @@
/*
* 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 ByteConvertible.kt
* LastUpdate 2026-02-08 10:25:22
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.bytes
import java.io.OutputStream
import java.io.Serializable
import java.nio.ByteBuffer
interface ByteConvertible : Serializable {
fun toBytes(): ByteArray
fun writeToStream(outputStream: OutputStream) {
outputStream.write(toBytes())
}
fun putToByteBuffer(byteBuffer: ByteBuffer) {
byteBuffer.put(toBytes())
}
companion object {
fun OutputStream.write(byteConvertible: ByteConvertible) {
byteConvertible.writeToStream(this)
}
fun ByteBuffer.put(byteConvertible: ByteConvertible) {
byteConvertible.putToByteBuffer(this)
}
}
}
@@ -16,14 +16,14 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ByteUtils.kt
* LastUpdate 2026-01-14 13:01:44
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
@file:JvmName("ByteUtils")
package com.mingliqiye.utils.bytes
import com.mingliqiye.utils.base.BASE16
import com.mingliqiye.utils.base.code.Base16
import com.mingliqiye.utils.stream.SuperStream
/**
@@ -125,5 +125,5 @@ fun hexStringToByteArray(string: String): ByteArray {
* @return 对应的十六进制字符串
*/
fun bytesToHex(bytes: ByteArray): String {
return BASE16.encode(bytes)
return Base16.encode(bytes)
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile CloneUtils.kt
* LastUpdate 2026-02-05 14:41:27
* LastUpdate 2026-02-08 10:36:51
* UpdateUser MingLiPro
*/
@file:JvmName("CloneUtils")
@@ -24,17 +24,18 @@
package com.mingliqiye.utils.clone
import com.mingliqiye.utils.exception.JsonException
import com.mingliqiye.utils.json.api.base.JsonApi
import com.mingliqiye.utils.json.api.JSONA
import java.io.*
inline fun <reified T> Serializable.deepClone(): T {
return deepClone(this) as T
@JvmName("_inline_deepClone")
inline fun <reified T : Serializable> T.deepClone(): T {
return deepClone(this)
}
inline fun <reified T> T.deepJsonClone(jsonApi: JsonApi): T {
inline fun <reified T> T.deepJsonClone(): T {
try {
return jsonApi.convert(this as Any, this!!.javaClass) as T
return JSONA.convert(this as Any, this!!.javaClass) as T
} catch (e: Exception) {
throw JsonException(
"Failed to deep clone object using JSON", e
@@ -0,0 +1,36 @@
/*
* 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 CodecException.kt
* LastUpdate 2026-02-09 19:52:21
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.exception
class CodecException : MingLiUtilsBaseException {
constructor()
constructor(message: String) : super(message)
constructor(throwable: Throwable) : super(throwable)
constructor(message: String, throwable: Throwable) : super(message, throwable)
constructor(
message: String? = null,
throwable: Throwable? = null,
enableSuppression: Boolean = false,
writableStackTrace: Boolean = false
) : super(message, throwable, enableSuppression, writableStackTrace)
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile HttpStatusException.kt
* LastUpdate 2026-02-05 14:55:04
* LastUpdate 2026-02-10 01:12:53
* UpdateUser MingLiPro
*/
@@ -29,7 +29,7 @@ package com.mingliqiye.utils.exception
* @param message 异常信息,默认为 null
* @param cause 异常原因,默认为 null
*/
sealed class HttpStatusException(
open class HttpStatusException(
open val statusCode: Int,
override val message: String? = null,
override val cause: Throwable? = null
@@ -16,13 +16,13 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile HttpUrlException.kt
* LastUpdate 2026-02-05 15:21:48
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.exception
open class HttpUrlException : HttpException {
open class HttpUrlException : MingLiUtilsBaseException {
constructor()
constructor(message: String) : super(message)
constructor(throwable: Throwable) : super(throwable)
@@ -31,6 +31,6 @@ open class HttpUrlException : HttpException {
message: String? = null,
throwable: Throwable? = null,
enableSuppression: Boolean = false,
writableStackTrace: Boolean = false
writableStackTrace: Boolean = false,
) : super(message, throwable, enableSuppression, writableStackTrace)
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JsonObjectCastException.kt
* LastUpdate 2026-02-07 15:11:42
* LastUpdate 2026-02-09 19:52:21
* UpdateUser MingLiPro
*/
@@ -1,5 +1,5 @@
/*
* Copyright 2025 mingliqiye
* 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.
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ForEach.kt
* LastUpdate 2025-09-15 12:44:46
* LastUpdate 2026-02-27 12:45:39
* UpdateUser MingLiPro
*/
@file:JvmName("ForEach")
@@ -58,10 +58,8 @@ fun <T> forEach(
else -> {
// 对于其他类型的可迭代对象,使用增强 for 循环并手动维护索引
var index = 0
for (element in iterable) {
for ((index, element) in iterable.withIndex()) {
action.call(element, index)
index++
}
}
}
@@ -16,14 +16,14 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Pipeline.kt
* LastUpdate 2026-02-05 15:22:21
* LastUpdate 2026-02-24 09:10:26
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.functions
import com.mingliqiye.utils.require.Require
import java.util.*
import kotlin.reflect.KClass
/**
* 流水线操作类,提供链式调用的操作方式来处理数据转换和操作
@@ -112,6 +112,7 @@ class Pipeline<T>(private val value: T) {
* @throws ClassCastException 当类型转换失败时抛出异常
*/
@Throws(ClassCastException::class)
@Suppress("UNCHECKED_CAST")
fun <E> cast(type: Class<E>): Pipeline<E> = Pipeline(value as E)
/**
@@ -160,7 +161,7 @@ class Pipeline<T>(private val value: T) {
fun require(
any: Any, message: String, exception: Class<out Exception> = IllegalArgumentException::class.java
): Pipeline<T> {
Require.require(Objects.equals(any, value), message, exception)
Require.require(any == value, message, exception)
return this
}
@@ -174,7 +175,7 @@ class Pipeline<T>(private val value: T) {
fun require(
any: Any, message: String
): Pipeline<T> {
Require.RequireLayz.require(any == value, message)
Require.require(any == value, message)
return this
}
@@ -194,6 +195,38 @@ class Pipeline<T>(private val value: T) {
return this
}
/**
* 验证当前值是否等于指定值,如果不相等则抛出异常
* @param any 比较的目标值
* @param message 错误消息
* @param exception 异常类型,默认为IllegalArgumentException
* @return 当前Pipeline实例
*/
fun require(
any: Any,
message: String,
exception: KClass<out Throwable> = IllegalArgumentException::class
): Pipeline<T> {
Require.require(any == value, message, exception)
return this
}
/**
* 使用P1RFunction验证当前值是否满足条件,不满足则抛出异常
* @param must 验证条件函数
* @param message 错误消息
* @param exception 异常类型,默认为IllegalArgumentException
* @return 当前Pipeline实例
*/
fun require(
must: P1RFunction<T, Boolean>,
message: String,
exception: KClass<out Throwable> = IllegalArgumentException::class
): Pipeline<T> {
Require.require(must.call(value), message, exception)
return this
}
/**
* 使用P1RFunction验证当前值是否满足条件,不满足则抛出IllegalArgumentException异常
* @param must 验证条件函数
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,29 @@
/*
* 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 MediaTypeUtils.kt
* LastUpdate 2026-02-27 22:15:03
* UpdateUser MingLiPro
*/
@file:JvmName("MediaTypeUtils")
package com.mingliqiye.utils.http
import okhttp3.MediaType.Companion.toMediaType
fun MediaType.okhttp(): okhttp3.MediaType = this.value.toMediaType()
@@ -0,0 +1,50 @@
/*
* 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 OkHttpUtils.kt
* LastUpdate 2026-02-27 22:16:15
* UpdateUser MingLiPro
*/
@file:JvmName("OkHttpUtils")
package com.mingliqiye.utils.http.okhttp
import com.mingliqiye.utils.http.MediaType
import com.mingliqiye.utils.http.okhttp
import com.mingliqiye.utils.json.api.JSONA
import com.mingliqiye.utils.json.api.JSONA.toJson
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
inline fun <reified T> Response.json() = body.use {
JSONA.parse<T>(it.bytes())
}
fun Response.text() = body.use {
String(it.bytes())
}
fun OkHttpClient.request() = Request.Builder()
fun Request.Builder.call(okHttpClient: OkHttpClient) = okHttpClient.newCall(this.build())
fun Request.Builder.postWithJson(data: Any): Request.Builder {
data.toJson().toRequestBody(MediaType.APPLICATION_JSON.okhttp())
return this
}
@@ -1,964 +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 I18N.kt
* LastUpdate 2026-02-05 22:39:07
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.i18n
import com.fasterxml.jackson.databind.ObjectMapper
import org.slf4j.Logger
object I18N {
@JvmStatic
private var _Internationalization: Internationalization = Internationalization(
clazz = I18N::class.java,
objectMapper = ObjectMapper(),
isloadSlef = true
)
fun setInternationalization(value: Internationalization) {
this._Internationalization = value
}
fun getInternationalization() = _Internationalization
@JvmStatic
fun getString(string: String, vararg any: Any): String = _Internationalization.getString(string, *any)
@JvmStatic
fun getString(string: String): String = _Internationalization.getString(string)
@JvmStatic
fun getKeyString(key: String): String = _Internationalization.getKeyString(key)
fun Logger.infoTranslater(string: String, vararg any: Any) = this.info(getString(string, *any))
fun Logger.warnTranslater(string: String, vararg any: Any) = this.warn(getString(string, *any))
fun Logger.debugTranslater(string: String, vararg any: Any) = this.debug(getString(string, *any))
fun Logger.traceTranslater(string: String, vararg any: Any) = this.trace(getString(string, *any))
// 0 个参数
fun Logger.errorTranslater(string: String, any1: Any) {
this.error(getString(string))
}
fun Logger.errorTranslater(string: String) {
this.error(getString(string))
}
// 2 个参数
fun Logger.errorTranslater(string: String, any1: Any, any2: Any) {
this.error(getString(string, any1, any2))
}
// 3 个参数
fun Logger.errorTranslater(string: String, any1: Any, any2: Any, any3: Any) {
this.error(getString(string, any1, any2, any3))
}
// 4 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
) {
this.error(getString(string, any1, any2, any3, any4))
}
// 5 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
) {
this.error(getString(string, any1, any2, any3, any4, any5))
}
// 6 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
) {
this.error(getString(string, any1, any2, any3, any4, any5, any6))
}
// 7 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
) {
this.error(getString(string, any1, any2, any3, any4, any5, any6, any7))
}
// 8 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
) {
this.error(getString(string, any1, any2, any3, any4, any5, any6, any7, any8))
}
// 9 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
) {
this.error(getString(string, any1, any2, any3, any4, any5, any6, any7, any8, any9))
}
// 10 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
) {
this.error(getString(string, any1, any2, any3, any4, any5, any6, any7, any8, any9, any10))
}
// 11 个参数
fun Logger.errorTranslater(
string: String,
any1: Any, any2: Any, any3: Any, any4: Any, any5: Any,
any6: Any, any7: Any, any8: Any, any9: Any, any10: Any, any11: Any,
) {
this.error(getString(string, any1, any2, any3, any4, any5, any6, any7, any8, any9, any10, any11))
}
// 12 个参数
fun Logger.errorTranslater(
string: String,
any1: Any, any2: Any, any3: Any, any4: Any, any5: Any,
any6: Any, any7: Any, any8: Any, any9: Any, any10: Any, any11: Any, any12: Any,
) {
this.error(
getString(string, any1, any2, any3, any4, any5, any6, any7, any8, any9, any10, any11, any12)
)
}
// 13 个参数
fun Logger.errorTranslater(
string: String,
any1: Any, any2: Any, any3: Any, any4: Any, any5: Any,
any6: Any, any7: Any, any8: Any, any9: Any, any10: Any, any11: Any, any12: Any, any13: Any,
) {
this.error(
getString(string, any1, any2, any3, any4, any5, any6, any7, any8, any9, any10, any11, any12, any13),
)
}
// 14 个参数
fun Logger.errorTranslater(
string: String,
any1: Any, any2: Any, any3: Any, any4: Any, any5: Any,
any6: Any, any7: Any, any8: Any, any9: Any, any10: Any, any11: Any, any12: Any, any13: Any, any14: Any,
) {
this.error(
getString(
string, any1, any2, any3, any4, any5, any6, any7, any8, any9, any10, any11, any12, any13, any14
)
)
}
// 15 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
any11: Any,
any12: Any,
any13: Any,
any14: Any,
any15: Any,
) {
this.error(
getString(
string, any1, any2, any3, any4, any5, any6, any7, any8, any9, any10, any11, any12, any13, any14, any15
)
)
}
// 16 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
any11: Any,
any12: Any,
any13: Any,
any14: Any,
any15: Any,
any16: Any,
) {
this.error(
getString(
string,
any1,
any2,
any3,
any4,
any5,
any6,
any7,
any8,
any9,
any10,
any11,
any12,
any13,
any14,
any15,
any16
)
)
}
// 17 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
any11: Any,
any12: Any,
any13: Any,
any14: Any,
any15: Any,
any16: Any,
any17: Any,
) {
this.error(
getString(
string,
any1,
any2,
any3,
any4,
any5,
any6,
any7,
any8,
any9,
any10,
any11,
any12,
any13,
any14,
any15,
any16,
any17
)
)
}
// 18 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
any11: Any,
any12: Any,
any13: Any,
any14: Any,
any15: Any,
any16: Any,
any17: Any,
any18: Any,
) {
this.error(
getString(
string,
any1,
any2,
any3,
any4,
any5,
any6,
any7,
any8,
any9,
any10,
any11,
any12,
any13,
any14,
any15,
any16,
any17,
any18
)
)
}
// 19 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
any11: Any,
any12: Any,
any13: Any,
any14: Any,
any15: Any,
any16: Any,
any17: Any,
any18: Any,
any19: Any,
) {
this.error(
getString(
string,
any1,
any2,
any3,
any4,
any5,
any6,
any7,
any8,
any9,
any10,
any11,
any12,
any13,
any14,
any15,
any16,
any17,
any18,
any19
)
)
}
// 20 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
any11: Any,
any12: Any,
any13: Any,
any14: Any,
any15: Any,
any16: Any,
any17: Any,
any18: Any,
any19: Any,
any20: Any,
) {
this.error(
getString(
string,
any1,
any2,
any3,
any4,
any5,
any6,
any7,
any8,
any9,
any10,
any11,
any12,
any13,
any14,
any15,
any16,
any17,
any18,
any19,
any20
)
)
}
fun Logger.errorTranslater(string: String, throwable: Throwable) {
this.error(getString(string), throwable)
}
// 1 个参数
fun Logger.errorTranslater(string: String, any1: Any, throwable: Throwable) {
this.error(getString(string, any1), throwable)
}
// 2 个参数
fun Logger.errorTranslater(string: String, any1: Any, any2: Any, throwable: Throwable) {
this.error(getString(string, any1, any2), throwable)
}
// 3 个参数
fun Logger.errorTranslater(string: String, any1: Any, any2: Any, any3: Any, throwable: Throwable) {
this.error(getString(string, any1, any2, any3), throwable)
}
// 4 个参数
fun Logger.errorTranslater(
string: String, any1: Any, any2: Any, any3: Any, any4: Any, throwable: Throwable
) {
this.error(getString(string, any1, any2, any3, any4), throwable)
}
// 5 个参数
fun Logger.errorTranslater(
string: String, any1: Any, any2: Any, any3: Any, any4: Any, any5: Any, throwable: Throwable
) {
this.error(getString(string, any1, any2, any3, any4, any5), throwable)
}
// 6 个参数
fun Logger.errorTranslater(
string: String, any1: Any, any2: Any, any3: Any, any4: Any, any5: Any, any6: Any, throwable: Throwable
) {
this.error(getString(string, any1, any2, any3, any4, any5, any6), throwable)
}
// 7 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
throwable: Throwable
) {
this.error(getString(string, any1, any2, any3, any4, any5, any6, any7), throwable)
}
// 8 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
throwable: Throwable
) {
this.error(getString(string, any1, any2, any3, any4, any5, any6, any7, any8), throwable)
}
// 9 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
throwable: Throwable
) {
this.error(getString(string, any1, any2, any3, any4, any5, any6, any7, any8, any9), throwable)
}
// 10 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
throwable: Throwable
) {
this.error(getString(string, any1, any2, any3, any4, any5, any6, any7, any8, any9, any10), throwable)
}
// 11 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
any11: Any,
throwable: Throwable
) {
this.error(getString(string, any1, any2, any3, any4, any5, any6, any7, any8, any9, any10, any11), throwable)
}
// 12 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
any11: Any,
any12: Any,
throwable: Throwable
) {
this.error(
getString(string, any1, any2, any3, any4, any5, any6, any7, any8, any9, any10, any11, any12), throwable
)
}
// 13 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
any11: Any,
any12: Any,
any13: Any,
throwable: Throwable
) {
this.error(
getString(string, any1, any2, any3, any4, any5, any6, any7, any8, any9, any10, any11, any12, any13),
throwable
)
}
// 14 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
any11: Any,
any12: Any,
any13: Any,
any14: Any,
throwable: Throwable
) {
this.error(
getString(
string, any1, any2, any3, any4, any5, any6, any7, any8, any9, any10, any11, any12, any13, any14
), throwable
)
}
// 15 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
any11: Any,
any12: Any,
any13: Any,
any14: Any,
any15: Any,
throwable: Throwable
) {
this.error(
getString(
string, any1, any2, any3, any4, any5, any6, any7, any8, any9, any10, any11, any12, any13, any14, any15
), throwable
)
}
// 16 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
any11: Any,
any12: Any,
any13: Any,
any14: Any,
any15: Any,
any16: Any,
throwable: Throwable
) {
this.error(
getString(
string,
any1,
any2,
any3,
any4,
any5,
any6,
any7,
any8,
any9,
any10,
any11,
any12,
any13,
any14,
any15,
any16
), throwable
)
}
// 17 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
any11: Any,
any12: Any,
any13: Any,
any14: Any,
any15: Any,
any16: Any,
any17: Any,
throwable: Throwable
) {
this.error(
getString(
string,
any1,
any2,
any3,
any4,
any5,
any6,
any7,
any8,
any9,
any10,
any11,
any12,
any13,
any14,
any15,
any16,
any17
), throwable
)
}
// 18 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
any11: Any,
any12: Any,
any13: Any,
any14: Any,
any15: Any,
any16: Any,
any17: Any,
any18: Any,
throwable: Throwable
) {
this.error(
getString(
string,
any1,
any2,
any3,
any4,
any5,
any6,
any7,
any8,
any9,
any10,
any11,
any12,
any13,
any14,
any15,
any16,
any17,
any18
), throwable
)
}
// 19 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
any11: Any,
any12: Any,
any13: Any,
any14: Any,
any15: Any,
any16: Any,
any17: Any,
any18: Any,
any19: Any,
throwable: Throwable
) {
this.error(
getString(
string,
any1,
any2,
any3,
any4,
any5,
any6,
any7,
any8,
any9,
any10,
any11,
any12,
any13,
any14,
any15,
any16,
any17,
any18,
any19
), throwable
)
}
// 20 个参数
fun Logger.errorTranslater(
string: String,
any1: Any,
any2: Any,
any3: Any,
any4: Any,
any5: Any,
any6: Any,
any7: Any,
any8: Any,
any9: Any,
any10: Any,
any11: Any,
any12: Any,
any13: Any,
any14: Any,
any15: Any,
any16: Any,
any17: Any,
any18: Any,
any19: Any,
any20: Any,
throwable: Throwable
) {
this.error(
getString(
string,
any1,
any2,
any3,
any4,
any5,
any6,
any7,
any8,
any9,
any10,
any11,
any12,
any13,
any14,
any15,
any16,
any17,
any18,
any19,
any20
), throwable
)
}
}
@@ -1,144 +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 Internationalization.kt
* LastUpdate 2026-02-06 08:47:26
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.i18n
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import org.slf4j.Logger
import java.net.URL
import java.util.*
class Internationalization {
var clazz: Class<*>
var objectMapper: ObjectMapper
var locale: Locale
var backLocale: Locale
val langPath: String
val thisName: String
val thisBackName: String
private var log: Logger = MingLiLoggerFactory.getLogger<Internationalization>()
constructor(
clazz: Class<*>,
objectMapper: ObjectMapper,
locale: Locale = Locale.getDefault(),
backLocale: Locale = Locale.US,
langPath: String = "/lang",
isloadSlef: Boolean = false
) {
this.clazz = clazz
this.objectMapper = objectMapper
this.locale = locale
this.backLocale = backLocale
this.langPath = langPath
thisName = getLanguageName(locale)
thisBackName = getLanguageName(backLocale)
readJson("/assets/mingli-utils/lang/${thisName}.json", Internationalization::class.java, thisName)
if (!isloadSlef) {
if (!readJson(fileName = "$langPath/${thisName}.json", lang = thisName)) {
log.warn(getString("com.mingliqiye.utils.i18n.readjson.error", "$langPath/${thisName}.json"))
}
}
if (thisName != thisBackName) {
readJson("/assets/mingli-utils/lang/${thisBackName}.json", Internationalization::class.java, thisBackName)
if (!isloadSlef) {
if (!readJson(fileName = "$langPath/${thisBackName}.json", lang = thisBackName)) {
log.warn(getString("com.mingliqiye.utils.i18n.readjson.error", "$langPath/${thisBackName}.json"))
}
}
}
}
fun getString(string: String, vararg any: Any): String {
return getString(string).format(*any)
}
fun getString(string: String): String {
return getKeyString(string)
}
fun getKeyString(key: String): String {
val s = localesData[thisName]?.get(key) ?: localesData[thisBackName]?.get(key)
if (s == null) {
return key
}
return s
}
fun getLanguageName(locale: Locale): String =
if (locale.country == null || locale.language == null) locale.country + locale.language else locale.language + '_' + locale.country
constructor(
clazz: Class<*>,
objectMapper: ObjectMapper,
) : this(
locale = Locale.getDefault(), clazz = clazz, objectMapper = objectMapper
)
constructor(
clazz: Class<*>, objectMapper: ObjectMapper, langPath: String = "/lang"
) : this(
locale = Locale.getDefault(), clazz = clazz, langPath = langPath, objectMapper = objectMapper
)
val localesData: MutableMap<String, MutableMap<String, String>> = mutableMapOf()
fun getlangFile(
clazzd: Class<*>, fileName: String
): URL? {
return clazzd.getResource(fileName)
}
fun readJson(
fileName: String, clazzd: Class<*> = clazz, lang: String
): Boolean {
val byteArray: ByteArray? = getlangFile(clazzd, fileName)?.openStream()?.use { it.readBytes() }
if (byteArray == null) return false
val node: JsonNode = objectMapper.readTree(byteArray)
if (node.isArray) return false
if (node.isEmpty) return false
var m = localesData[lang]
if (m == null) {
m = mutableMapOf()
localesData[lang] = m
}
readJsonNode(node, "", m)
return true
}
fun readJsonNode(node: JsonNode, path: String, map: MutableMap<String, String>) {
val fields = node.properties().iterator()
while (fields.hasNext()) {
val (k, v) = fields.next()
val pathName = if (path.isEmpty()) path + k else "$path.$k"
if (v.isTextual) {
map[pathName] = v.asText()
} else if (v.isObject) {
readJsonNode(v, pathName, map)
}
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2025 mingliqiye
* 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.
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile InputStreamUtils.kt
* LastUpdate 2025-09-15 17:26:34
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
@file:JvmName("InputStreamUtils")
@@ -28,23 +28,16 @@ import java.io.OutputStream
import java.nio.charset.Charset
fun InputStream.readAllText(charset: Charset = Charsets.UTF_8): String {
return this.readAllBytes().toString(charset)
}
fun InputStream.readAllBytes(): ByteArray {
return this.readBytes()
}
fun InputStream.readAllText(charset: Charset = Charsets.UTF_8) = this.readAllBytes().toString(charset)
fun InputStream.exportBytes(out: OutputStream) {
out.write(this.readAllBytes())
out.flush()
}
fun InputStream.readToList(): List<Byte> {
return this.readBytes().toList()
}
fun InputStream.readToList(): List<Byte> = this.readBytes().toList()
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
@JvmName("readInputStreamAllBytes")
fun InputStream.readAllBytes(): ByteArray = this.readBytes()
@@ -15,8 +15,8 @@
*
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile IO.kt
* LastUpdate 2026-02-06 13:21:33
* CurrentFile SIO.kt
* LastUpdate 2026-02-27 12:36:11
* UpdateUser MingLiPro
*/
@@ -29,46 +29,134 @@ import org.slf4j.Logger
import java.io.OutputStream
import java.io.PrintStream
/**
* 已弃用的IO对象,所有方法都委托给SIO对象
* @deprecated 请使用SIO对象替代
*/
@Deprecated("This IO is deprecated. reName SIO", replaceWith = ReplaceWith("SIO"), level = DeprecationLevel.WARNING)
object IO {
/**
* 打印多个参数,使用空格分隔
* @param args 要打印的参数数组
*/
@JvmStatic
fun print(vararg args: Any?) = SIO.print(*args)
/**
* 打印多个参数并换行,使用空格分隔
* @param args 要打印的参数数组
*/
@JvmStatic
fun println(vararg args: Any?) = SIO.println(*args)
/**
* 打印多个参数并换行,指定分隔符
* @param sp 分隔符
* @param args 要打印的参数数组
*/
@JvmStatic
fun printlnA(sp: String, vararg args: Any?) = SIO.printlnA(sp, *args)
/**
* 打印多个参数,指定分隔符
* @param sp 分隔符,默认为空字符串
* @param args 要打印的参数数组
*/
@JvmStatic
fun printA(sp: String = "", vararg args: Any?) = SIO.printA(sp, *args)
/**
* 重定向 System.out 到 INFO 级别日志
*/
@JvmStatic
fun redirectOutToInfo() = SIO.redirectOutToInfo()
/**
* 重定向 System.err 到 ERROR 级别
*/
@JvmStatic
fun redirectErrToError() = SIO.redirectErrToError()
/**
* 完全重定向(包括第三方库的输出)
*/
@JvmStatic
fun redirectAll() = SIO.redirectAll()
/**
* 恢复原始输出流
*/
@JvmStatic
fun restore() = SIO.restore()
}
/**
* IO工具类,提供打印功能和系统输出流重定向到日志的功能
*/
object IO {
object SIO {
/**
* 扩展函数:将字节数组以十六进制格式打印,每两个字符用空格分隔
* @return 原始字节数组
*/
@JvmStatic
fun ByteArray.println(): ByteArray {
this.toHexString().chunked(2).println()
return this
}
/**
* 扩展函数:将列表以花括号格式打印,元素间用逗号分隔
* @return 原始列表
*/
@JvmStatic
fun <T> List<T>.println(): List<T> {
println("{" + ",".join(this) + "}")
return this
}
/**
* 扩展函数:将数组以花括号格式打印,元素间用逗号分隔
* @return 原始数组
*/
@JvmStatic
fun <T> Array<T>.println(): Array<T> {
println("{" + ",".join(this) + "}")
return this
}
/**
* 扩展函数:打印任意对象并返回该对象
* @return 原始对象
*/
@JvmStatic
fun <T> T.println(): T {
println(this)
return this
}
/**
* 原始标准输出流的备份
*/
@JvmStatic
var originalOut: PrintStream = System.out
val originalOut: PrintStream = System.out
/**
* 原始错误输出流的备份
*/
@JvmStatic
var originalErr: PrintStream = System.err
val originalErr: PrintStream = System.err
/**
* 用于记录标准输出的日志记录器
*/
@JvmStatic
val outLog: Logger = MingLiLoggerFactory.getLogger("out")
/**
* 用于记录错误输出的日志记录器
*/
@JvmStatic
val errLog: Logger = MingLiLoggerFactory.getLogger("err")
@@ -119,10 +207,11 @@ object IO {
kotlin.io.print(sb)
}
/**
* 重定向 System.out 到 INFO 级别日志
* 创建自定义PrintStream,将输出内容缓冲并记录到INFO级别日志中
*/
@JvmStatic
/**
* 重定向 System.out 到 INFO 级别日志
*/
fun redirectOutToInfo() {
val outLogger = PrintStream(object : OutputStream() {
private val buffer = StringBuilder()
@@ -169,10 +258,11 @@ object IO {
System.setOut(outLogger)
}
/**
* 重定向 System.err 到 ERROR 级别
* 创建自定义PrintStream,将错误输出内容缓冲并记录到ERROR级别日志中
*/
@JvmStatic
/**
* 重定向 System.err 到 ERROR 级别
*/
fun redirectErrToError() {
val errLogger = PrintStream(object : OutputStream() {
private val buffer = StringBuilder()
@@ -219,19 +309,21 @@ object IO {
System.setErr(errLogger)
}
/**
* 完全重定向(包括第三方库的输出)
* 同时重定向标准输出和错误输出到对应的日志级别
*/
@JvmStatic
/**
* 完全重定向(包括第三方库的输出)
*/
fun redirectAll() {
redirectOutToInfo()
redirectErrToError()
}
/**
* 恢复原始输出流
* 将System.out和System.err恢复到原始状态
*/
@JvmStatic
/**
* 恢复原始输出流
*/
fun restore() {
System.setOut(originalOut)
System.setErr(originalErr)
@@ -0,0 +1,217 @@
/*
* 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 Jackson3JsonApi.kt
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json
import com.mingliqiye.utils.exception.JsonException
import com.mingliqiye.utils.json.api.base.JsonApi
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.getJackson3Module
import tools.jackson.core.type.TypeReference
import tools.jackson.databind.JsonNode
import tools.jackson.databind.ObjectMapper
import tools.jackson.databind.node.ObjectNode
import java.lang.reflect.Type
class Jackson3JsonApi : JsonApi {
var get: () -> ObjectMapper
var set: (ObjectMapper) -> Unit
private var _prObjectMapper: ObjectMapper? = null
private var objectMapper: ObjectMapper
get() = get()
set(value) = set(value)
constructor(objectMapper: ObjectMapper) {
_prObjectMapper = objectMapper
get = { _prObjectMapper!! }
set = { _prObjectMapper = it }
}
constructor(
get: () -> ObjectMapper,
set: (ObjectMapper) -> Unit,
) {
this.get = get
this.set = set
}
override fun <T> parse(json: String, clazz: Class<T>): T {
try {
return objectMapper.readValue(json, clazz)
} catch (e: Exception) {
throw JsonException("Failed to parse JSON to ${clazz.simpleName}", e)
}
}
override fun <T> parse(json: String, type: JsonTypeReference<T>): T {
try {
return objectMapper.readValue(json, object : TypeReference<T>() {
override fun getType(): Type = type.type
})
} catch (e: Exception) {
throw JsonException("Failed to parse JSON to type: $type", e)
}
}
override fun format(obj: Any): String {
try {
return objectMapper.writeValueAsString(obj)
} catch (e: Exception) {
throw JsonException("Failed to format object to JSON: ${obj.javaClass.simpleName}", e)
}
}
override fun formatPretty(obj: Any): String {
try {
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj)
} catch (e: Exception) {
throw JsonException("Failed to format object to pretty JSON: ${obj.javaClass.simpleName}", e)
}
}
override fun isValidJson(json: String): Boolean {
return try {
objectMapper.readTree(json)
true
} catch (e: Exception) {
false
}
}
override fun merge(vararg jsons: String): String {
try {
if (jsons.isEmpty()) return "{}"
val resultNode = objectMapper.createObjectNode()
for (json in jsons) {
val node = objectMapper.readTree(json)
if (node is ObjectNode) {
resultNode.setAll(node)
} else {
throw JsonException("Cannot merge non-object JSON: $json")
}
}
return objectMapper.writeValueAsString(resultNode)
} catch (e: Exception) {
throw JsonException("Failed to merge JSON objects", e)
}
}
override fun getNodeValue(json: String, path: String): String? {
try {
val rootNode = objectMapper.readTree(json)
val node = rootNode.at(path)
return if (node.isMissingNode || node.isNull) {
null
} else {
node.asString()
}
} catch (e: Exception) {
throw JsonException("Failed to get node value at path: $path", e)
}
}
override fun updateNodeValue(json: String, path: String, newValue: Any): String {
try {
val rootNode = objectMapper.readTree(json)
// 处理 JSON Pointer 路径
val pathParts = path.split("/").filter { it.isNotEmpty() }
if (pathParts.isEmpty()) {
// 替换整个根节点
return objectMapper.writeValueAsString(newValue)
}
when (val parentNode = findParentNode(rootNode, pathParts)) {
is ObjectNode -> {
val fieldName = pathParts.last()
val valueNode = objectMapper.valueToTree<JsonNode>(newValue)
parentNode.replace(fieldName, valueNode)
}
else -> {
throw JsonException("Cannot update node: parent is not an object node at path: $path")
}
}
return objectMapper.writeValueAsString(rootNode)
} catch (e: Exception) {
throw JsonException("Failed to update node value at path: $path", e)
}
}
override fun <D> convert(source: Any, destinationClass: Class<D>): D {
try {
return objectMapper.convertValue(source, destinationClass)
} catch (e: Exception) {
throw JsonException(
"Failed to convert from ${source.javaClass.simpleName} to ${destinationClass.simpleName}",
e
)
}
}
override fun <D> convert(
source: Any,
destinationType: JsonTypeReference<D>,
): D {
try {
return objectMapper.convertValue(source, object : TypeReference<D>() {
override fun getType(): Type = destinationType.type
})
} catch (e: Exception) {
throw JsonException("Failed to convert from ${source.javaClass.simpleName} to type: $destinationType", e)
}
}
// 辅助方法:查找父节点
private fun findParentNode(root: JsonNode, pathParts: List<String>): JsonNode {
var current: JsonNode = root
// 遍历到最后一个元素之前(即找到父节点)
for (i in 0 until pathParts.size - 1) {
val part = pathParts[i]
current = when {
part.matches(Regex("\\d+")) -> current.get(part.toInt())
else -> current.get(part)
} ?: throw JsonException("Path not found: ${pathParts.subList(0, i + 1).joinToString("/")}")
}
return current
}
override fun addJsonConverter(c: BaseJsonConverter<*, *>) {
val mapperBuilder = Jackson3ApiJavaHelper.rebuild(objectMapper)
mapperBuilder.addModule(c.getJackson3Module())
this.objectMapper = mapperBuilder.build()
}
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JSONA.kt
* LastUpdate 2026-02-05 10:34:30
* LastUpdate 2026-02-26 14:14:18
* UpdateUser MingLiPro
*/
@@ -28,6 +28,7 @@ import com.mingliqiye.utils.json.api.base.JsonApi
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.api.type.listType
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.getJsonConverter
import java.io.File
import java.io.InputStream
import java.io.OutputStream
@@ -71,7 +72,7 @@ object JSONA {
* @param T 继承自JsonApi的具体实现类
*/
inline fun <reified T : JsonApi> setJsonApi() {
setJsonApi(T::class.java.newInstance() as JsonApi)
setJsonApi(T::class.java.getConstructor().newInstance() as JsonApi)
}
/**
@@ -127,14 +128,6 @@ object JSONA {
@JvmStatic
fun format(obj: Any): String = getJsonApi().format(obj)
/**
* 将对象格式化为带Unicode转义的JSON字符串
*
* @param obj 待格式化的对象
* @return 格式化后的带Unicode转义的JSON字符串
*/
@JvmStatic
fun formatUnicode(obj: Any): String = getJsonApi().formatPrettyUnicode(obj)
/**
* 从文件路径解析JSON为指定类型的对象
@@ -291,24 +284,6 @@ object JSONA {
@JvmStatic
fun formatPrettyBytes(obj: Any): ByteArray = getJsonApi().formatPrettyBytes(obj)
/**
* 将对象格式化为带Unicode转义的美化JSON字符串
*
* @param obj 待格式化的对象
* @return 格式化后的带Unicode转义的美化JSON字符串
*/
@JvmStatic
fun formatPrettyUnicode(obj: Any): String = getJsonApi().formatPrettyUnicode(obj)
/**
* 将对象格式化为带Unicode转义的美化JSON字节数组
*
* @param obj 待格式化的对象
* @return 格式化后的带Unicode转义的美化JSON字节数组
*/
@JvmStatic
fun formatPrettyUnicodeBytes(obj: Any): ByteArray = getJsonApi().formatPrettyUnicodeBytes(obj)
/**
* 将对象格式化为美化格式的JSON字符串并写入文件
*
@@ -345,41 +320,6 @@ object JSONA {
@JvmStatic
fun formatPretty(obj: Any, stream: OutputStream) = getJsonApi().formatPretty(obj, stream)
/**
* 将对象格式化为带Unicode转义的美化JSON字符串并写入文件
*
* @param obj 待格式化的对象
* @param file 文件路径
*/
@JvmStatic
fun formatPrettyUnicode(obj: Any, file: String) = getJsonApi().formatPrettyUnicode(obj, file)
/**
* 将对象格式化为带Unicode转义的美化JSON字符串并写入文件
*
* @param obj 待格式化的对象
* @param file Path对象
*/
@JvmStatic
fun formatPrettyUnicode(obj: Any, file: Path) = getJsonApi().formatPrettyUnicode(obj, file)
/**
* 将对象格式化为带Unicode转义的美化JSON字符串并写入文件
*
* @param obj 待格式化的对象
* @param file File对象
*/
@JvmStatic
fun formatPrettyUnicode(obj: Any, file: File) = getJsonApi().formatPrettyUnicode(obj, file)
/**
* 将对象格式化为带Unicode转义的美化JSON字符串并写入输出流
*
* @param obj 待格式化的对象
* @param stream OutputStream对象
*/
@JvmStatic
fun formatPrettyUnicode(obj: Any, stream: OutputStream) = getJsonApi().formatPrettyUnicode(obj, stream)
/**
* 将对象格式化为JSON字节数组
@@ -390,14 +330,6 @@ object JSONA {
@JvmStatic
fun formatBytes(obj: Any): ByteArray = getJsonApi().formatBytes(obj)
/**
* 将对象格式化为带Unicode转义的JSON字节数组
*
* @param obj 待格式化的对象
* @return 格式化后的带Unicode转义的JSON字节数组
*/
@JvmStatic
fun formatUnicodeBytes(obj: Any): ByteArray = getJsonApi().formatUnicodeBytes(obj)
/**
* 将对象格式化为JSON字符串并写入文件
@@ -435,41 +367,6 @@ object JSONA {
@JvmStatic
fun format(obj: Any, stream: OutputStream) = getJsonApi().format(obj, stream)
/**
* 将对象格式化为带Unicode转义的JSON字符串并写入文件
*
* @param obj 待格式化的对象
* @param file 文件路径
*/
@JvmStatic
fun formatUnicode(obj: Any, file: String) = getJsonApi().formatUnicode(obj, file)
/**
* 将对象格式化为带Unicode转义的JSON字符串并写入文件
*
* @param obj 待格式化的对象
* @param file Path对象
*/
@JvmStatic
fun formatUnicode(obj: Any, file: Path) = getJsonApi().formatUnicode(obj, file)
/**
* 将对象格式化为带Unicode转义的JSON字符串并写入文件
*
* @param obj 待格式化的对象
* @param file File对象
*/
@JvmStatic
fun formatUnicode(obj: Any, file: File) = getJsonApi().formatUnicode(obj, file)
/**
* 将对象格式化为带Unicode转义的JSON字符串并写入输出流
*
* @param obj 待格式化的对象
* @param stream OutputStream对象
*/
@JvmStatic
fun formatUnicode(obj: Any, stream: OutputStream) = getJsonApi().formatUnicode(obj, stream)
/**
* 将JSON字符串解析为指定元素类型的List集合
@@ -627,8 +524,7 @@ object JSONA {
*
* @param T 继承自BaseJsonConverter的具体实现类
*/
inline fun <reified T : BaseJsonConverter<*, *>> addJsonConverter() =
addJsonConverter(T::class.java.newInstance())
inline fun <reified T : BaseJsonConverter<*, *>> addJsonConverter() = addJsonConverter(getJsonConverter<T>())
inline fun <reified T> String.parseJson() = parse<T>(this)
@@ -639,6 +535,9 @@ object JSONA {
fun Any.toJson() = format(this)
@JvmStatic
fun jacksonKotlinObjectMapper(): ObjectMapper = ObjectMapper().jacksonKotlinObjectMapper()
@JvmStatic
fun ObjectMapper.jacksonKotlinObjectMapper(): ObjectMapper = this.registerModule(kotlinModule())
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JacksonJsonApi.kt
* LastUpdate 2026-02-05 14:41:27
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
@@ -32,6 +32,7 @@ import com.mingliqiye.utils.exception.JsonException
import com.mingliqiye.utils.json.api.base.JsonApi
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.getJacksonModule
/**
* 基于Jackson的JSON处理实现类,提供JSON字符串解析、格式化、合并、节点操作等功能。
@@ -110,7 +111,7 @@ class JacksonJsonApi : JsonApi {
}
}
override fun formatUnicode(obj: Any): String {
fun formatUnicode(obj: Any): String {
return try {
objectMapper.writer().with(JsonGenerator.Feature.ESCAPE_NON_ASCII).writeValueAsString(obj)
} catch (e: Exception) {
@@ -135,7 +136,7 @@ class JacksonJsonApi : JsonApi {
}
}
override fun formatPrettyUnicode(obj: Any): String {
fun formatPrettyUnicode(obj: Any): String {
return try {
objectMapper.writerWithDefaultPrettyPrinter().with(JsonGenerator.Feature.ESCAPE_NON_ASCII)
.writeValueAsString(obj)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JsonApi.kt
* LastUpdate 2026-02-04 21:00:48
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
@@ -25,6 +25,7 @@ package com.mingliqiye.utils.json.api.base
import com.mingliqiye.utils.json.api.type.JsonTypeReference
import com.mingliqiye.utils.json.api.type.listType
import com.mingliqiye.utils.json.converters.base.BaseJsonConverter
import com.mingliqiye.utils.json.converters.base.getJsonConverter
import java.io.*
import java.nio.file.Files
import java.nio.file.Path
@@ -111,7 +112,7 @@ interface JsonApi {
* @return 解析后的Map集合
*/
inline fun <reified K, reified V> JsonApi.parseMap(
json: String
json: String,
): MutableMap<K, V> = parseMap(json, K::class.java, V::class.java)
@@ -133,7 +134,7 @@ interface JsonApi {
*/
@JvmStatic
inline fun <reified T : BaseJsonConverter<*, *>> JsonApi.addJsonConverter() {
addJsonConverter(T::class.java.newInstance())
addJsonConverter(getJsonConverter<T>())
}
}
@@ -166,8 +167,6 @@ interface JsonApi {
*/
fun format(obj: Any): String
fun formatUnicode(obj: Any): String
/**
* 从文件路径读取JSON并解析为指定类型对象
*
@@ -333,7 +332,7 @@ interface JsonApi {
* @return 解析后的对象实例或默认值
**/
fun <T> parse(
json: String, type: JsonTypeReference<T>, defaultValue: T
json: String, type: JsonTypeReference<T>, defaultValue: T,
): T {
return try {
parse<T>(json, type)
@@ -354,12 +353,6 @@ interface JsonApi {
return formatPretty(obj)!!.toByteArray()
}
fun formatPrettyUnicode(obj: Any): String
fun formatPrettyUnicodeBytes(obj: Any): ByteArray {
return formatPrettyUnicode(obj)!!.toByteArray()
}
fun formatPretty(obj: Any, file: String) {
formatPretty(obj, Paths.get(file))
}
@@ -378,30 +371,8 @@ interface JsonApi {
stream.write(formatPrettyBytes(obj))
}
fun formatPrettyUnicode(obj: Any, file: String) {
formatPrettyUnicode(obj, Paths.get(file))
}
fun formatPrettyUnicode(obj: Any, file: Path) {
formatPrettyUnicode(obj, file.toFile())
}
fun formatPrettyUnicode(obj: Any, file: File) {
FileOutputStream(file).use { fos ->
formatPrettyUnicode(obj, fos)
}
}
fun formatPrettyUnicode(obj: Any, stream: OutputStream) {
stream.write(formatPrettyUnicodeBytes(obj))
}
fun formatBytes(obj: Any): ByteArray {
return format(obj)!!.toByteArray()
}
fun formatUnicodeBytes(obj: Any): ByteArray {
return formatUnicode(obj)!!.toByteArray()
return format(obj).toByteArray()
}
fun format(obj: Any, file: String) {
@@ -422,23 +393,6 @@ interface JsonApi {
stream.write(formatPrettyBytes(obj))
}
fun formatUnicode(obj: Any, file: String) {
formatUnicode(obj, Paths.get(file))
}
fun formatUnicode(obj: Any, file: Path) {
formatUnicode(obj, file.toFile())
}
fun formatUnicode(obj: Any, file: File) {
FileOutputStream(file).use { fos ->
formatUnicode(obj, fos)
}
}
fun formatUnicode(obj: Any, stream: OutputStream) {
stream.write(formatPrettyUnicodeBytes(obj))
}
/**
* 将JSON字符串解析为指定元素类型的List集合
@@ -463,7 +417,7 @@ interface JsonApi {
* @return 解析后的Map集合
</V></K> */
fun <K, V> parseMap(
json: String, keyType: Class<K>, valueType: Class<V>
json: String, keyType: Class<K>, valueType: Class<V>,
): MutableMap<K, V> {
val mapType: JsonTypeReference<MutableMap<K, V>> = object : JsonTypeReference<MutableMap<K, V>>() {}
return parse<MutableMap<K, V>>(json, mapType)
@@ -16,16 +16,16 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile TypeReference.kt
* LastUpdate 2026-02-04 21:00:48
* LastUpdate 2026-02-26 14:11:35
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.api.type
import com.mingliqiye.utils.string.join
import sun.reflect.generics.reflectiveObjects.WildcardTypeImpl
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.lang.reflect.WildcardType
class TypeReference(
val rawClass: Type,
@@ -40,23 +40,37 @@ class TypeReference(
override fun getOwnerType(): Type? = null
override fun toString(): String = "${getRawString(rawType)}<${
",".join(typeArguments, TypeReference::getRawString)
override fun toString(): String = "${getRawString(rawClass)}<${
",".join(typeArguments) { getRawString(it) }
}>"
companion object {
fun getRawString(s: Any): String {
if (s is Class<*>) {
return s.name
fun getRawString(type: Type): String {
return when (type) {
is Class<*> -> type.name
is WildcardType -> {
val upperBounds = type.upperBounds
val lowerBounds = type.lowerBounds
when {
upperBounds.isNotEmpty() && upperBounds[0] != Any::class.java -> {
"? extends ${getRawString(upperBounds[0])}"
}
lowerBounds.isNotEmpty() -> {
"? super ${getRawString(lowerBounds[0])}"
}
else -> "?"
}
}
is ParameterizedType -> {
of(type).toString()
}
else -> type.typeName
}
if (s is WildcardTypeImpl) {
return getRawString(s.upperBounds[0])
}
if (s is ParameterizedType) {
return of(s).toString()
}
return s.toString()
}
inline fun <reified T> of(): TypeReference {
@@ -64,13 +78,17 @@ class TypeReference(
}
fun of(type: Type): TypeReference {
if (type is Class<*>) {
return TypeReference(type)
return when (type) {
is Class<*> -> TypeReference(type)
is ParameterizedType -> TypeReference(type.rawType, *type.actualTypeArguments)
is WildcardType -> {
// 处理通配符类型,返回上界类型
val upperBound = type.upperBounds.firstOrNull() ?: Any::class.java
TypeReference(upperBound)
}
else -> throw IllegalStateException("无法获取类型: $type")
}
if (type is ParameterizedType) {
return TypeReference(type.rawType, *type.actualTypeArguments)
}
throw IllegalStateException("无法获取类型: $type")
}
}
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile AnnotationGetter.kt
* LastUpdate 2026-02-06 16:57:45
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
@@ -73,6 +73,7 @@ interface AnnotationGetter {
* @param clazz 目标注解类型的Class对象。
* @return 如果annotation的类型与clazz一致,则返回annotation转换为T类型的实例;否则返回null。
*/
@Suppress("UNCHECKED_CAST")
override fun <T : Annotation> get(clazz: Class<T>): T? =
if (annotation.javaClass == clazz) annotation as T else null
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile BaseJsonConverter.kt
* LastUpdate 2026-02-08 01:22:35
* LastUpdate 2026-02-26 15:59:35
* UpdateUser MingLiPro
*/
@@ -31,4 +31,4 @@ package com.mingliqiye.utils.json.converters.base
* @param F 源类型,表示需要被转换的数据类型。
* @param T 目标类型,表示转换后的数据类型。
*/
interface BaseJsonConverter<F, T> : JackSonJsonConverter<F, T>
interface BaseJsonConverter<F, T> : JsonConverter<F, T>
@@ -0,0 +1,62 @@
/*
* 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 JackJson3Deserializer.kt
* LastUpdate 2026-02-26 13:02:52
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import tools.jackson.core.JsonParser
import tools.jackson.core.JsonToken
import tools.jackson.databind.BeanProperty
import tools.jackson.databind.DeserializationContext
import tools.jackson.databind.ValueDeserializer
class JackJson3Deserializer<F, T>(
val property: BeanProperty? = null,
val jsonConverter: JsonConverter<F, T>
) : ValueDeserializer<F>() {
override fun deserialize(
p: JsonParser,
ctxt: DeserializationContext?
): F? {
if (p.currentToken() == JsonToken.VALUE_NULL) return null
return jsonConverter.deConvert(p.readValueAs(jsonConverter.getToClass()), object : AnnotationGetter {
override fun <T : Annotation> get(clazz: Class<T>): T? = property?.getAnnotation(clazz)
})
}
/**
* 上下文感知方法:设置当前属性信息。
*
* @param ctxt 反序列化上下文,可选参数。
* @param property 当前属性信息。
* @return 返回当前反序列化器实例。
*/
override fun createContextual(
ctxt: DeserializationContext?,
property: BeanProperty?
): JackJson3Deserializer<F, T> {
return JackJson3Deserializer(property, jsonConverter)
}
}
@@ -0,0 +1,66 @@
/*
* 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 JackJson3Serializer.kt
* LastUpdate 2026-02-26 13:04:18
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import tools.jackson.databind.BeanProperty
import tools.jackson.databind.SerializationContext
import tools.jackson.databind.ValueSerializer
import java.math.BigDecimal
import java.math.BigInteger
class JackJson3Serializer<F, T>(
val property: BeanProperty? = null,
val jsonConverter: JsonConverter<F, T>
) : ValueSerializer<F>() {
/**
* 序列化方法:将源对象转换为目标对象,并根据目标对象的类型写入 JSON。
*
* @param value 源对象,可能为 null。
* @param gen JSON 生成器,用于写入 JSON 数据。
* @param provider 序列化提供者,可选参数。
*/
override fun serialize(value: F, gen: tools.jackson.core.JsonGenerator, ctxt: SerializationContext) {
val data: T? = jsonConverter.convert(value, object : AnnotationGetter {
override fun <T : Annotation> get(clazz: Class<T>): T? = property?.getAnnotation(clazz)
})
when (data) {
null -> gen.writeNull()
is String -> gen.writeString(data)
is Long -> gen.writeNumber(data)
is Short -> gen.writeNumber(data)
is Byte -> gen.writeNumber(data.toShort())
is Int -> gen.writeNumber(data)
is BigDecimal -> gen.writeNumber(data)
is BigInteger -> gen.writeNumber(data)
is Float -> gen.writeNumber(data)
is Double -> gen.writeNumber(data)
is Boolean -> gen.writeBoolean(data)
else -> throw IllegalArgumentException("not sport data type ${data.javaClass} $data")
}
}
override fun createContextual(ctxt: SerializationContext?, property: BeanProperty?): ValueSerializer<*> {
return JackJson3Serializer(property, jsonConverter)
}
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JackJsonSerializer.kt
* LastUpdate 2026-02-08 02:27:52
* LastUpdate 2026-02-26 12:55:57
* UpdateUser MingLiPro
*/
@@ -1,57 +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 JackSonJsonConverter.kt
* LastUpdate 2026-02-08 02:28:49
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.converters.base
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.module.SimpleModule
interface JackSonJsonConverter<F, T> : JsonConverter<F, T> {
companion object {
/**
* 扩展ObjectMapper,用于注册指定类型的模块。
*
* 此函数通过反射创建指定类型的实例,并调用其getJacksonModule方法来获取Jackson模块,
* 然后将该模块注册到当前ObjectMapper实例中。
*
* @param T 必须继承自BaseJsonConverter的泛型类型。
* @return 返回注册了模块后的ObjectMapper实例。
*/
inline fun <reified T : BaseJsonConverter<*, *>> ObjectMapper.addJsonConverter(): ObjectMapper =
this.registerModule(getJsonConverter<T>().getJacksonModule())
@JvmStatic
fun <T : BaseJsonConverter<*, *>> ObjectMapper.addJsonConverter(clazz: Class<T>): ObjectMapper =
this.registerModule(getJsonConverter(clazz).getJacksonModule())
}
/**
* 创建并返回一个 Jackson 模块,该模块包含自定义的序列化器和反序列化器。
*
* @return 配置了自定义序列化器和反序列化器的 SimpleModule 对象。
*/
fun getJacksonModule(): SimpleModule =
SimpleModule("${getFromClass().name}To${getToClass().name}")
.addSerializer(getFromClass(), JackJsonSerializer(null, this))
.addDeserializer(getFromClass(), JackJsonDeserializer(null, this))
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JsonConverterUtils.kt
* LastUpdate 2026-02-07 22:33:09
* LastUpdate 2026-02-26 16:01:49
* UpdateUser MingLiPro
*/
@file:JvmName("JsonConverterUtils")
@@ -49,6 +49,7 @@ fun getClass(type: Type?): Class<*>? {
inline fun <reified T : JsonConverter<*, *>> getJsonConverter(): T = getJsonConverter(T::class.java)
@Suppress("UNCHECKED_CAST")
fun <T : JsonConverter<*, *>> getJsonConverter(clazz: Class<T>): T {
try {
return clazz.getDeclaredMethod(
@@ -59,3 +60,25 @@ fun <T : JsonConverter<*, *>> getJsonConverter(clazz: Class<T>): T {
throw e
}
}
fun <T : BaseJsonConverter<*, *>> com.fasterxml.jackson.databind.ObjectMapper.addJsonConverter(clazz: Class<T>): com.fasterxml.jackson.databind.ObjectMapper =
this.registerModule(getJsonConverter(clazz).getJacksonModule())
@JvmName("inline_addJsonConverter")
inline fun <reified T : BaseJsonConverter<*, *>> com.fasterxml.jackson.databind.ObjectMapper.addJsonConverter(): com.fasterxml.jackson.databind.ObjectMapper =
this.registerModule(getJsonConverter(T::class.java).getJacksonModule())
/**
* 创建并返回一个 Jackson 模块,该模块包含自定义的序列化器和反序列化器。
*
* @return 配置了自定义序列化器和反序列化器的 SimpleModule 对象。
*/
fun <F, T> JsonConverter<F, T>.getJacksonModule(): com.fasterxml.jackson.databind.module.SimpleModule =
com.fasterxml.jackson.databind.module.SimpleModule("${getFromClass().name}To${getToClass().name}")
.addSerializer(getFromClass(), JackJsonSerializer(null, this))
.addDeserializer(getFromClass(), JackJsonDeserializer(null, this))
fun <F, T> JsonConverter<F, T>.getJackson3Module(): tools.jackson.databind.module.SimpleModule =
tools.jackson.databind.module.SimpleModule("${getFromClass().name}To${getToClass().name}")
.addSerializer(getFromClass(), JackJson3Serializer(null, this))
.addDeserializer(getFromClass(), JackJson3Deserializer(null, this))
@@ -1,5 +1,5 @@
/*
* Copyright 2025 mingliqiye
* 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.
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Maps.kt
* LastUpdate 2025-09-15 08:33:24
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
@@ -40,6 +40,10 @@ fun <K, V> newHashMap(size: Int): HashMap<K, V> {
return HashMap(size)
}
fun <K, V> newHashMap(): HashMap<K, V> {
return HashMap()
}
fun <K, V> newHashMap(vararg elements: Map.Entry<K, V>): HashMap<K, V> {
val map = HashMap<K, V>()
for (element in elements) {
@@ -1,5 +1,5 @@
/*
* Copyright 2025 mingliqiye
* 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.
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile MetaData.kt
* LastUpdate 2025-09-20 10:45:43
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
@file:JvmName("MetaData")
@@ -40,16 +40,6 @@ fun getMetaData(): Map<String, String> {
}.filter { it != null }.collect(toMap({ it!!.first }, { it!!.second }))
}
class MingliUtilsMetaData {
var buildTime: String = ""
var groupId: String = ""
var artifactId: String = ""
var version: String = ""
var buildJdkVersion: String = ""
var author: String = ""
var website: String = ""
}
val mingliUtilsMetaData: MingliUtilsMetaData by lazy {
val metaData = getMetaData()
MingliUtilsMetaData().apply {
@@ -0,0 +1,33 @@
/*
* 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 MingliUtilsMetaData.kt
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.metadata
class MingliUtilsMetaData {
var buildTime: String = ""
var groupId: String = ""
var artifactId: String = ""
var version: String = ""
var buildJdkVersion: String = ""
var author: String = ""
var website: String = ""
}
@@ -0,0 +1,263 @@
/*
* 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 KotlinReflect.kt
* LastUpdate 2026-03-11 08:16:32
* UpdateUser MingLiPro
*/
@file:JvmName("KotlinReflect")
package com.mingliqiye.utils.reflect.kotlin
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.KType
import kotlin.reflect.full.*
import kotlin.reflect.jvm.isAccessible
/**
* 获取实例的 KClass
*/
inline fun <reified T : Any> T.kClass(): KClass<T> = T::class
/**
* 获取实例的 Java Class
*/
inline fun <reified T : Any> T.kClassJava(): Class<T> = T::class.java
/**
* 创建实例(通过无参构造函数)
*/
inline fun <reified T : Any> createInstance(): T = T::class.createInstance()
/**
* 创建实例(通过主构造函数,提供参数)
*/
inline fun <reified T : Any> createInstance(vararg args: Any?): T? {
val kClass = T::class
val constructor = kClass.primaryConstructor
return constructor?.let {
it.isAccessible = true
it.call(*args)
}
}
/**
* 获取所有父类(包括接口)
*/
inline fun <reified T : Any> T.superClasses(): Collection<KClass<*>> = T::class.allSuperclasses
/**
* 判断是否是某个类的子类
*/
inline fun <reified T : Any, reified S : Any> T.isSubclassOf(): Boolean = T::class.isSubclassOf(S::class)
/**
* 获取伴生对象实例
*/
inline fun <reified T : Any> T.companion(): Any? = T::class.companionObject?.objectInstance
/**
* 获取对象的所有属性名
*/
inline fun <reified T : Any> T.propertyNames(): List<String> = T::class.memberProperties.map { it.name }
/**
* 获取属性值
*/
inline fun <reified T : Any> T.getPropertyValue(name: String): Any? {
val property = T::class.memberProperties.find { it.name == name }
return if (property != null) {
property.isAccessible = true
property.get(this)
} else null
}
/**
* 设置属性值(仅适用于 var 属性)
*/
inline fun <reified T : Any> T.setPropertyValue(name: String, value: Any?): Boolean {
val property = T::class.memberProperties.find { it.name == name }
return if (property is kotlin.reflect.KMutableProperty<*>) {
property.isAccessible = true
property.setter.call(this, value)
true
} else false
}
/**
* 批量获取属性值
*/
inline fun <reified T : Any> T.getPropertyValues(vararg names: String): Map<String, Any?> {
val properties = T::class.memberProperties
return names.associateWith { name ->
properties.find { it.name == name }?.let {
it.isAccessible = true
it.get(this)
}
}
}
/**
* 获取所有属性及其值
*/
inline fun <reified T : Any> T.getAllPropertyValues(): Map<String, Any?> {
return T::class.memberProperties.associate { prop ->
prop.isAccessible = true
prop.name to prop.get(this)
}
}
/**
* 调用对象的方法
*/
inline fun <reified T : Any> T.callMethod(name: String, vararg args: Any?): Any? {
val function = T::class.functions.find { it.name == name }
return function?.let {
it.isAccessible = true
it.call(this, *args)
}
}
/**
* 调用静态方法(通过伴生对象)
*/
inline fun <reified T : Any> T.callStaticMethod(name: String, vararg args: Any?): Any? {
val companion = T::class.companionObject?.objectInstance
val function = companion?.let {
it::class.functions.find { func -> func.name == name }
}
return function?.let {
it.isAccessible = true
it.call(companion, *args)
}
}
/**
* 获取所有方法名
*/
inline fun <reified T : Any> T.methodNames(): List<String> = T::class.functions.map { it.name }
/**
* 检查类是否有特定注解
*/
inline fun <reified T : Any, reified A : Annotation> T.hasAnnotation(): Boolean = T::class.hasAnnotation<A>()
/**
* 获取所有带有特定注解的属性
*/
inline fun <reified T : Any, reified A : Annotation> T.propertiesWithAnnotation(): List<String> {
return T::class.memberProperties.filter { it.hasAnnotation<A>() }.map { it.name }
}
/**
* 获取所有带有特定注解的方法
*/
inline fun <reified T : Any, reified A : Annotation> T.methodsWithAnnotation(): List<String> {
return T::class.functions.filter { it.hasAnnotation<A>() }.map { it.name }
}
/**
* 获取泛型类型参数
*/
inline fun <reified T : Any> T.genericType(): KType = T::class.starProjectedType
/**
* 检查类型是否匹配
*/
inline fun <reified T : Any> T.isInstanceOf(instance: Any): Boolean = T::class.isInstance(instance)
// ==================== Java 互操作 ====================
/**
* 获取对应的 Java 方法
*/
inline fun <reified T : Any> T.getJavaMethod(name: String, vararg paramTypes: Class<*>): java.lang.reflect.Method? {
return T::class.java.getDeclaredMethod(name, *paramTypes).apply {
isAccessible = true
}
}
/**
* 获取对应的 Java 字段
*/
inline fun <reified T : Any> T.getJavaField(name: String): java.lang.reflect.Field? {
return T::class.java.getDeclaredField(name).apply {
isAccessible = true
}
}
/**
* 调用 Java 方法
*/
inline fun <reified T : Any> T.callJavaMethod(name: String, vararg args: Any?): Any? {
val method = T::class.java.methods.find { it.name == name }
return method?.let {
it.isAccessible = true
it.invoke(this, *args)
}
}
/**
* 获取所有构造函数
*/
inline fun <reified T : Any> T.constructors(): List<KFunction<T>> = T::class.constructors.toList()
/**
* 通过构造函数索引创建实例
*/
inline fun <reified T : Any> createInstanceByIndex(index: Int, vararg args: Any?): T? {
val constructors = T::class.constructors.toList()
return if (index < constructors.size) {
constructors[index].apply { isAccessible = true }.call(*args)
} else null
}
/**
* 比较两个对象的属性值
*/
inline fun <reified T : Any> T.compareWith(other: T, vararg properties: String): Map<String, Pair<Any?, Any?>> {
val result = mutableMapOf<String, Pair<Any?, Any?>>()
val props = T::class.memberProperties.associateBy { it.name }
properties.forEach { propName ->
props[propName]?.let { prop ->
prop.isAccessible = true
result[propName] = Pair(prop.get(this), prop.get(other))
}
}
return result
}
/**
* 获取单例对象实例(适用于 object 声明)
*/
inline fun <reified T : Any> getSingletonInstance(): T? {
return (T::class.objectInstance as? T)
}
/**
* 检查是否是单例对象
*/
inline fun <reified T : Any> T.isSingleton(): Boolean = T::class.objectInstance != null
/**
* 获取类的所有扩展函数
*/
inline fun <reified T : Any> T.extensionFunctions(): Collection<KFunction<*>> =
T::class.declaredMemberExtensionFunctions
@@ -16,160 +16,182 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Require.kt
* LastUpdate 2026-02-06 08:27:44
* LastUpdate 2026-02-24 09:03:42
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.require
import com.mingliqiye.utils.exception.InternalServerErrorException
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import org.slf4j.Logger
import java.lang.reflect.Constructor
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
import kotlin.reflect.KClass
/**
* 工具对象,用于提供条件检查功能。
* 支持抛出自定义异常、延迟消息构造以及日志记录等功能。
* 条件检查工具对象,提供多种重载的require方法用于参数验证和异常抛出
* 支持自定义异常类型、延迟消息构造和日志记录功能
*/
class Require(val defaultException: Class<out Throwable>) {
object Require {
@JvmStatic
var logger: Logger? = MingLiLoggerFactory.getLogger<Require>()
companion object {
@JvmStatic
val RequireLayz by lazy {
Require(IllegalArgumentException::class.java)
@JvmStatic
var isLogError = true
/**
* 检查条件是否满足,如果不满足则抛出指定类型的异常
* @param value 要检查的布尔条件
* @param throwable 异常类型Class对象
* @param layzMessage 延迟消息构造器
*/
@JvmStatic
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, throwable: Class<out Throwable>, layzMessage: RequireLayzMessageConstructor) {
contract {
returns() implies value
}
@JvmStatic
val RequireHttpLayz by lazy {
Require(InternalServerErrorException::class.java)
}
@JvmStatic
var logger: Logger? = MingLiLoggerFactory.getLogger<Require>()
@JvmStatic
var isLogError = true
/**
* 检查给定条件是否为真。如果为假,则使用延迟消息构造器生成异常并抛出。
*
* @param value 需要检查的布尔值。
* @param throwable 异常类型。
* @param layzMessage 延迟消息构造器。
*/
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, throwable: Class<out Throwable>, layzMessage: RequireLayzMessageConstructor) {
contract {
returns() implies value
}
require(value, layzMessage.call(), throwable)
}
/**
* 检查给定条件是否为真。如果为假,则使用延迟异常构造器生成异常并抛出。
*
* @param value 需要检查的布尔值。
* @param layzThrowable 延迟异常构造器。
*/
@JvmStatic
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, layzThrowable: RequireLayzExceptionConstructor) {
contract {
returns() implies value
}
if (!value) throwThrowable(layzThrowable.call())
}
/**
* 检查给定条件是否为真。如果为假,则根据指定的异常类型和消息生成异常并抛出。
*
* @param value 需要检查的布尔值。
* @param message 异常消息。
* @param throwable 异常类型。
*/
@JvmStatic
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, message: String, throwable: Class<out Throwable>) {
contract {
returns() implies value
}
if (!value) throwThrowable(getExceptionConstructor(throwable).newInstance(message))
}
/**
* 抛出指定的异常,并在启用日志记录时记录错误信息。
*
* @param throwable 需要抛出的异常。
*/
@JvmStatic
fun throwThrowable(throwable: Throwable) {
if (isLogError && logger != null) logger!!.error(throwable.message, throwable)
throw throwable
}
/**
* 检查给定条件是否为真。如果为假,则根据指定的异常类型抛出异常。
*
* @param value 需要检查的布尔值。
* @param message 异常消息。
* @param T 异常类型。
*/
@OptIn(ExperimentalContracts::class)
@JvmName("__inline_Require")
inline fun <reified T : Throwable> require(value: Boolean, message: String) {
contract {
returns() implies value
}
require(value, message, T::class.java)
}
/**
* 检查给定条件是否为真。如果为假,则根据指定的异常类型和延迟消息构造器生成异常并抛出。
*
* @param value 需要检查的布尔值。
* @param layzMessage 延迟消息构造器。
* @param T 异常类型。
*/
@OptIn(ExperimentalContracts::class)
@JvmName("__inline_Require")
inline fun <reified T : Throwable> require(value: Boolean, layzMessage: RequireLayzMessageConstructor) {
contract {
returns() implies value
}
if (!value) throwThrowable(getExceptionConstructor<T>().newInstance(layzMessage.call()))
}
/**
* 获取指定异常类型的构造函数(带字符串参数)。
*
* @param T 异常类型。
* @return 异常类型的构造函数。
*/
@JvmName("__inline_GetExceptionConstructor")
inline fun <reified T : Throwable> getExceptionConstructor(): Constructor<out T> =
getExceptionConstructor(T::class.java)
/**
* 获取指定异常类型的构造函数(带字符串参数)。
*
* @param throwable 异常类型。
* @return 异常类型的构造函数。
*/
@JvmStatic
@JvmName("__GetExceptionConstructor")
fun <T : Throwable> getExceptionConstructor(throwable: Class<out T>): Constructor<out T> =
throwable.getConstructor(String::class.java)
require(value, layzMessage.call(), throwable)
}
/**
* 检查给定条件是否为真。如果为假,则抛出 [IllegalArgumentException] 异常。
*
* @param value 需要检查的布尔值。
* 检查条件是否满足,如果不满足则抛出指定类型的异常
* @param value 要检查的布尔条件
* @param throwable 异常类型KClass对象
* @param layzMessage 延迟消息构造器
*/
@JvmStatic
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, throwable: KClass<out Throwable>, layzMessage: RequireLayzMessageConstructor) {
contract {
returns() implies value
}
require(value, throwable.java, layzMessage)
}
/**
* 检查条件是否满足,如果不满足则抛出延迟构造的异常
* @param value 要检查的布尔条件
* @param layzThrowable 延迟异常构造器
*/
@JvmStatic
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, layzThrowable: RequireLayzExceptionConstructor) {
contract {
returns() implies value
}
if (!value) throwThrowable(layzThrowable.call())
}
/**
* 检查条件是否满足,如果不满足则抛出指定消息和类型的异常
* @param value 要检查的布尔条件
* @param message 异常消息
* @param throwable 异常类型Class对象
*/
@JvmStatic
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, message: String, throwable: Class<out Throwable>) {
contract {
returns() implies value
}
if (!value) throwThrowable(getExceptionConstructor(throwable).newInstance(message))
}
/**
* 检查条件是否满足,如果不满足则抛出指定消息和类型的异常
* @param value 要检查的布尔条件
* @param message 异常消息
* @param throwable 异常类型KClass对象
*/
@JvmStatic
@OptIn(ExperimentalContracts::class)
fun require(value: Boolean, message: String, throwable: KClass<out Throwable>) {
contract {
returns() implies value
}
require(value, message, throwable.java)
}
/**
* 抛出异常并在启用日志时记录错误信息
* @param throwable 要抛出的异常对象
*/
@JvmStatic
fun throwThrowable(throwable: Throwable) {
if (isLogError && logger != null) logger!!.error(throwable.message, throwable)
throw throwable
}
/**
* 内联函数版本的条件检查,支持泛型异常类型
* @param T 异常类型
* @param value 要检查的布尔条件
* @param message 异常消息
*/
@OptIn(ExperimentalContracts::class)
@JvmName("__inline_Require")
@JvmStatic
inline fun <reified T : Throwable> require(value: Boolean, message: String) {
contract {
returns() implies value
}
require(value, message, T::class.java)
}
/**
* 内联函数版本的条件检查,支持泛型异常类型和延迟消息构造
* @param T 异常类型
* @param value 要检查的布尔条件
* @param layzMessage 延迟消息构造器
*/
@OptIn(ExperimentalContracts::class)
@JvmName("__inline_Require")
@JvmStatic
inline fun <reified T : Throwable> require(value: Boolean, layzMessage: RequireLayzMessageConstructor) {
contract {
returns() implies value
}
if (!value) throwThrowable(getExceptionConstructor<T>().newInstance(layzMessage.call()))
}
/**
* 获取指定异常类型的构造函数(内联泛型版本)
* @param T 异常类型
* @return 异常类型的构造函数
*/
@JvmName("__inline_GetExceptionConstructor")
@JvmStatic
inline fun <reified T : Throwable> getExceptionConstructor(): Constructor<out T> =
getExceptionConstructor(T::class.java)
/**
* 获取指定异常类型的构造函数
* @param throwable 异常类型Class对象
* @return 异常类型的构造函数
*/
@JvmStatic
@JvmName("__GetExceptionConstructor")
fun <T : Throwable> getExceptionConstructor(throwable: Class<out T>): Constructor<out T> =
throwable.getConstructor(String::class.java)
/**
* 获取指定异常类型的构造函数
* @param throwable 异常类型KClass对象
* @return 异常类型的构造函数
*/
@JvmStatic
@JvmName("__GetExceptionConstructor")
fun <T : Throwable> getExceptionConstructor(throwable: KClass<out T>): Constructor<out T> =
getExceptionConstructor(throwable.java)
/**
* 基础条件检查方法,不满足条件时抛出IllegalArgumentException
* @param value 要检查的布尔条件
*/
@OptIn(ExperimentalContracts::class)
@JvmStatic
fun require(value: Boolean) {
contract {
returns() implies value
@@ -178,30 +200,30 @@ class Require(val defaultException: Class<out Throwable>) {
}
/**
* 检查给定条件是否为真。如果为假,则使用延迟消息构造器生成 [IllegalArgumentException] 并抛出。
*
* @param value 需要检查的布尔值。
* @param layzMessage 延迟消息构造器。
* 使用延迟消息构造器进行条件检查,不满足时抛出IllegalArgumentException
* @param value 要检查的布尔条件
* @param layzMessage 延迟消息构造器
*/
@OptIn(ExperimentalContracts::class)
@JvmStatic
fun requireLayzMessage(value: Boolean, layzMessage: RequireLayzMessageConstructor) {
contract {
returns() implies value
}
require(value, defaultException, layzMessage)
require(value, IllegalArgumentException::class.java, layzMessage)
}
/**
* 检查给定条件是否为真。如果为假,则抛出 [IllegalArgumentException] 异常。
*
* @param value 需要检查的布尔值。
* @param message 异常消息。
* 带消息的条件检查方法,不满足条件时抛出IllegalArgumentException
* @param value 要检查的布尔条件
* @param message 异常消息
*/
@OptIn(ExperimentalContracts::class)
@JvmStatic
fun require(value: Boolean, message: String) {
contract {
returns() implies value
}
if (!value) throwThrowable(getExceptionConstructor(defaultException).newInstance(message))
if (!value) throwThrowable(getExceptionConstructor(IllegalArgumentException::class.java).newInstance(message))
}
}
@@ -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 ApplicationDestroyedRunner.kt
* LastUpdate 2026-03-10 09:04:02
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation
@Target(AnnotationTarget.FUNCTION)
annotation class ApplicationDestroyedRunner(
val order: Int = Int.MIN_VALUE
)
@@ -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 ApplicationStartedRunner.kt
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation
@Target(AnnotationTarget.FUNCTION)
annotation class ApplicationStartedRunner(
val order: Int = Int.MIN_VALUE,
)
@@ -0,0 +1,32 @@
/*
* 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 Listener.kt
* LastUpdate 2026-03-10 09:04:02
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.annotation
import org.springframework.core.annotation.AliasFor
import org.springframework.stereotype.Component
@Component
annotation class Listener(
@get:AliasFor(annotation = Component::class)
val value: String = ""
)
@@ -16,116 +16,27 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile AutoConfiguration.kt
* LastUpdate 2026-02-06 15:15:46
* LastUpdate 2026-03-10 09:04:30
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.autoconfigure
import com.mingliqiye.utils.i18n.I18N
import com.mingliqiye.utils.i18n.I18N.infoTranslater
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import com.mingliqiye.utils.system.computerName
import com.mingliqiye.utils.system.getPid
import com.mingliqiye.utils.system.jdkVersion
import com.mingliqiye.utils.system.userName
import com.mingliqiye.utils.time.DateTime
import com.mingliqiye.utils.time.Formatter
import org.springframework.boot.autoconfigure.AutoConfiguration
import org.springframework.context.annotation.ComponentScan
import java.io.IOException
/**
* 自动配置类,用于Spring Boot应用启动时加载相关组件和打印启动横幅。
*
* 该类通过@ComponentScan注解扫描指定包下的Bean,并在初始化时打印包含系统信息的启动横幅。
*/
@org.springframework.boot.autoconfigure.AutoConfiguration
@AutoConfiguration
@ComponentScan(
"com.mingliqiye.utils.springboot.bean",
"com.mingliqiye.utils.springboot.converters"
"com.mingliqiye.utils.springboot.converters",
"com.mingliqiye.utils.springboot.listener",
)
open class AutoConfiguration {
private val log = MingLiLoggerFactory.getLogger("MingliUtils-AutoConfiguration")
companion object {
/**
* 启动横幅字符串,包含艺术字体和占位符。
*/
private const val BANNER =
" | $$\\ $$\\ $$\\ $$\\ $$\\ $$$$$$$$\\ $$$$$$\\ \n" +
"| $$$\\ $$$ |$$ | $$ | $$ |\\__$$ __|$$ __$$\\ \n" +
"| $$$$\\ $$$$ |$$ | $$ | $$ | $$ | $$ / \\__| \n" +
"| $$\\$$\\$$ $$ |$$ | $$ | $$ | $$ | \\$$$$$$\\ \n" +
"| $$ \\$$$ $$ |$$ | $$ | $$ | $$ | \\____$$\\ \n" +
"| $$ |\\$ /$$ |$$ | $$ | $$ | $$ | $$\\ $$ | \n" +
"| $$ | \\_/ $$ |$$$$$$$$\\\\$$$$$$ | $$ | \\$$$$$$ \n" +
"| \\__| \\__|\\________|\\______/ \\__| \\______/ \n|\n"
/**
* 打印启动横幅,包含系统元数据(如JDK版本、进程ID、计算机名等)。
*
* 该方法从资源文件中读取元数据,并将其格式化后追加到横幅中进行输出。
* 如果读取资源失败,则仅打印默认横幅。
*/
fun printBanner() {
val bannerBuilder = StringBuilder(BANNER)
// 尝试从资源文件中读取元数据并拼接到横幅中
try {
val inputStream = AutoConfiguration::class.java.getResourceAsStream("/META-INF/meta-data") ?: return
inputStream.use { stream ->
var readlen: Int
val buffer = ByteArray(1024)
val metaData = StringBuilder()
// 逐块读取资源文件内容
while (stream.read(buffer).also { readlen = it } != -1) {
metaData.append(String(buffer, 0, readlen))
}
// 解析元数据并添加额外的系统信息
val da = metaData.toString().split("\n").toMutableList()
da.add("${I18N.getString("com.mingliqiye.utils.springboot.autoconfigure.AutoConfiguration.jdkRuntime")}=$jdkVersion")
da.add("${I18N.getString("com.mingliqiye.utils.springboot.autoconfigure.AutoConfiguration.pid")}=$getPid")
da.add("${I18N.getString("com.mingliqiye.utils.springboot.autoconfigure.AutoConfiguration.computerName")}=$computerName")
da.add("${I18N.getString("com.mingliqiye.utils.springboot.autoconfigure.AutoConfiguration.userName")}=$userName")
da.add(
"${I18N.getString("com.mingliqiye.utils.springboot.autoconfigure.AutoConfiguration.time")}=" + DateTime.now()
.format(Formatter.STANDARD_DATETIME_MILLISECOUND7, false)
)
// 格式化每条元数据并追加到横幅中
da.forEach { s: String ->
val d = s.trim { it <= ' ' }.split("=".toRegex(), 2).toTypedArray()
if (d.size >= 2) {
val content = "| -> " + I18N.getString(d[0]) + ": " + d[1]
val targetLength = 56
if (content.length < targetLength) {
bannerBuilder.append(
String.format(
"%-${targetLength}s\n",
content
)
)
} else {
bannerBuilder
.append(content, 0, targetLength)
.append("|\n")
}
}
}
}
} catch (e: IOException) {
// 捕获IO异常并打印堆栈跟踪
e.printStackTrace()
}
// 输出最终构建的横幅
println("")
println(bannerBuilder.toString().trim())
println("")
}
}
/**
* 初始化块,在类实例化时执行。
@@ -133,7 +44,6 @@ open class AutoConfiguration {
* 调用printBanner方法打印启动横幅,并记录日志表示自动配置成功。
*/
init {
printBanner()
log.infoTranslater("com.mingliqiye.utils.springboot.autoconfigure.AutoConfiguration.bean")
com.mingliqiye.utils.main.Main.printb()
}
}
@@ -0,0 +1,50 @@
/*
* 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 Jackson3AutoConfiguration.kt
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.autoconfigure;
import com.mingliqiye.utils.json.converters.DateTimeJsonConverter
import com.mingliqiye.utils.json.converters.UUIDJsonConverter
import com.mingliqiye.utils.json.converters.base.getJackson3Module
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import org.springframework.boot.autoconfigure.AutoConfigureAfter
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass
import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer
import org.springframework.context.annotation.Bean
@ConditionalOnClass(name = ["tools.jackson.databind.json.JsonMapper", "org.springframework.boot.jackson.autoconfigure.JacksonAutoConfiguration"])
@AutoConfigureAfter(name = ["org.springframework.boot.jackson.autoconfigure.JacksonAutoConfiguration"])
open class Jackson3AutoConfiguration {
private val logger = MingLiLoggerFactory.getLogger<Jackson3AutoConfiguration>()
@Bean
open fun myJsonMapperCustomizer(): JsonMapperBuilderCustomizer {
return JsonMapperBuilderCustomizer { builder ->
builder
.addModule(UUIDJsonConverter.getJsonConverter().getJackson3Module())
.addModule(DateTimeJsonConverter.getJsonConverter().getJackson3Module())
}.also {
logger.info("MingliUtils Jackson3 Serializers created")
}
}
}
@@ -0,0 +1,58 @@
/*
* 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 Jackson3JsonApiAutoConfiguration.kt
* LastUpdate 2026-02-26 14:24:33
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.autoconfigure
import com.mingliqiye.utils.exception.JsonException
import com.mingliqiye.utils.json.Jackson3JsonApi
import com.mingliqiye.utils.json.api.JSONA
import com.mingliqiye.utils.json.api.base.JsonApi
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import org.springframework.boot.autoconfigure.AutoConfigureAfter
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.context.annotation.Bean
import tools.jackson.databind.json.JsonMapper
@ConditionalOnClass(name = ["tools.jackson.databind.json.JsonMapper", "org.springframework.boot.jackson.autoconfigure.JacksonAutoConfiguration"])
@AutoConfigureAfter(name = ["com.mingliqiye.utils.springboot.autoconfigure.Jackson3AutoConfiguration"])
open class Jackson3JsonApiAutoConfiguration {
private val logger = MingLiLoggerFactory.getLogger<Jackson3JsonApiAutoConfiguration>()
@Bean
@ConditionalOnMissingBean
open fun jsonApi(jsonMapper: JsonMapper): JsonApi {
return Jackson3JsonApi(
get = { jsonMapper },
set = { throw JsonException("JSON API set method is not allowed.") }).also {
logger.info("JsonApi Bean Auto Configuration Success")
try {
JSONA.getJsonApi()
} catch (_: NullPointerException) {
JSONA.setJsonApi(it)
logger.info(
"JSONA Using {}", it.javaClass.name
)
}
}
}
}
@@ -16,20 +16,19 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JacksonAutoConfiguration.kt
* LastUpdate 2026-02-08 01:29:21
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.autoconfigure
import com.fasterxml.jackson.databind.ObjectMapper
import com.mingliqiye.utils.i18n.I18N.infoTranslater
import com.mingliqiye.utils.json.api.JSONA
import com.mingliqiye.utils.json.api.JacksonJsonApi
import com.mingliqiye.utils.json.api.base.JsonApi
import com.mingliqiye.utils.json.converters.DateTimeJsonConverter
import com.mingliqiye.utils.json.converters.UUIDJsonConverter
import com.mingliqiye.utils.json.converters.base.JackSonJsonConverter.Companion.addJsonConverter
import com.mingliqiye.utils.json.converters.base.addJsonConverter
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import org.slf4j.Logger
import org.springframework.boot.autoconfigure.AutoConfigureAfter
@@ -77,10 +76,10 @@ open class JacksonAutoConfiguration(objectMapper: ObjectMapper) {
* 注册自定义的 UUID 和 DateTime JSON 转换器模块到 ObjectMapper 中。
*/
init {
log.infoTranslater("com.mingliqiye.utils.springboot.autoconfigure.JsonApiAutoConfiguration.jacksonserializers")
objectMapper
.addJsonConverter<UUIDJsonConverter>()
.addJsonConverter<DateTimeJsonConverter>()
log.info("MingliUtils Jackson Serializers created")
}
/*
@@ -95,14 +94,13 @@ open class JacksonAutoConfiguration(objectMapper: ObjectMapper) {
@ConditionalOnMissingBean
open fun jsonApi(objectMapper: ObjectMapper): JsonApi {
return JacksonJsonApi(objectMapper).also {
log.infoTranslater("com.mingliqiye.utils.springboot.autoconfigure.JsonApiAutoConfiguration.jsonapiconfiged")
log.info("JsonApi Bean Auto Configuration Success")
try {
JSONA.getJsonApi()
} catch (_: NullPointerException) {
JSONA.setJsonApi(it)
log.infoTranslater(
"com.mingliqiye.utils.springboot.autoconfigure.JsonApiAutoConfiguration.jsonause",
it.javaClass.name
log.info(
"JSONA Using {}", it.javaClass.name
)
}
}
@@ -0,0 +1,72 @@
/*
* 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 Okhttp3AutoConfiguration.kt
* LastUpdate 2026-02-27 17:40:32
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.springboot.autoconfigure
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import org.slf4j.Logger
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.AutoConfiguration
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass
import org.springframework.context.annotation.Bean
import org.springframework.context.event.ContextClosedEvent
import org.springframework.context.event.EventListener
@AutoConfiguration
@ConditionalOnClass(name = ["okhttp3.OkHttpClient"])
open class Okhttp3AutoConfiguration {
private var okHttpClient: okhttp3.OkHttpClient? = null
val log: Logger = MingLiLoggerFactory.getLogger<Okhttp3AutoConfiguration>()
@Autowired(required = false)
open var userDefinedBuilder: okhttp3.OkHttpClient.Builder? = null
open fun initOkHttpClient() {
if (userDefinedBuilder == null) {
okHttpClient = okhttp3.OkHttpClient()
} else {
userDefinedBuilder!!.build()
}
}
@Bean
open fun okHttpClient(): okhttp3.OkHttpClient {
if (okHttpClient == null) {
initOkHttpClient()
}
log.info("OkHttpClient initialized (using ${if (userDefinedBuilder != null) "user-defined" else "default"} builder)")
return okHttpClient!!
}
@EventListener(ContextClosedEvent::class)
open fun handleContextClosed() {
if (okHttpClient != null) {
log.info("Context closed, cleaning up OkHttpClient...")
okHttpClient?.dispatcher?.executorService?.shutdown()
okHttpClient?.connectionPool?.evictAll()
okHttpClient?.dispatcher?.executorService?.shutdownNow()
}
}
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile SpringBeanUtils.kt
* LastUpdate 2026-02-04 16:50:39
* LastUpdate 2026-02-26 14:09:02
* UpdateUser MingLiPro
*/
@@ -40,7 +40,7 @@ class SpringBeanUtils : ApplicationContextAware {
private var applicationContext: ApplicationContext? = null
@Throws(BeansException::class)
inline fun <reified T> getBean() = getBean(T::class.java)
inline fun <reified T : Any> getBean() = getBean(T::class.java)
/**
* 根据Bean名称获取Bean实例
@@ -64,7 +64,7 @@ class SpringBeanUtils : ApplicationContextAware {
*/
@JvmStatic
@Throws(BeansException::class)
fun <T> getBean(clazz: Class<T>): T {
fun <T : Any> getBean(clazz: Class<T>): T {
return applicationContext!!.getBean(clazz)
}
@@ -78,7 +78,7 @@ class SpringBeanUtils : ApplicationContextAware {
*/
@JvmStatic
@Throws(BeansException::class)
fun <T> getBean(name: String, clazz: Class<T>): T {
fun <T : Any> getBean(name: String, clazz: Class<T>): T {
return applicationContext!!.getBean<T>(name, clazz)
}
}
@@ -0,0 +1,105 @@
/*
* 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
@Listener
class ApplicationListener {
val runningMap = HashMap<String, MutableList<ApplicationRunnerData>>()
companion object {
private val log = MingLiLoggerFactory.getLogger<ApplicationListener>()
}
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))
}
}
@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()
}
}
@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()
}
}
}
@@ -0,0 +1,33 @@
/*
* 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
data class ApplicationRunnerData(
val beanName: String, val order: Int, val bean: Any, val method: Method
) {
fun run() {
method.invoke(bean)
}
}
@@ -16,15 +16,14 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile StringUtils.kt
* LastUpdate 2026-02-06 08:35:07
* LastUpdate 2026-03-11 08:46:40
* UpdateUser MingLiPro
*/
@file:JvmName("StringUtils")
package com.mingliqiye.utils.string
import com.mingliqiye.utils.base.BASE16
import com.mingliqiye.utils.i18n.I18N.warnTranslater
import com.mingliqiye.utils.base.code.Base16
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import com.mingliqiye.utils.objects.isNull
import java.net.URLDecoder
@@ -100,13 +99,13 @@ fun format(str: String, vararg args: Any?): String {
// 检查参数数量
val placeholderCount = matches.count()
if (placeholderCount != args.size) {
log.warnTranslater(
"com.mingliqiye.utils.string.StringUtils.format.warn.placeholder",
log.warn(
"Placeholder Count: {}, Argument Count: {}",
placeholderCount, args.size
)
log.warnTranslater("com.mingliqiye.utils.string.StringUtils.format.warn.template", str)
log.warnTranslater(
"com.mingliqiye.utils.string.StringUtils.format.warn.arguments",
log.warn("Template: {}", str)
log.warn(
"Arguments: [{}]",
", ".join(args) {
if (it.isNull()) return@join "null:null"
"${it.javaClass.simpleName}:$it"
@@ -287,14 +286,14 @@ fun String.hmacSHA256String(keyS: String): String {
val key = keyS.toByteArray()
instance.init(SecretKeySpec(key, 0, key.size, "HmacSHA256"))
val bytes = instance.doFinal(this.toByteArray())
return BASE16.encode(bytes)
return Base16.encode(bytes)
}
fun String.md5String(): String {
val instance = MessageDigest.getInstance("MD5")
instance.update(this.toByteArray())
val bytes = instance.digest()
return BASE16.encode(bytes)
return Base16.encode(bytes)
}
fun String.hmacMd5String(keyS: String): String {
@@ -302,5 +301,5 @@ fun String.hmacMd5String(keyS: String): String {
val key = keyS.toByteArray()
instance.init(SecretKeySpec(key, 0, key.size, "HmacSHA256"))
val bytes = instance.doFinal(this.toByteArray())
return BASE16.encode(bytes)
return Base16.encode(bytes)
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile SystemUtil.kt
* LastUpdate 2026-01-31 20:47:59
* LastUpdate 2026-03-11 08:44:41
* UpdateUser MingLiPro
*/
@file:JvmName("SystemUtils")
@@ -454,6 +454,6 @@ fun loadProtocol(clazz: Class<*>? = null): String {
protocol = resource!!.protocol
return protocol.let {
isLoadprotocol = true
return@let it
it
}
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ThreadUtils.kt
* LastUpdate 2026-01-31 20:48:19
* LastUpdate 2026-02-09 20:14:22
* UpdateUser MingLiPro
*/
@@ -35,7 +35,7 @@ object ThreadUtils {
* @return 当前线程的名称字符串
*/
@JvmStatic
var name: String
var currentThreadName: String
get() = Thread.currentThread().name
set(s) {
Thread.currentThread().name = s
@@ -16,27 +16,19 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile DateTime.kt
* LastUpdate 2026-02-04 21:54:04
* LastUpdate 2026-03-07 11:02:42
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.time
import com.mingliqiye.utils.jna.FILETIME_EPOCH_OFFSET
import com.mingliqiye.utils.jna.NANOS_PER_100NS
import com.mingliqiye.utils.jna.WinKernel32Api
import com.mingliqiye.utils.jna.getWinKernel32Apis
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import com.mingliqiye.utils.system.isWindows
import com.mingliqiye.utils.system.javaVersionAsInteger
import org.slf4j.Logger
import io.swagger.v3.oas.annotations.media.Schema
import java.io.Serializable
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.util.*
import kotlin.time.ExperimentalTime
import kotlin.time.Instant
@@ -55,33 +47,17 @@ import kotlin.time.Instant
* @see ZoneId
* @see Instant
*/
@Schema(
name = "DateTime",
description = "DateTime",
type = "string",
format = "date-time"
)
class DateTime private constructor(
private var localDateTime: LocalDateTime, private val zoneId: ZoneId = ZoneId.systemDefault()
) : Serializable {
companion object {
private val WIN_KERNEL_32_API: WinKernel32Api? = if (javaVersionAsInteger == 8 && isWindows) {
val log: Logger = MingLiLoggerFactory.getLogger("mingli-utils DateTime")
val a = getWinKernel32Apis()
if (a.size > 1) {
log.warn("Multiple Size:{} WinKernel32Api implementations found.", a.size)
a.forEach { api ->
log.warn("Found WinKernel32Api: {}", api.javaClass.name)
}
}
if (a.isEmpty()) {
log.warn("No WinKernel32Api implementation found. Use Jdk1.8 LocalDateTime")
null
} else {
log.info("Found and Use WinKernel32Api: {}", a[a.size - 1].javaClass.name)
a[a.size - 1]
}
} else {
null
}
/**
* 获取当前时间的 DateTime 实例。
* 如果运行在 Java 1.8 环境下,则通过 WinKernel32 获取高精度时间。
@@ -90,11 +66,6 @@ class DateTime private constructor(
*/
@JvmStatic
fun now(): DateTime {
if (WIN_KERNEL_32_API != null) {
return DateTime(
WIN_KERNEL_32_API.getTime().atZone(ZoneId.systemDefault()).toLocalDateTime()
)
}
return DateTime(LocalDateTime.now())
}
@@ -266,27 +237,6 @@ class DateTime private constructor(
return DateTime(LocalDateTime.of(year, month, day, hour, minute))
}
/**
* 将 FILETIME 转换为 LocalDateTime。
*
* @param fileTime FILETIME 时间戳(100纳秒单位自1601年1月1日起)
* @return 转换后的 LocalDateTime 实例
*/
@OptIn(ExperimentalTime::class)
@JvmStatic
fun fileTimeToLocalDateTime(fileTime: Long): LocalDateTime {
// 1. 将 FILETIME (100ns间隔 since 1601) 转换为 Unix 时间戳 (纳秒 since 1970)
val unixNanos = (fileTime + FILETIME_EPOCH_OFFSET) * NANOS_PER_100NS
// 2. 从纳秒时间戳创建 Instant
val instant = java.time.Instant.ofEpochSecond(
unixNanos / 1_000_000_000L, unixNanos % 1_000_000_000L
)
// 3. 转换为系统默认时区的 LocalDateTime
return instant.atZone(ZoneId.systemDefault()).toLocalDateTime()
}
/**
* 根据年、月、日、时、分、秒创建 DateTime 实例
*
@@ -16,46 +16,120 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile DateTimeOffset.kt
* LastUpdate 2026-02-04 21:54:04
* LastUpdate 2026-02-27 11:04:05
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.time
import java.time.temporal.ChronoUnit
import java.util.concurrent.TimeUnit
/**
* 时间位移 类
* 表示一个时间偏移量的类,用于封装时间单位和偏移值。
*
* @author MingLiPro
* @property offsetType 时间单位类型,使用 [ChronoUnit] 表示。
* @property offset 偏移量的数值。
*/
class DateTimeOffset private constructor(
val offsetType: ChronoUnit, val offset: Long
val offsetType: ChronoUnit,
val offset: Long
) {
companion object {
/**
* 创建一个新的DateTimeOffset实例
* 将 [ChronoUnit] 扩展为创建 [DateTimeOffset] 实例的函数。
*
* @param offsetType 偏移量的单位类型,指定偏移量的计算单位
* @param offset 偏移量的数值,可以为正数、负数或零
* @return 返回一个新的DateTimeOffset对象,包含指定的偏移量信息
* @param offset 偏移量的长整型数值。
* @return 返回一个新的 [DateTimeOffset] 实例。
*/
@JvmStatic
fun of(offsetType: ChronoUnit, offset: Long): DateTimeOffset {
return DateTimeOffset(offsetType, offset)
}
@JvmName("of")
fun ChronoUnit.toDateTimeOffset(offset: Long) = DateTimeOffset(this, offset)
/**
* 创建一个 DateTimeOffset 实例
* 将 [ChronoUnit] 扩展为创建 [DateTimeOffset] 实例的函数。
*
* @param offset 偏移量数值
* @param offsetType 偏移量的时间单位类型
* @return 返回一个新的 DateTimeOffset 实例
* @param offset 偏移量的整型数值。
* @return 返回一个新的 [DateTimeOffset] 实例。
*/
@JvmStatic
fun of(offset: Long, offsetType: ChronoUnit): DateTimeOffset {
return DateTimeOffset(offsetType, offset)
@JvmName("of")
fun ChronoUnit.toDateTimeOffset(offset: Int) = DateTimeOffset(this, offset.toLong())
/**
* 将 [TimeUnit] 扩展为创建 [DateTimeOffset] 实例的函数。
*
* @param offset 偏移量的长整型数值。
* @return 返回一个新的 [DateTimeOffset] 实例。
*/
@JvmStatic
@JvmName("of")
fun TimeUnit.toDateTimeOffset(offset: Long) = DateTimeOffset(this.toChronoUnit(), offset)
/**
* 将 [TimeUnit] 扩展为创建 [DateTimeOffset] 实例的函数。
*
* @param offset 偏移量的整型数值。
* @return 返回一个新的 [DateTimeOffset] 实例。
*/
@JvmStatic
@JvmName("of")
fun TimeUnit.toDateTimeOffset(offset: Int) = DateTimeOffset(this.toChronoUnit(), offset.toLong())
/**
* 创建 [DateTimeOffset] 实例的静态工厂方法。
*
* @param offset 偏移量的长整型数值。
* @param offsetType 时间单位类型,使用 [ChronoUnit] 表示。
* @return 返回一个新的 [DateTimeOffset] 实例。
*/
@JvmStatic
fun of(offset: Long, offsetType: ChronoUnit) = offsetType.toDateTimeOffset(offset)
/**
* 创建 [DateTimeOffset] 实例的静态工厂方法。
*
* @param offset 偏移量的整型数值。
* @param offsetType 时间单位类型,使用 [ChronoUnit] 表示。
* @return 返回一个新的 [DateTimeOffset] 实例。
*/
@JvmStatic
fun of(offset: Int, offsetType: ChronoUnit) = offsetType.toDateTimeOffset(offset)
/**
* 创建 [DateTimeOffset] 实例的静态工厂方法。
*
* @param offset 偏移量的长整型数值。
* @param offsetType 时间单位类型,使用 [TimeUnit] 表示。
* @return 返回一个新的 [DateTimeOffset] 实例。
*/
@JvmStatic
fun of(offset: Long, offsetType: TimeUnit) = offsetType.toDateTimeOffset(offset)
/**
* 创建 [DateTimeOffset] 实例的静态工厂方法。
*
* @param offset 偏移量的整型数值。
* @param offsetType 时间单位类型,使用 [TimeUnit] 表示。
* @return 返回一个新的 [DateTimeOffset] 实例。
*/
@JvmStatic
fun of(offset: Int, offsetType: TimeUnit) = offsetType.toDateTimeOffset(offset)
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
@JvmStatic
@JvmName("TimeUnitToChronoUnit")
fun TimeUnit.toChronoUnit(): ChronoUnit {
return when (this) {
TimeUnit.NANOSECONDS -> ChronoUnit.NANOS
TimeUnit.MICROSECONDS -> ChronoUnit.MICROS
TimeUnit.MILLISECONDS -> ChronoUnit.MILLIS
TimeUnit.SECONDS -> ChronoUnit.SECONDS
TimeUnit.MINUTES -> ChronoUnit.MINUTES
TimeUnit.HOURS -> ChronoUnit.HOURS
TimeUnit.DAYS -> ChronoUnit.DAYS
}
}
}
}
@@ -16,30 +16,45 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile UUID.kt
* LastUpdate 2026-02-06 14:33:24
* LastUpdate 2026-03-07 11:02:29
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.uuid
import com.mingliqiye.utils.base.*
import com.mingliqiye.utils.io.IO.println
import com.mingliqiye.utils.array.copyTo
import com.mingliqiye.utils.base.BaseCodec
import com.mingliqiye.utils.base.BaseType
import com.mingliqiye.utils.base.code.Base256
import com.mingliqiye.utils.base.code.Base64
import com.mingliqiye.utils.base.code.Base91
import com.mingliqiye.utils.random.randomByte
import com.mingliqiye.utils.random.secureRandom
import com.mingliqiye.utils.system.macAddressBytes
import com.mingliqiye.utils.time.DateTime
import com.mingliqiye.utils.time.DateTimeOffset
import com.mingliqiye.utils.time.DateTimeOffset.Companion.toDateTimeOffset
import io.swagger.v3.oas.annotations.media.Schema
import java.io.Serializable
import java.math.BigInteger
import java.nio.ByteBuffer
import java.security.MessageDigest
import java.time.temporal.ChronoUnit
import java.util.concurrent.atomic.AtomicLong
import java.util.UUID as JUUID
/**
* UUID 类用于生成和操作不同版本的 UUID(通用唯一标识符)。
* 支持 UUID 的序列化、转换、解析和时间/版本信息提取。
* V8 请开发者自己实现
*/
@Schema(
name = "UUID",
description = "UUID",
type = "string",
format = "uuid"
)
class UUID : Serializable {
private val data: ByteArray
private val mostSigBits: Long
@@ -48,6 +63,11 @@ class UUID : Serializable {
companion object {
private var lastTimestamp = 0L
private var clockSequence = secureRandom.nextInt(0x3FFF + 1)
private val clockSeqHolder = AtomicLong(0)
/**
* 预期 UUID 字符串中连字符的位置数组。
*/
@@ -63,17 +83,35 @@ class UUID : Serializable {
@JvmStatic
fun ofBase64ShortString(baseShortString: String): UUID {
return UUID(BASE64.decode(baseShortString))
return UUID(Base64.decode(baseShortString))
}
@JvmStatic
fun ofBase256ShortString(baseShortString: String): UUID {
return UUID(BASE256.decode(baseShortString))
return UUID(Base256.decode(baseShortString))
}
@JvmStatic
fun ofBase91ShortString(baseShortString: String): UUID {
return UUID(BASE91.decode(baseShortString))
return UUID(Base91.decode(baseShortString))
}
@JvmStatic
fun getV8(
customA: ByteArray, // 6字节
customB: ByteArray, // 2字节 前4位被替换位版本号
customC: ByteArray, // 8字节, 前2位被替换位变体
): UUID {
require(customA.size == 6) { "customA 必须是6字节" }
require(customB.size == 2) { "customB 必须是2字节" }
require(customC.size == 8) { "customC 必须是8字节" }
val rbyte = ByteArray(16)
customA.copyTo(rbyte, 0, 0, 6)
customB.copyTo(rbyte, 0, 6, 2)
customC.copyTo(rbyte, 0, 8, 8)
rbyte[6] = (rbyte[6].toInt() and 0x0F or 0x80).toByte()
rbyte[8] = (rbyte[8].toInt() and 0x3F or 0x80).toByte()
return UUID(rbyte)
}
/**
@@ -85,18 +123,47 @@ class UUID : Serializable {
@JvmStatic
fun getV1(): UUID {
val time = DateTime.now().add(DateTimeOffset.of(UUID_EPOCH_OFFSET, ChronoUnit.DAYS)).to100NanoTime()
val timeLow = (time and 0xFFFFFFFFL).toInt()
val timeMid = ((time shr 32) and 0xFFFFL).toShort()
val timeHighAndVersion = (((time shr 48) and 0x0FFFL) or 0x1000L).toShort()
val clockSeq = (secureRandom.nextInt(16384)) and 0x3FFF
val clockSeq: Long = if (time == lastTimestamp) {
clockSeqHolder.addAndGet(1)
} else {
clockSeqHolder.set(0)
lastTimestamp = time
0
}
val byteBuffer = ByteBuffer.wrap(ByteArray(16))
byteBuffer.putInt(timeLow)
byteBuffer.putShort(timeMid)
byteBuffer.putShort(timeHighAndVersion)
byteBuffer.putShort((clockSeq and 0x3FFF).toShort())
byteBuffer.put(macAddressBytes)
return UUID(byteBuffer.array())
}
@JvmStatic
fun getV1RandomMac(): UUID {
val time = DateTime.now().add(DateTimeOffset.of(UUID_EPOCH_OFFSET, ChronoUnit.DAYS)).to100NanoTime()
val timeLow = (time and 0xFFFFFFFFL).toInt()
val timeMid = ((time shr 32) and 0xFFFFL).toShort()
val timeHighAndVersion = (((time shr 48) and 0x0FFFL) or 0x1000L).toShort()
val clockSeq: Long = if (time == lastTimestamp) {
clockSeqHolder.addAndGet(1)
} else {
clockSeqHolder.set(0)
lastTimestamp = time
0
}
lastTimestamp = time
val byteBuffer = ByteBuffer.wrap(ByteArray(16))
byteBuffer.putInt(timeLow)
byteBuffer.putShort(timeMid)
byteBuffer.putShort(timeHighAndVersion)
byteBuffer.putShort(clockSeq.toShort())
byteBuffer.put(macAddressBytes)
byteBuffer.putShort((clockSeq and 0x3FFF).toShort())
byteBuffer.put(randomByte(6))
return UUID(byteBuffer.array())
}
@@ -109,10 +176,8 @@ class UUID : Serializable {
@JvmStatic
fun getV4(): UUID {
val randomBytes = randomByte(16)
randomBytes[6] = (randomBytes[6].toInt() and 0x0F).toByte()
randomBytes[6] = (randomBytes[6].toInt() or 0x40).toByte()
randomBytes[8] = (randomBytes[8].toInt() and 0x3F).toByte()
randomBytes[8] = (randomBytes[8].toInt() or 0x80).toByte()
randomBytes[6] = (randomBytes[6].toInt() and 0x0F or 0x40).toByte()
randomBytes[8] = (randomBytes[8].toInt() and 0x3F or 0x80).toByte()
return UUID(randomBytes)
}
@@ -161,8 +226,7 @@ class UUID : Serializable {
*/
@JvmStatic
fun getV6(): UUID {
val timestamp = DateTime.now()
.add(DateTimeOffset.of(UUID_EPOCH_OFFSET, ChronoUnit.DAYS))
val timestamp = DateTime.now().add(DateTimeOffset.of(UUID_EPOCH_OFFSET, ChronoUnit.DAYS))
.to100NanoTime() and 0x0FFFFFFFFFFFFFFFL
val timeHigh = (timestamp ushr 12) and 0xFFFFFFFFFFFFL
val timeMid = timestamp and 0x0FFFL
@@ -278,8 +342,7 @@ class UUID : Serializable {
return UUID(
ByteArray(
16
) { 0xFF.toByte() }
)
) { 0xFF.toByte() })
}
/**
@@ -292,8 +355,7 @@ class UUID : Serializable {
return UUID(
ByteArray(
16
) { 0x00.toByte() }
)
) { 0x00.toByte() })
}
/**
@@ -574,8 +636,6 @@ class UUID : Serializable {
if (this === other) return true
return when (other) {
is UUID -> {
this.println()
other.println()
this.data.contentEquals(other.data)
}
@@ -645,40 +705,29 @@ class UUID : Serializable {
1 -> {
val timestamp =
((mostSigBits and 0x0FFFL) shl 48 or (((mostSigBits shr 16) and 0x0FFFFL) shl 32) or (mostSigBits ushr 32))
val timestampBigInt = java.math.BigInteger.valueOf(timestamp)
val nanosecondsBigInt = timestampBigInt.multiply(java.math.BigInteger.valueOf(100L))
val divisor = java.math.BigInteger.valueOf(1_000_000_000L)
val timestampBigInt = BigInteger.valueOf(timestamp)
val nanosecondsBigInt = timestampBigInt.multiply(BigInteger.valueOf(100L))
val divisor = BigInteger.valueOf(1_000_000_000L)
val seconds = nanosecondsBigInt.divide(divisor)
val nanos = nanosecondsBigInt.remainder(divisor)
return DateTime.of(seconds.toLong(), nanos.toLong())
.sub(DateTimeOffset.of(ChronoUnit.DAYS, UUID_EPOCH_OFFSET))
.sub(ChronoUnit.DAYS.toDateTimeOffset(UUID_EPOCH_OFFSET))
}
6 -> {
val timeHigh = (
((data[0].toLong() and 0xFF) shl 40) or
((data[1].toLong() and 0xFF) shl 32) or
((data[2].toLong() and 0xFF) shl 24) or
((data[3].toLong() and 0xFF) shl 16) or
((data[4].toLong() and 0xFF) shl 8) or
(data[5].toLong() and 0xFF)
)
val timeHigh =
(((data[0].toLong() and 0xFF) shl 40) or ((data[1].toLong() and 0xFF) shl 32) or ((data[2].toLong() and 0xFF) shl 24) or ((data[3].toLong() and 0xFF) shl 16) or ((data[4].toLong() and 0xFF) shl 8) or (data[5].toLong() and 0xFF))
val timeMidAndVersion = ((data[6].toInt() and 0xFF) shl 8) or (data[7].toInt() and 0xFF)
val timeMid = timeMidAndVersion and 0x0FFF
val hundredNanosSinceUuidEpoch = (timeHigh shl 12) or timeMid.toLong()
val seconds = hundredNanosSinceUuidEpoch / 10_000_000
val nanos = (hundredNanosSinceUuidEpoch % 10_000_000) * 100
return DateTime.of(seconds, nanos).sub(DateTimeOffset.of(ChronoUnit.DAYS, UUID_EPOCH_OFFSET))
return DateTime.of(seconds, nanos).sub(ChronoUnit.DAYS.toDateTimeOffset(UUID_EPOCH_OFFSET))
}
7 -> {
val times =
(data[0].toLong() and 0xFF shl 40) or
(data[1].toLong() and 0xFF shl 32) or
(data[2].toLong() and 0xFF shl 24) or
(data[3].toLong() and 0xFF shl 16) or
(data[4].toLong() and 0xFF shl 8) or
(data[5].toLong() and 0xFF)
(data[0].toLong() and 0xFF shl 40) or (data[1].toLong() and 0xFF shl 32) or (data[2].toLong() and 0xFF shl 24) or (data[3].toLong() and 0xFF shl 16) or (data[4].toLong() and 0xFF shl 8) or (data[5].toLong() and 0xFF)
return DateTime.of(times)
}
@@ -698,15 +747,15 @@ class UUID : Serializable {
}
fun getBase64ShortString(): String {
return BASE64.encode(data).substring(0, 22)
return Base64.encode(data).substring(0, 22)
}
fun getBase91ShortString(): String {
return BASE91.encode(data)
return Base91.encode(data)
}
fun getBase256ShortString(): String {
return BASE256.encode(data)
return Base256.encode(data)
}
/**
+7 -7
View File
@@ -1,7 +1,7 @@
com.mingliqiye.utils.springboot.autoconfigure.AutoConfiguration.buildTime=$buildTime
com.mingliqiye.utils.springboot.autoconfigure.AutoConfiguration.groupId=$GROUPSID
com.mingliqiye.utils.springboot.autoconfigure.AutoConfiguration.artifactId=$ARTIFACTID
com.mingliqiye.utils.springboot.autoconfigure.AutoConfiguration.version=$VERSIONS
com.mingliqiye.utils.springboot.autoconfigure.AutoConfiguration.buildJdkVersion=$JDKVERSIONS
com.mingliqiye.utils.springboot.autoconfigure.AutoConfiguration.author=MingLiPro
com.mingliqiye.utils.springboot.autoconfigure.AutoConfiguration.website=https://mingli-utils.mingliqiye.com
buildTime=$buildTime
groupId=$GROUPSID
artifactId=$ARTIFACTID
version=$VERSIONS
buildJdkVersion=$JDKVERSIONS
author=MingLiPro
website=https://mingli-utils.mingliqiye.com
@@ -16,9 +16,12 @@
# ProjectName mingli-utils
# ModuleName mingli-utils.main
# CurrentFile org.springframework.boot.autoconfigure.AutoConfiguration.imports
# LastUpdate 2026-02-04 16:47:27
# LastUpdate 2026-02-27 17:39:55
# UpdateUser MingLiPro
#
com.mingliqiye.utils.springboot.autoconfigure.AutoConfiguration
com.mingliqiye.utils.springboot.autoconfigure.JacksonAutoConfiguration
com.mingliqiye.utils.springboot.autoconfigure.Jackson3AutoConfiguration
com.mingliqiye.utils.springboot.autoconfigure.Jackson3JsonApiAutoConfiguration
com.mingliqiye.utils.springboot.autoconfigure.Okhttp3AutoConfiguration
@@ -1,42 +0,0 @@
{
"com.mingliqiye.utils": {
"i18n": {
"readjson": {
"error": "Failed to load language file %s"
}
},
"springboot.autoconfigure": {
"AutoConfiguration": {
"jdkRuntime": "JDK Runtime Environment Version",
"pid": "Process PID",
"computerName": "Computer Name",
"userName": "User Name",
"time": "Current Time",
"buildTime": "Build Time",
"groupId": "Group ID",
"artifactId": "Artifact ID",
"version": "Version",
"buildJdkVersion": "Build JDK Version",
"author": "Author",
"website": "Official Website",
"bean": "MingliUtils Auto Configuration Bean Success"
},
"JsonApiAutoConfiguration": {
"jsonause": "JSONA Using %s",
"jsonapiconfiged": "JsonApi Bean Auto Configuration Success",
"jacksonserializers": "MingliUtils Jackson Serializers created"
}
},
"string": {
"StringUtils": {
"format": {
"warn": {
"placeholder": "Placeholder Count: %s, Argument Count: %s",
"template": "Template: %s",
"arguments": "Arguments: [%s]"
}
}
}
}
}
}
@@ -1,42 +0,0 @@
{
"com.mingliqiye.utils": {
"i18n": {
"readjson": {
"error": "加载语言文件失败 %s"
}
},
"springboot.autoconfigure": {
"AutoConfiguration": {
"jdkRuntime": "Jdk运行环境版本",
"pid": "程序Pid",
"computerName": "计算机名",
"userName": "用户名",
"time": "当前时间",
"buildTime": "编译时间",
"groupId": "组Id",
"artifactId": "组件Id",
"version": "版本",
"buildJdkVersion": "编译Jdk版本",
"author": "作者",
"website": "官方网址",
"bean": "MingliUtils 自动配置 Bean 成功"
},
"JsonApiAutoConfiguration": {
"jsonause": "JSONA 使用 %s",
"jsonapiconfiged": "JsonApi Bean 自动配置成功",
"jacksonserializers": "MingliUtils Jackson 序列化器注册成功"
}
},
"string": {
"StringUtils": {
"format": {
"warn": {
"placeholder": "占位符数量: %s, 参数数量: %s",
"template": "模板: %s",
"arguments": "参数: [%s]"
}
}
}
}
}
}