This commit is contained in:
2026-06-21 10:41:28 +08:00
parent e00f8ad7a1
commit 60ec0e2883
38 changed files with 23987 additions and 614 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,276 @@
/*
* 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 ByteBufferWrapperConvertor.kt
* LastUpdate 2026-03-15 11:05:48
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.buffer.convertor
import com.mingliqiye.utils.buffer.ByteBufferWrapper
import com.mingliqiye.utils.bytes.ByteFlags
import com.mingliqiye.utils.time.DateTime
import com.mingliqiye.utils.uuid.UUID
import java.math.BigDecimal
import java.math.BigInteger
import java.time.LocalDateTime
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.UUID as JUUID
interface ByteBufferWrapperConvertorInterface<T : Any> {
fun write(obj: T, byteBufferWrapper: ByteBufferWrapper)
fun read(byteBufferWrapper: ByteBufferWrapper, parameters: Array<Any>): T
fun getType(): Class<T>
}
abstract class ByteBufferWrapperConvertor<T : Any> : ByteBufferWrapperConvertorInterface<T> {
override fun toString(): String {
return "ByteBufferWrapperConvertor(type=${getType()})"
}
companion object {
private val _instantiations =
ConcurrentHashMap<Class<ByteBufferWrapperConvertor<*>>, ByteBufferWrapperConvertor<*>>()
@JvmStatic
fun getInstantiation(clazz: Class<ByteBufferWrapperConvertor<*>>): ByteBufferWrapperConvertor<*> {
return _instantiations.getOrPut(clazz) {
clazz.getConstructor().newInstance()
}
}
@JvmStatic
@Suppress("UNCHECKED_CAST")
inline fun <reified T : ByteBufferWrapperConvertor<*>> getInstantiation(): ByteBufferWrapperConvertor<*> {
return getInstantiation(T::class.java as Class<ByteBufferWrapperConvertor<*>>)
}
fun defaultConvertorInstall() {
ByteBufferWrapper.addConvertor<BigDecimalBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<BigIntegerBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<BooleanBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<BytedBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<ByteFlagsBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<CharBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<DateBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<DateTimeFlagsBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<DoubleBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<FloatBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<IntBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<JUUIDBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<LocalDateTimeBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<LongBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<ShortBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<StringBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<UUIDBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<ByteArrayBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<CharArrayBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<ShortArrayBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<IntArrayBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<LongArrayBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<FloatArrayBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<DoubleArrayBufferWrapperConvertor>()
ByteBufferWrapper.addConvertor<BooleanArrayBufferWrapperConvertor>()
}
}
}
abstract class ObjectBufferWrapperConvertor<T : Any>(
val write: ByteBufferWrapper.(obj: T) -> Unit,
val read: ByteBufferWrapper.() -> T,
val typer: Class<T>,
) : ByteBufferWrapperConvertor<T>() {
override fun write(obj: T, byteBufferWrapper: ByteBufferWrapper) = write.invoke(byteBufferWrapper, obj)
override fun read(byteBufferWrapper: ByteBufferWrapper, parameters: Array<Any>): T =
read.invoke(byteBufferWrapper)
override fun getType(): Class<T> = typer
}
class BytedBufferWrapperConvertor : ObjectBufferWrapperConvertor<Byte>(
ByteBufferWrapper::putByte,
ByteBufferWrapper::getByte,
Byte::class.java,
)
class CharBufferWrapperConvertor : ObjectBufferWrapperConvertor<Char>(
ByteBufferWrapper::putChar,
ByteBufferWrapper::getChar,
Char::class.java,
)
class ShortBufferWrapperConvertor : ObjectBufferWrapperConvertor<Short>(
ByteBufferWrapper::putShort,
ByteBufferWrapper::getShort,
Short::class.java,
)
class IntBufferWrapperConvertor : ObjectBufferWrapperConvertor<Int>(
ByteBufferWrapper::putInt,
ByteBufferWrapper::getInt,
Int::class.java,
)
class LongBufferWrapperConvertor : ObjectBufferWrapperConvertor<Long>(
ByteBufferWrapper::putLong,
ByteBufferWrapper::getLong,
Long::class.java,
)
class DoubleBufferWrapperConvertor : ObjectBufferWrapperConvertor<Double>(
ByteBufferWrapper::putDouble,
ByteBufferWrapper::getDouble,
Double::class.java,
)
class FloatBufferWrapperConvertor : ObjectBufferWrapperConvertor<Float>(
ByteBufferWrapper::putFloat,
ByteBufferWrapper::getFloat,
Float::class.java,
)
class BigIntegerBufferWrapperConvertor : ObjectBufferWrapperConvertor<BigInteger>(
ByteBufferWrapper::putBigInteger,
ByteBufferWrapper::getBigInteger,
BigInteger::class.java,
)
class BigDecimalBufferWrapperConvertor : ObjectBufferWrapperConvertor<BigDecimal>(
ByteBufferWrapper::putBigDecimal,
ByteBufferWrapper::getBigDecimal,
BigDecimal::class.java,
)
class BooleanBufferWrapperConvertor : ObjectBufferWrapperConvertor<Boolean>(
ByteBufferWrapper::putBoolean,
ByteBufferWrapper::getBoolean,
Boolean::class.java,
)
class StringBufferWrapperConvertor : ObjectBufferWrapperConvertor<String>(
ByteBufferWrapper::putString,
ByteBufferWrapper::getString,
String::class.java,
)
class ByteFlagsBufferWrapperConvertor : ObjectBufferWrapperConvertor<ByteFlags>(
ByteBufferWrapper::putFlag,
ByteBufferWrapper::getFlag,
ByteFlags::class.java,
)
class JUUIDBufferWrapperConvertor : ObjectBufferWrapperConvertor<JUUID>(
ByteBufferWrapper::putUUID,
ByteBufferWrapper::getJUUID,
JUUID::class.java,
)
class UUIDBufferWrapperConvertor : ObjectBufferWrapperConvertor<UUID>(
ByteBufferWrapper::putUUID,
ByteBufferWrapper::getUUID,
UUID::class.java,
)
class DateTimeFlagsBufferWrapperConvertor : ObjectBufferWrapperConvertor<DateTime>(
ByteBufferWrapper::putDateTime,
ByteBufferWrapper::getDateTime,
DateTime::class.java,
)
class LocalDateTimeBufferWrapperConvertor : ObjectBufferWrapperConvertor<LocalDateTime>(
ByteBufferWrapper::putLocalDateTime,
ByteBufferWrapper::getLocalDateTime,
LocalDateTime::class.java,
)
class DateBufferWrapperConvertor : ObjectBufferWrapperConvertor<Date>(
ByteBufferWrapper::putDate,
ByteBufferWrapper::getDate,
Date::class.java,
)
abstract class ArrayBufferWrapperConvertor<T : Any>(
val write: ByteBufferWrapper.(obj: T) -> Unit,
val read: ByteBufferWrapper.(size: Int) -> T,
val typer: Class<T>,
) : ByteBufferWrapperConvertor<T>() {
override fun write(obj: T, byteBufferWrapper: ByteBufferWrapper) = write.invoke(byteBufferWrapper, obj)
override fun read(byteBufferWrapper: ByteBufferWrapper, parameters: Array<Any>): T {
if (parameters.isEmpty()) {
throw IllegalArgumentException("parameters cannot be empty, must has a Int")
}
val size = parameters[0]
if (size !is Int)
throw IllegalArgumentException("parameters[0] cannot be Int, must has a Int")
return read.invoke(byteBufferWrapper, size)
}
override fun getType(): Class<T> = typer
}
class ByteArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<ByteArray>(
ByteBufferWrapper::putByteArray,
ByteBufferWrapper::getByteArray,
ByteArray::class.java,
)
class CharArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<CharArray>(
ByteBufferWrapper::putCharArray,
ByteBufferWrapper::getCharArray,
CharArray::class.java,
)
class ShortArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<ShortArray>(
ByteBufferWrapper::putShortArray,
ByteBufferWrapper::getShortArray,
ShortArray::class.java,
)
class IntArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<IntArray>(
ByteBufferWrapper::putIntArray,
ByteBufferWrapper::getIntArray,
IntArray::class.java,
)
class LongArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<LongArray>(
ByteBufferWrapper::putLongArray,
ByteBufferWrapper::getLongArray,
LongArray::class.java,
)
class FloatArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<FloatArray>(
ByteBufferWrapper::putFloatArray,
ByteBufferWrapper::getFloatArray,
FloatArray::class.java,
)
class DoubleArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<DoubleArray>(
ByteBufferWrapper::putDoubleArray,
ByteBufferWrapper::getDoubleArray,
DoubleArray::class.java,
)
class BooleanArrayBufferWrapperConvertor : ArrayBufferWrapperConvertor<BooleanArray>(
ByteBufferWrapper::putBooleanArray,
ByteBufferWrapper::getBooleanArray,
BooleanArray::class.java,
)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ByteFlags.kt
* LastUpdate 2026-01-07 09:37:09
* LastUpdate 2026-06-21 10:40:58
* UpdateUser MingLiPro
*/
@@ -47,7 +47,7 @@ data class ByteFlags(
/** 第 6 位(0x40) */
var b6: Boolean = false,
/** 第 7 位(最高位,0x80) */
var b7: Boolean = false
var b7: Boolean = false,
) {
/**
@@ -410,7 +410,7 @@ data class ByteFlags(
* @return 全 1 的 ByteFlags(值为 0xFF)
*/
fun allTrue(): ByteFlags {
return ByteFlags(true, true, true, true, true, true, true, true)
return ByteFlags(b0 = true, b1 = true, b2 = true, b3 = true, b4 = true, b5 = true, b6 = true, b7 = true)
}
/**
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ByteUtils.kt
* LastUpdate 2026-03-12 10:09:05
* LastUpdate 2026-05-22 13:26:55
* UpdateUser MingLiPro
*/
@file:JvmName("ByteUtils")
@@ -88,7 +88,7 @@ const val ESC_RESERVED: Byte = 0x06
*/
fun ByteArray.getByteArrayString(): MutableList<String> {
return this.toList().stream().map { a -> String.format("0X%02X", a!!.toInt() and 0xFF) }
.collect(SuperStream.toList()) as MutableList<String>
.collect(SuperStream.toListCollector()) as MutableList<String>
}
@@ -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 NotFoundResourceException.kt
* LastUpdate 2026-05-22 13:20:00
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.exception
class NotFoundResourceException : 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,12 +16,13 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Debouncer.kt
* LastUpdate 2026-01-11 09:10:30
* LastUpdate 2026-05-23 10:30:38
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.functions
import com.mingliqiye.utils.netty.NamedThreadFactory
import java.util.concurrent.*
/**
@@ -31,7 +32,11 @@ import java.util.concurrent.*
*/
class Debouncer(private val delay: Long, unit: TimeUnit) {
private val scheduler: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor()
private val scheduler: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor(
NamedThreadFactory { clazz, poolNumber, threadNumber ->
"Debouncer-$poolNumber-$threadNumber"
}
)
private val delayedMap: ConcurrentHashMap<Any, Future<*>> = ConcurrentHashMap()
private val delayMillis: Long = unit.toMillis(delay)
@@ -60,9 +65,7 @@ class Debouncer(private val delay: Long, unit: TimeUnit) {
)
// 如果之前存在任务,则取消它
if (prev != null) {
prev.cancel(true)
}
prev?.cancel(true)
}
/**
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Response.kt
* LastUpdate 2026-03-12 10:33:32
* LastUpdate 2026-03-14 08:01:32
* UpdateUser MingLiPro
*/
@@ -49,10 +49,19 @@ data class Response<T>(
* 创建一个默认的成功响应对象
* 使用默认消息"操作成功",无数据,状态码200
*
* @return Response<Any> 默认的成功响应对象
* @return Response<Nothing> 默认的成功响应对象
*/
fun ok() = ok("操作成功")
/**
* 创建一个默认的错误响应对象
* 使用默认消息"服务器错误",无数据,状态码500
*
* @return Response<Nothing> 默认的成功响应对象
*/
fun error() = error("服务器错误")
/**
* 创建一个成功的响应对象(仅包含消息)
*
@@ -292,5 +301,5 @@ data class Response<T>(
* @return 格式化的字符串表示
*/
override fun toString(): String =
"Response(time=${getTime()}, message=${getMessage()}, data:[${data?.javaClass?.simpleName}]=${getData()}, statusCode=${getStatusCode()})"
"Response<${data?.javaClass?.simpleName ?: "Nothing"}>(time=${getTime()}, message=${getMessage()}, data=${getData()}, statusCode=${getStatusCode()})"
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile SIO.kt
* LastUpdate 2026-02-27 12:36:11
* LastUpdate 2026-06-21 10:40:58
* UpdateUser MingLiPro
*/
@@ -106,6 +106,14 @@ object SIO {
return this
}
fun <T> T.ifOr(boolean: Boolean, pd: T.() -> T): T = if (boolean) {
this
} else pd(this)
fun <T> T.ifOrElse(boolean: Boolean, pd: T.() -> T): T = if (!boolean) {
this
} else pd(this)
/**
* 扩展函数:将列表以花括号格式打印,元素间用逗号分隔
* @return 原始列表
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JSONA.kt
* LastUpdate 2026-02-26 14:14:18
* LastUpdate 2026-03-18 09:14:06
* UpdateUser MingLiPro
*/
@@ -29,10 +29,13 @@ 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 com.mingliqiye.utils.json.objects.base.JsonItem
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.nio.file.Path
import kotlin.io.path.readBytes
/**
* JSON工具类,提供静态方法访问JSON API功能
@@ -263,7 +266,7 @@ object JSONA {
*/
@JvmStatic
fun <T> parse(
json: String, type: JsonTypeReference<T>, defaultValue: T
json: String, type: JsonTypeReference<T>, defaultValue: T,
): T = getJsonApi().parse(json, type, defaultValue)
/**
@@ -401,7 +404,7 @@ object JSONA {
*/
@JvmStatic
fun <K, V> parseMap(
json: String, keyType: Class<K>, valueType: Class<V>
json: String, keyType: Class<K>, valueType: Class<V>,
): MutableMap<K, V> = getJsonApi().parseMap(json, keyType, valueType)
/**
@@ -414,7 +417,7 @@ object JSONA {
*/
@JvmStatic
inline fun <reified K, reified V> parseMap(
json: String
json: String,
): MutableMap<K, V> = getJsonApi().parseMap(json, K::class.java, V::class.java)
/**
@@ -429,7 +432,6 @@ object JSONA {
/**
* 将对象转换为JSON字节数组
*
* @param object 待转换的对象
* @return 转换后的JSON字节数组
*/
@JvmStatic
@@ -438,7 +440,6 @@ object JSONA {
/**
* 将对象转换为美化格式的JSON字节数组
*
* @param object 待转换的对象
* @return 转换后的美化格式JSON字节数组
*/
@JvmStatic
@@ -478,7 +479,6 @@ object JSONA {
/**
* 将源对象转换为目标类型的对象
*
* @param T 源对象的类型
* @param D 目标对象的类型
* @param source 需要转换的源对象
* @param destinationClass 目标对象的Class类型
@@ -490,7 +490,6 @@ object JSONA {
/**
* 使用内联函数和reified类型参数将源对象转换为目标类型的对象
*
* @param T 源对象的类型
* @param D 目标对象的类型(通过reified类型参数推断)
* @param source 需要转换的源对象
* @return 转换后的目标类型对象
@@ -501,7 +500,6 @@ object JSONA {
/**
* 将源对象转换为目标类型的对象,使用JsonTypeReference指定目标类型
*
* @param T 源对象的类型
* @param D 目标对象的类型
* @param source 需要转换的源对象
* @param destinationType 目标对象的JsonTypeReference类型引用
@@ -540,4 +538,86 @@ object JSONA {
@JvmStatic
fun ObjectMapper.jacksonKotlinObjectMapper(): ObjectMapper = this.registerModule(kotlinModule())
/**
* 将 JSON 字符串解析为 JsonItem 对象
*
* @param json JSON 格式的字符串
* @return 解析后的 JsonItem 对象,可以是 JsonObject、JsonArray 或 JsonValue
*/
@JvmStatic
fun parseJsonItem(json: String): JsonItem = getJsonApi().parseJsonItem(json)
/**
* 将字节数组解析为 JsonItem 对象
* 字节数组会被转换为字符串后再解析
*
* @param byte JSON 格式的字节数组(通常是 UTF-8 编码)
* @return 解析后的 JsonItem 对象
*/
@JvmStatic
fun parseJsonItem(byte: ByteArray): JsonItem {
return parseJsonItem(String(byte))
}
/**
* 将输入流解析为 JsonItem 对象
* 会自动关闭输入流
*
* @param inputStream JSON 数据的输入流
* @return 解析后的 JsonItem 对象
* @throws IOException 当读取输入流失败时抛出
*
* 使用示例:
* ```
* val inputStream = FileInputStream("data.json")
* val jsonItem = converter.parseJsonItem(inputStream)
* ```
*/
@JvmStatic
@Throws(IOException::class)
fun parseJsonItem(inputStream: InputStream): JsonItem {
inputStream.use {
return parseJsonItem(it.readAllBytes())
}
}
/**
* 将文件解析为 JsonItem 对象
*
* @param file 包含 JSON 数据的文件
* @return 解析后的 JsonItem 对象
* @throws IOException 当读取文件失败时抛出
*
* 使用示例:
* ```
* val file = File("config.json")
* val jsonItem = converter.parseJsonItem(file)
* ```
*/
@JvmStatic
@Throws(IOException::class)
fun parseJsonItem(file: File): JsonItem {
return parseJsonItem(file.readBytes())
}
/**
* 将文件路径解析为 JsonItem 对象
*
* @param path 包含 JSON 数据的文件路径
* @return 解析后的 JsonItem 对象
* @throws IOException 当读取文件失败时抛出
*
* 使用示例:
* ```
* val path = Paths.get("data/user.json")
* val jsonItem = converter.parseJsonItem(path)
* ```
*/
@JvmStatic
@Throws(IOException::class)
fun parseJsonItem(path: Path): JsonItem {
return parseJsonItem(path.readBytes())
}
}
@@ -16,27 +16,30 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Jackson3JsonApi.kt
* LastUpdate 2026-03-11 08:46:40
* LastUpdate 2026-06-21 10:40:58
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json
package com.mingliqiye.utils.json.api
import com.mingliqiye.utils.exception.JsonException
import com.mingliqiye.utils.json.api.JackSon3JsonItem.Companion.getJsonItem
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 com.mingliqiye.utils.json.objects.base.*
import tools.jackson.core.type.TypeReference
import tools.jackson.databind.JsonNode
import tools.jackson.databind.ObjectMapper
import tools.jackson.databind.node.JsonNodeType
import tools.jackson.databind.node.ObjectNode
import java.lang.reflect.Type
class Jackson3JsonApi : JsonApi {
var get: () -> ObjectMapper
var set: (ObjectMapper) -> Unit
var get: () -> ObjectMapper = { _prObjectMapper!! }
var set: (ObjectMapper) -> Unit = { _prObjectMapper = it }
private var _prObjectMapper: ObjectMapper? = null
@@ -47,8 +50,6 @@ class Jackson3JsonApi : JsonApi {
constructor(objectMapper: ObjectMapper) {
_prObjectMapper = objectMapper
get = { _prObjectMapper!! }
set = { _prObjectMapper = it }
}
constructor(
@@ -59,6 +60,10 @@ class Jackson3JsonApi : JsonApi {
this.set = set
}
constructor() {
_prObjectMapper = ObjectMapper()
}
override fun <T> parse(json: String, clazz: Class<T>): T {
try {
return objectMapper.readValue(json, clazz)
@@ -97,7 +102,7 @@ class Jackson3JsonApi : JsonApi {
return try {
objectMapper.readTree(json)
true
} catch (e: Exception) {
} catch (_: Exception) {
false
}
}
@@ -214,4 +219,80 @@ class Jackson3JsonApi : JsonApi {
mapperBuilder.addModule(c.getJackson3Module())
this.objectMapper = mapperBuilder.build()
}
override fun parseJsonItem(json: String): JsonItem {
try {
return getJsonItem(objectMapper.readTree(json))
} catch (e: Exception) {
throw JsonException("Failed to parseJsonItem", e)
}
}
}
class JackSon3JsonItem : JsonItem {
companion object {
fun getJsonItem(node: JsonNode): JsonItem {
return when (node.nodeType) {
JsonNodeType.OBJECT -> JackSon3JsonObject(node)
JsonNodeType.ARRAY -> JackSon3JsonArray(node)
JsonNodeType.BOOLEAN -> JackSon3JsonBoolean(node)
JsonNodeType.NULL -> JsonNull()
JsonNodeType.NUMBER -> JackSon3JsonNumber(node)
JsonNodeType.STRING -> JackSon3JsonString(node)
else -> throw IllegalStateException("unknown type ${node.nodeType}")
}
}
}
}
class JackSon3JsonNumber(node: JsonNode) : JsonNumber(node.asString())
class JackSon3JsonBoolean(node: JsonNode) : JsonBoolean(node.asBoolean())
class JackSon3JsonString(node: JsonNode) : JsonString(node.asString())
class JackSon3JsonArray(val node: JsonNode) : JsonArray() {
override fun getIndex(index: Int): JsonItem {
return JackSon3JsonItem.getJsonItem(node.get(index))
}
override fun iteratorArray(): Iterator<IndexedValue<JsonItem>> {
val iteet = node.iterator().withIndex()
return object : Iterator<IndexedValue<JsonItem>> {
override fun next(): IndexedValue<JsonItem> {
val it = iteet.next()
return IndexedValue(it.index, JackSon3JsonItem.getJsonItem(it.value))
}
override fun hasNext(): Boolean {
return iteet.hasNext()
}
}
}
}
class JackSon3JsonObject(val node: JsonNode) : JsonObject() {
override fun getField(name: String): JsonItem {
return JackSon3JsonItem.getJsonItem(node.get(name))
}
override fun iteratorObject(): Iterator<Map.Entry<String, JsonItem>> {
return object : Iterator<Map.Entry<String, JsonItem>> {
val it = node.properties().iterator()
override fun next(): Map.Entry<String, JsonItem> {
val utem = it.next()
return object : Map.Entry<String, JsonItem> {
override val key: String
get() = utem.key
override val value: JsonItem
get() = JackSon3JsonItem.getJsonItem(utem.value)
}
}
override fun hasNext(): Boolean {
return it.hasNext()
}
}
}
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JacksonJsonApi.kt
* LastUpdate 2026-03-11 08:46:40
* LastUpdate 2026-06-21 10:40:58
* UpdateUser MingLiPro
*/
@@ -27,12 +27,15 @@ import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.ObjectReader
import com.fasterxml.jackson.databind.node.JsonNodeType
import com.fasterxml.jackson.databind.node.ObjectNode
import com.mingliqiye.utils.exception.JsonException
import com.mingliqiye.utils.json.api.JackSonJsonItem.Companion.getJsonItem
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
import com.mingliqiye.utils.json.objects.base.*
/**
* 基于Jackson的JSON处理实现类,提供JSON字符串解析、格式化、合并、节点操作等功能。
@@ -97,7 +100,6 @@ class JacksonJsonApi : JsonApi {
/**
* 将对象格式化为JSON字符串
*
* @param `object` 待格式化的对象
* @return 格式化后的JSON字符串
* @throws JsonException 当格式化失败时抛出异常
*/
@@ -122,7 +124,6 @@ class JacksonJsonApi : JsonApi {
/**
* 将对象格式化为美化(带缩进)的JSON字符串
*
* @param `object` 待格式化的对象
* @return 美化后的JSON字符串
* @throws JsonException 当格式化失败时抛出异常
*/
@@ -158,7 +159,7 @@ class JacksonJsonApi : JsonApi {
return try {
objectMapper.readTree(json)
true
} catch (e: Exception) {
} catch (_: Exception) {
false
}
}
@@ -178,7 +179,7 @@ class JacksonJsonApi : JsonApi {
if (node.isObject) {
result.setAll<JsonNode>(node as ObjectNode)
}
} catch (e: Exception) {
} catch (_: Exception) {
}
}
return try {
@@ -293,4 +294,79 @@ class JacksonJsonApi : JsonApi {
throw JsonException("Failed to update node value", e)
}
}
override fun parseJsonItem(json: String): JsonItem {
try {
return getJsonItem(objectMapper.readTree(json))
} catch (e: Exception) {
throw JsonException("Failed to parseJsonItem", e)
}
}
}
class JackSonJsonItem : JsonItem {
companion object {
fun getJsonItem(node: JsonNode): JsonItem {
return when (node.nodeType) {
JsonNodeType.OBJECT -> JackSonJsonObject(node)
JsonNodeType.ARRAY -> JackSonJsonArray(node)
JsonNodeType.BOOLEAN -> JackSonJsonBoolean(node)
JsonNodeType.NULL -> JsonNull()
JsonNodeType.NUMBER -> JackSonJsonNumber(node)
JsonNodeType.STRING -> JackSonJsonString(node)
else -> throw IllegalStateException("unknown type ${node.nodeType}")
}
}
}
}
class JackSonJsonNumber(node: JsonNode) : JsonNumber(node.asText())
class JackSonJsonBoolean(node: JsonNode) : JsonBoolean(node.asBoolean())
class JackSonJsonString(node: JsonNode) : JsonString(node.asText())
class JackSonJsonArray(val node: JsonNode) : JsonArray() {
override fun getIndex(index: Int): JsonItem {
return getJsonItem(node.get(index))
}
override fun iteratorArray(): Iterator<IndexedValue<JsonItem>> {
val iteet = node.iterator().withIndex()
return object : Iterator<IndexedValue<JsonItem>> {
override fun next(): IndexedValue<JsonItem> {
val it = iteet.next()
return IndexedValue(it.index, getJsonItem(it.value))
}
override fun hasNext(): Boolean {
return iteet.hasNext()
}
}
}
}
class JackSonJsonObject(val node: JsonNode) : JsonObject() {
override fun getField(name: String): JsonItem {
return getJsonItem(node.get(name))
}
override fun iteratorObject(): Iterator<Map.Entry<String, JsonItem>> {
return object : Iterator<Map.Entry<String, JsonItem>> {
val it = node.properties().iterator()
override fun next(): Map.Entry<String, JsonItem> {
val utem = it.next()
return object : Map.Entry<String, JsonItem> {
override val key: String
get() = utem.key
override val value: JsonItem
get() = getJsonItem(utem.value)
}
}
override fun hasNext(): Boolean {
return it.hasNext()
}
}
}
}
@@ -16,20 +16,24 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile JsonApi.kt
* LastUpdate 2026-03-11 08:46:40
* LastUpdate 2026-03-27 14:19:31
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.api.base
import com.mingliqiye.utils.exception.JsonParserException
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 com.mingliqiye.utils.json.objects.base.JsonItem
import okio.IOException
import java.io.*
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.io.path.readBytes
/**
* JSON处理接口,提供JSON字符串与Java对象之间的相互转换功能
@@ -46,6 +50,7 @@ interface JsonApi {
*/
inline fun <reified T> JsonApi.parse(json: String): T = parse(json, object : JsonTypeReference<T>() {})
/**
* 将JSON字节数组解析为指定泛型类型对象
*
@@ -248,6 +253,7 @@ interface JsonApi {
return parseFrom(path.toFile(), type)
}
/**
* 从文件读取JSON并解析为指定泛型类型对象
*
@@ -478,9 +484,123 @@ interface JsonApi {
*/
fun updateNodeValue(json: String, path: String, newValue: Any): String
/**
* 将任意对象转换为指定类型的对象
*
* @param source 源对象,可以是 JSON 字符串、JsonItem 或其他对象
* @param destinationClass 目标类型的 Class 对象
* @return 转换后的目标类型对象
*
* @param <D> 目标类型泛型参数
*/
fun <D> convert(source: Any, destinationClass: Class<D>): D
/**
* 将任意对象转换为指定泛型类型的对象
* 用于处理带泛型的复杂类型,如 List<User>、Map<String, User> 等
*
* @param source 源对象,可以是 JSON 字符串、JsonItem 或其他对象
* @param destinationType 目标类型的类型引用,包含泛型信息
* @return 转换后的目标类型对象
*
* @param <D> 目标类型泛型参数
*
* 使用示例:
* ```
* val typeRef = object : JsonTypeReference<List<User>>() {}
* val userList = converter.convert(jsonString, typeRef)
* ```
*/
fun <D> convert(source: Any, destinationType: JsonTypeReference<D>): D
/**
* 注册自定义的 JSON 转换器
* 用于处理特定类型的自定义序列化和反序列化逻辑
*
* @param c 自定义的 JSON 转换器实例
*
* 使用示例:
* ```
* converter.addJsonConverter(DateJsonConverter())
* converter.addJsonConverter(LocalDateTimeJsonConverter())
* ```
*/
fun addJsonConverter(c: BaseJsonConverter<*, *>)
/**
* 将 JSON 字符串解析为 JsonItem 对象
*
* @param json JSON 格式的字符串
* @return 解析后的 JsonItem 对象,可以是 JsonObject、JsonArray 或 JsonValue
* @throws JsonParserException 当 JSON 格式错误时抛出
*/
fun parseJsonItem(json: String): JsonItem
/**
* 将字节数组解析为 JsonItem 对象
* 字节数组会被转换为字符串后再解析
*
* @param byte JSON 格式的字节数组(通常是 UTF-8 编码)
* @return 解析后的 JsonItem 对象
* @throws JsonParserException 当 JSON 格式错误时抛出
*/
fun parseJsonItem(byte: ByteArray): JsonItem {
return parseJsonItem(String(byte))
}
/**
* 将输入流解析为 JsonItem 对象
* 会自动关闭输入流
*
* @param inputStream JSON 数据的输入流
* @return 解析后的 JsonItem 对象
* @throws JsonParserException 当 JSON 格式错误时抛出
* @throws IOException 当读取输入流失败时抛出
*
* 使用示例:
* ```
* val inputStream = FileInputStream("data.json")
* val jsonItem = converter.parseJsonItem(inputStream)
* ```
*/
fun parseJsonItem(inputStream: InputStream): JsonItem {
inputStream.use {
return parseJsonItem(it.readAllBytes())
}
}
/**
* 将文件解析为 JsonItem 对象
*
* @param file 包含 JSON 数据的文件
* @return 解析后的 JsonItem 对象
* @throws IOException 当读取文件失败时抛出
*
* 使用示例:
* ```
* val file = File("config.json")
* val jsonItem = converter.parseJsonItem(file)
* ```
*/
@Throws(IOException::class)
fun parseJsonItem(file: File): JsonItem {
return parseJsonItem(file.readBytes())
}
/**
* 将文件路径解析为 JsonItem 对象
*
* @param path 包含 JSON 数据的文件路径
* @return 解析后的 JsonItem 对象
* @throws IOException 当读取文件失败时抛出
*
* 使用示例:
* ```
* val path = Paths.get("data/user.json")
* val jsonItem = converter.parseJsonItem(path)
* ```
*/
fun parseJsonItem(path: Path): JsonItem {
return parseJsonItem(path.readBytes())
}
}
@@ -0,0 +1,279 @@
/*
* 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 JsonObject.kt
* LastUpdate 2026-06-21 10:40:58
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.json.objects.base
import java.math.BigDecimal
import java.math.BigInteger
import java.util.*
/**
* JSON 元素接口,定义所有 JSON 数据类型的通用操作
*/
interface JsonItem {
/**
* 作为 JSON 对象返回
* @throws IllegalStateException 如果不是对象类型
*/
fun asObject(): JsonObject {
throw IllegalStateException("Current JSON element is ${name()} not a Object")
}
/**
* 作为 JSON 数组返回
* @throws IllegalStateException 如果不是数组类型
*/
fun asArray(): JsonArray {
throw IllegalStateException("Current JSON element is ${name()} not a Array")
}
/**
* 作为字符串返回
* @throws IllegalStateException 如果不是字符串类型
*/
fun asString(): String {
throw IllegalStateException("Current JSON element is ${name()} not a String")
}
/**
* 作为布尔值返回
* @throws IllegalStateException 如果不是布尔类型
*/
fun asBoolean(): Boolean {
throw IllegalStateException("Current JSON element is ${name()} not a Boolean")
}
/**
* 作为数字返回
* @throws IllegalStateException 如果不是数字类型
*/
fun asNumber(): JsonNumber {
throw IllegalStateException("Current JSON element is ${name()} not a Number")
}
/**
* 转换为 List 集合
* @throws IllegalStateException 如果不是数组类型
*/
fun toList(): List<JsonItem> {
val it = asArray().iteratorArray()
val list = LinkedList<JsonItem>()
it.forEach { item -> list.add(item.value) }
return list
}
/**
* 转换为 Map 集合
* @throws IllegalStateException 如果不是对象类型
*/
fun toMap(): Map<String, JsonItem> {
val it = asObject().iteratorObject()
val map = LinkedHashMap<String, JsonItem>()
it.forEach { item -> map[item.key] = item.value }
return map
}
/** 是否为 null */
fun isNull(): Boolean = false
/** 是否为布尔值 */
fun isBoolean(): Boolean = false
/** 是否为数字 */
fun isNumber(): Boolean = false
/** 是否为字符串 */
fun isString(): Boolean = false
/** 是否为对象 */
fun isObject(): Boolean = false
/** 是否为数组 */
fun isArray(): Boolean = false
/** 返回当前元素的类型名称 */
fun name(): String = "Any"
/** 根据索引获取元素(数组专用) */
fun get(index: Int): JsonItem = getIndex(index)
/** 根据字段名获取元素(对象专用) */
fun get(fieldName: String): JsonItem = getField(fieldName)
/**
* 根据索引获取元素
* @throws IllegalStateException 如果不是数组类型
*/
fun getIndex(index: Int): JsonItem {
throw IllegalStateException("Current JSON element is ${name()} not a Array")
}
/**
* 根据字段名获取元素
* @throws IllegalStateException 如果不是对象类型
*/
fun getField(name: String): JsonItem {
throw IllegalStateException("Current JSON element is ${name()} not a Object")
}
/**
* 遍历数组元素
* @param consumer 接收索引和元素的消费者函数
*/
fun forEachArray(consumer: (Int, JsonItem) -> Unit) {
iteratorArray().forEach {
consumer(it.index, it.value)
}
}
/**
* 遍历对象字段
* @param consumer 接收字段名和值的消费者函数
*/
fun forEachObject(consumer: (String, JsonItem) -> Unit) {
iteratorObject().forEach {
consumer(it.key, it.value)
}
}
/**
* 获取数组迭代器
* @throws IllegalStateException 如果不是数组类型
*/
fun iteratorArray(): Iterator<IndexedValue<JsonItem>> {
throw IllegalStateException("Current JSON element is ${name()} not a Array")
}
/**
* 获取对象迭代器
* @throws IllegalStateException 如果不是对象类型
*/
fun iteratorObject(): Iterator<Map.Entry<String, JsonItem>> {
throw IllegalStateException("Current JSON element is ${name()} not a Object")
}
}
/**
* JSON 对象抽象类
* 表示键值对形式的 JSON 对象 {}
*/
abstract class JsonObject : JsonItem {
override fun isObject(): Boolean = true
override fun name(): String = "object"
override fun asObject(): JsonObject = this
override fun toString(): String = StringBuilder().apply {
append("{")
iteratorObject().forEach {
append(it.key)
append("=")
append(it.value)
append(",")
}
deleteCharAt(length - 1)
append("}")
}.toString()
}
/**
* JSON 数组抽象类
* 表示有序的 JSON 数组 []
*/
abstract class JsonArray : JsonItem {
override fun isArray(): Boolean = true
override fun name(): String = "array"
override fun asArray() = this
override fun toString(): String = StringBuilder().apply {
append("[")
iteratorArray().forEach {
append(it.value)
append(",")
}
deleteCharAt(length - 1)
append("]")
}.toString()
}
/**
* JSON null 类型
* 表示 JSON 中的 null 值
*/
open class JsonNull : JsonItem {
override fun isNull(): Boolean = true
override fun name(): String = "null"
override fun toString(): String = "null"
}
/**
* JSON 数字类型
* 表示 JSON 中的数字,继承自 Number 以便转换为各种数值类型
* @param numberString 数字的字符串表示形式
*/
open class JsonNumber(val numberString: String) : JsonItem, Number() {
override fun isNumber(): Boolean = true
override fun name(): String = "number"
override fun asNumber(): JsonNumber = this
override fun toDouble(): Double = numberString.toDouble()
override fun toFloat(): Float = numberString.toFloat()
override fun toLong(): Long = numberString.toLong()
override fun toInt(): Int = numberString.toInt()
override fun toShort(): Short = numberString.toShort()
override fun toByte(): Byte = numberString.toByte()
/** 转换为 BigDecimal */
open fun toBigDecimal(): BigDecimal = numberString.toBigDecimal()
/** 转换为指定精度的 BigDecimal */
open fun toBigDecimal(scale: Int): BigDecimal = numberString.toBigDecimal().setScale(scale)
/** 转换为 BigInteger */
open fun toBigInteger(): BigInteger = numberString.toBigInteger()
override fun toString(): String = numberString
}
/**
* JSON 字符串类型
* @param value 字符串值
*/
open class JsonString(val value: String) : JsonItem {
override fun isString(): Boolean = true
override fun name(): String = "string"
override fun asString(): String {
return value
}
override fun toString(): String = value
}
/**
* JSON 布尔类型
* @param value 布尔值
*/
open class JsonBoolean(val value: Boolean) : JsonItem {
override fun isBoolean(): Boolean = true
override fun name(): String = "boolean"
override fun asBoolean(): Boolean {
return value
}
override fun toString(): String = value.toString()
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile MathUtils.kt
* LastUpdate 2026-02-05 10:25:32
* LastUpdate 2026-06-21 10:40:58
* UpdateUser MingLiPro
*/
@file:JvmName("MathUtils")
@@ -167,7 +167,7 @@ operator fun BigDecimal.div(value: BigDecimal): BigDecimal = this.divide(value)
* @return 除法运算结果
*/
operator fun BigDecimal.div(
value: Long
value: Long,
): BigDecimal = this.divide(BigDecimal(value))
/**
@@ -176,7 +176,7 @@ operator fun BigDecimal.div(
* @return 除法运算结果
*/
operator fun BigDecimal.div(
value: Int
value: Int,
): BigDecimal = this.divide(BigDecimal(value))
/**
@@ -185,7 +185,7 @@ operator fun BigDecimal.div(
* @return 除法运算结果
*/
operator fun BigDecimal.div(
value: Double
value: Double,
): BigDecimal = this.divide(BigDecimal(value.toString()))
/**
@@ -194,7 +194,7 @@ operator fun BigDecimal.div(
* @return 除法运算结果
*/
operator fun BigDecimal.div(
value: Float
value: Float,
): BigDecimal = this.divide(BigDecimal(value.toString()))
/**
@@ -203,7 +203,7 @@ operator fun BigDecimal.div(
* @return 除法运算结果
*/
operator fun BigDecimal.div(
value: BigInteger
value: BigInteger,
): BigDecimal = this.divide(BigDecimal(value))
/**
@@ -372,3 +372,63 @@ fun Number.toBigInteger(): BigInteger = BigInteger(this.toString())
* @return 返回与当前 Number 对象等值且具有指定精度的 BigDecimal 实例。
*/
fun Number.toBigDecimal(scale: Int): BigDecimal = BigDecimal(this.toString()).setScale(scale)
/**
* Number 与 BigDecimal 的加法运算符重载
*
* 允许任意数字类型(Int、Long、Double等)直接与 BigDecimal 进行加法运算
* 例如:val result = 100 + BigDecimal("10.5")
*
* @param value 要相加的 BigDecimal 值
* @return 相加后的 BigDecimal 结果
*
* 注意:通过 toString() 转换可能会丢失精度(如 Double 的精度问题)
*/
operator fun Number.plus(value: BigDecimal): BigDecimal = BigDecimal(this.toString()).plus(value)
/**
* Number 与 BigDecimal 的减法运算符重载
*
* 允许任意数字类型直接与 BigDecimal 进行减法运算
* 例如:val result = 100 - BigDecimal("10.5")
*
* @param value 要相减的 BigDecimal 值
* @return 相减后的 BigDecimal 结果
*/
operator fun Number.minus(value: BigDecimal): BigDecimal = BigDecimal(this.toString()).minus(value)
/**
* Number 与 BigDecimal 的乘法运算符重载
*
* 允许任意数字类型直接与 BigDecimal 进行乘法运算
* 例如:val result = 100 * BigDecimal("10.5")
*
* @param value 要相乘的 BigDecimal 值
* @return 相乘后的 BigDecimal 结果
*/
operator fun Number.times(value: BigDecimal): BigDecimal = BigDecimal(this.toString()).times(value)
/**
* Number 与 BigDecimal 的除法运算符重载
*
* 允许任意数字类型直接与 BigDecimal 进行除法运算
* 例如:val result = 100 / BigDecimal("10.5")
*
* @param value 要相除的 BigDecimal 值(除数)
* @return 相除后的 BigDecimal 结果
*
* 注意:如果除不尽会抛出 ArithmeticException,建议使用 divide() 方法指定精度
*/
operator fun Number.div(value: BigDecimal): BigDecimal = BigDecimal(this.toString()).div(value)
/**
* Number 与 BigDecimal 的取余运算符重载
*
* 允许任意数字类型直接与 BigDecimal 进行取余运算
* 例如:val result = 100 % BigDecimal("10.5")
*
* @param value 取余运算的 BigDecimal 值
* @return 取余后的 BigDecimal 结果
*/
operator fun Number.rem(value: BigDecimal): BigDecimal = BigDecimal(this.toString()).rem(value)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile MetaData.kt
* LastUpdate 2026-03-11 08:46:40
* LastUpdate 2026-05-22 13:27:28
* UpdateUser MingLiPro
*/
@file:JvmName("MetaData")
@@ -26,8 +26,10 @@ package com.mingliqiye.utils.metadata
import com.mingliqiye.utils.resource.ResourceUtils
import java.util.stream.Collectors.toMap
class MetaDataResource
fun getMetaData(): Map<String, String> {
return ResourceUtils.getStringResource("/META-INF/meta-data").split("\n").stream().map {
return ResourceUtils.getResourceAsString<MetaDataResource>("/META-INF/meta-data").split("\n").stream().map {
if (it.isBlank()) {
return@map null
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ClientScheduleReconnect.kt
* LastUpdate 2026-01-20 08:10:15
* LastUpdate 2026-06-21 10:40:58
* UpdateUser MingLiPro
*/
@@ -119,21 +119,20 @@ abstract class ClientScheduleReconnect {
* 停止连接时的日志记录回调
*/
abstract fun onStoppedLog()
abstract fun onConnectClosed()
/**
* 执行连接操作
* @return ChannelFuture 连接结果的异步操作对象
*/
abstract fun doConnect(): ChannelFuture
abstract fun doConnect(bootstrap: Bootstrap): ChannelFuture
/**
* 初始化引导配置
* @param bootstrap 要初始化的引导配置对象
*/
open fun initBootstrap(bootstrap: Bootstrap) {
}
abstract fun initBootstrap(bootstrap: Bootstrap)
/**
* 更新重连延迟配置
@@ -151,7 +150,7 @@ abstract class ClientScheduleReconnect {
* 执行连接操作,设置连接完成监听器
*/
open fun connect() {
doConnect().addListener(object : ChannelFutureListener {
doConnect(bootstrap).addListener(object : ChannelFutureListener {
override fun operationComplete(future: ChannelFuture) {
if (future.isSuccess) {
onConnected(future.channel())
@@ -165,6 +164,7 @@ abstract class ClientScheduleReconnect {
/**
* 停止连接并标记为停止状态
*/
@Deprecated("use close()", ReplaceWith("close()"))
open fun stop() {
isStop = true
disConnect()
@@ -178,6 +178,14 @@ abstract class ClientScheduleReconnect {
channel = null
}
/**
* 停止连接并标记为停止状态
*/
open fun close() {
isStop = true
disConnect()
}
/**
* 调度下一次重连操作
*/
@@ -0,0 +1,52 @@
/*
* 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 NamedMultiThreadIoEventLoopGroup.kt
* LastUpdate 2026-06-20 22:01:50
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.netty
import com.mingliqiye.utils.system.availableProcessors
import io.netty.channel.MultiThreadIoEventLoopGroup
import io.netty.channel.nio.NioIoHandler
import java.nio.channels.spi.SelectorProvider
import java.text.MessageFormat
/**
* 命名的NIO事件循环组,继承自NioEventLoopGroup
* 用于创建具有自定义命名规则的线程池,便于线程管理和调试
*
* @param name 线程池的名称,默认为"NioEventLoopGroup"
* @param template 线程名称的格式模板,默认为"{0}-{2}-{3}",{0} 名字 {1} 类名 {2} 线程池序号 {3} 线程池内线程的序号
* @param nThreads 线程数量,默认为核心数的2倍
* @param selectorProvider NIO 提供者
*/
open class NamedMultiThreadIoEventLoopGroup(
val template: String = "{0}-{2}-{3}",
val name: String = "NamedMultiThreadIoEventLoopGroup",
nThreads: Int = availableProcessors * 2,
selectorProvider: SelectorProvider = SelectorProvider.provider(),
) :
MultiThreadIoEventLoopGroup(
nThreads,
NamedThreadFactory(
getName = { a, b, c -> MessageFormat.format(template, name, a, b, c) }
),
NioIoHandler.newFactory(selectorProvider),
)
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile NamedNioEventLoopGroup.kt
* LastUpdate 2026-02-05 10:20:31
* LastUpdate 2026-06-20 22:01:50
* UpdateUser MingLiPro
*/
@@ -37,7 +37,7 @@ import java.text.MessageFormat
open class NamedNioEventLoopGroup(
val template: String = "{0}-{2}-{3}",
val name: String = "NioEventLoopGroup",
nThreads: Int = availableProcessors * 2
nThreads: Int = availableProcessors * 2,
) :
NioEventLoopGroup(
nThreads,
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile NettyUtils.kt
* LastUpdate 2026-01-31 20:50:41
* LastUpdate 2026-06-20 22:18:39
* UpdateUser MingLiPro
*/
@@ -30,7 +30,10 @@ import io.netty.bootstrap.ServerBootstrap
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import io.netty.channel.Channel
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelInitializer
import io.netty.channel.ChannelPipeline
import io.netty.util.concurrent.Future
import java.nio.ByteBuffer
import java.nio.charset.Charset
@@ -106,6 +109,26 @@ fun ServerBootstrap.channelInitializer(funa: P1Function<Channel>): ServerBootstr
return this
}
/**
* 为ServerBootstrap配置子管道初始化器
*
* 该函数用于设置ServerBootstrap的childHandler,当新的客户端连接建立时,
* 会调用提供的函数来初始化子管道
*
* @receiver ServerBootstrap 需要配置的服务器引导程序实例
* @param funa 用于初始化管道的回调函数,接收ChannelPipeline作为参数
* @return ServerBootstrap 返回当前实例以支持链式调用
*/
@JvmName("pipelineInit")
fun ServerBootstrap.pipelineInitializer(funa: P1Function<ChannelPipeline>): ServerBootstrap {
this.childHandler(object : ChannelInitializer<Channel>() {
override fun initChannel(ch: Channel) {
funa.call(ch.pipeline())
}
})
return this
}
/**
* 为Bootstrap配置通道初始化器
*
@@ -126,6 +149,26 @@ fun Bootstrap.channelInitializer(funa: P1Function<Channel>): Bootstrap {
return this
}
/**
* 为Bootstrap配置管道初始化器
*
* 该函数用于设置Bootstrap的handler,当客户端连接建立时,
* 会调用提供的函数来初始化管道
*
* @receiver Bootstrap 需要配置的客户端引导程序实例
* @param funa 用于初始化管道的回调函数,接收ChannelPipeline作为参数
* @return Bootstrap 返回当前实例以支持链式调用
*/
@JvmName("pipelineInit")
fun Bootstrap.pipelineInitializer(funa: P1Function<ChannelPipeline>): Bootstrap {
this.handler(object : ChannelInitializer<Channel>() {
override fun initChannel(ch: Channel) {
funa.call(ch.pipeline())
}
})
return this
}
/**
* 将字符串转换为Netty的ByteBuf对象
*
@@ -248,7 +291,7 @@ fun Channel.closeSafely() {
/**
* 检查通道是否处于活跃状态
*/
val Channel.isActive: Boolean
val Channel.isActived: Boolean
get() = isOpen && isActive
/**
@@ -288,3 +331,8 @@ fun ByteBuf.tryRelease(): Boolean {
false
}
}
fun ChannelFuture.addChannelListener(
listener: (Future<Channel>) -> Unit,
) {
}
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile NetworkEndpoint.kt
* LastUpdate 2026-02-05 10:20:31
* LastUpdate 2026-05-23 11:00:33
* UpdateUser MingLiPro
*/
@@ -24,6 +24,7 @@ package com.mingliqiye.utils.network
import java.io.Serializable
import java.net.InetSocketAddress
import java.net.SocketAddress
import java.nio.ByteBuffer
/**
@@ -34,7 +35,7 @@ import java.nio.ByteBuffer
* @see java.net.InetSocketAddress
*/
class NetworkEndpoint private constructor(
val networkAddress: NetworkAddress, val networkPort: NetworkPort
val networkAddress: NetworkAddress, val networkPort: NetworkPort,
) : Serializable, InetSocketAddress(networkAddress.toInetAddress(), networkPort.port) {
@@ -47,10 +48,13 @@ class NetworkEndpoint private constructor(
* @see InetSocketAddress
*/
@JvmStatic
fun of(address: InetSocketAddress): NetworkEndpoint {
return NetworkEndpoint(
NetworkAddress.of(address.hostString), NetworkPort(address.port)
)
fun of(address: SocketAddress): NetworkEndpoint {
if (address is InetSocketAddress) {
return NetworkEndpoint(
NetworkAddress.of(address.hostString), NetworkPort(address.port)
)
}
throw ClassCastException("${address.javaClass} cannot be cast to InetSocketAddress to NetworkEndpoint")
}
/**
@@ -117,6 +121,11 @@ class NetworkEndpoint private constructor(
s.take(lastColonIndex), s.substring(lastColonIndex + 1).toInt()
)
}
val SocketAddress.networkAddress: NetworkEndpoint
get() = of(this)
val SocketAddress.hostPortString: String
get() = networkAddress.toHostPortString()
}
/**
@@ -16,73 +16,292 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile RandomBytes.kt
* LastUpdate 2026-01-28 10:47:13
* LastUpdate 2026-03-27 14:18:30
* UpdateUser MingLiPro
*/
@file:JvmName("RandomBytes")
package com.mingliqiye.utils.random
import java.security.SecureRandom
import kotlin.random.Random
import kotlin.random.nextInt
import kotlin.random.nextLong
/**
* 生成指定长度的随机字节数组
* @param length 数组长度
* @return 包含随机字节的数组
* Random对象 - 提供各种随机数据生成方法
* 使用SecureRandom确保密码学安全,同时提供便捷的随机数生成接口
*/
fun randomBytes(length: Int): ByteArray {
val bytes = ByteArray(length)
for (i in 0..<length) {
bytes[i] = randomByte(0x00.toByte(), 0xff.toByte())
object Random {
/**
* 安全随机数生成器 - 使用系统强随机算法
* 通过lazy委托延迟初始化,提高性能
*/
private val secureRandom: SecureRandom by lazy {
SecureRandom.getInstanceStrong()
}
return bytes
}
/**
* 生成指定长度的随机字节数组
* 从给定的字节数组中随机选择字节来填充新数组
*
* @param length 要生成的随机字节数组的长度
* @param bytes 用于随机选择的源字节数组
* @return 包含随机字节的新数组
*/
fun randomBytes(length: Int, bytes: ByteArray): ByteArray {
val rbytes = ByteArray(length)
// 从源数组中随机选择字节填充到结果数组中
for (i in 0..<length) {
rbytes[i] = bytes[randomInt(i, bytes.size - 1)]
/**
* 标准随机数生成器 - Kotlin标准库提供的随机数生成器
* 通过lazy委托延迟初始化
*/
private val random: Random by lazy {
Random
}
return rbytes
}
/**
* 生成指定范围内的随机字节
* @param from 起始字节值(包含)
* @param to 结束字节值(包含)
* @return 指定范围内的随机字节
*/
fun randomByte(from: Byte, to: Byte): Byte {
val fromInt = from.toInt() and 0xFF
val toInt = to.toInt() and 0xFF
val randomValue = randomInt(fromInt, toInt)
return (randomValue and 0xFF).toByte()
}
/**
* 生成指定长度的随机字节数组
* @param size 要生成的字节数组长度
* @return 包含随机字节的ByteArray
*/
@JvmStatic
fun nextBytes(size: Int): ByteArray = ByteArray(size).also { secureRandom.nextBytes(it) }
/**
* 生成指定范围内的随机字节(不包含边界值)
* @param from 起始字节值(不包含)
* @param to 结束字节值(不包含)
* @return 指定范围内的随机字节
*/
fun randomByteNoHave(from: Byte, to: Byte): Byte {
val fromInt = from.toInt() and 0xFF
val toInt = to.toInt() and 0xFF
val randomValue = randomIntNoHave(fromInt, toInt)
return (randomValue and 0xFF).toByte()
}
/**
* 生成单个随机字节
* @return 随机字节值(0-255)
*/
@JvmStatic
fun nextByte(): Byte = nextInt(0, 256).toByte()
/**
* 生成无符号随机字节
* @return 无符号随机字节值(0-255)
*/
@JvmStatic
fun nextUByte(): UByte = nextInt(0, 256).toUByte()
fun randomByte(size: Int): ByteArray {
val bytes = ByteArray(size)
secureRandom.nextBytes(bytes)
return bytes
/**
* 生成小于指定最大值的随机字节
* @param max 最大值(包含)
* @return 在Byte.MIN_VALUE到max范围内的随机字节
*/
@JvmStatic
fun nextByte(max: Byte): Byte = nextInt(Byte.MIN_VALUE.toInt(), max.toInt()).toByte()
/**
* 生成指定范围内的随机字节
* @param min 最小值(包含)
* @param max 最大值(包含)
* @return 在min到max范围内的随机字节
*/
@JvmStatic
fun nextByte(min: Byte, max: Byte): Byte = nextInt(min.toInt(), max.toInt() + 1).toByte()
/**
* 生成指定范围内的无符号随机字节
* @param min 最小值(包含)
* @param max 最大值(包含)
* @return 在min到max范围内的无符号随机字节
*/
@JvmStatic
fun nextByte(min: UByte, max: UByte): UByte = nextInt(min.toInt(), max.toInt() + 1).toUByte()
/**
* 生成指定IntRange范围内的随机字节
* @param range 指定的整数范围
* @return 在范围内转换为字节的随机值
*/
@JvmStatic
fun nextByte(range: IntRange): Byte = nextByte(range.first.toByte(), range.last.toByte())
/**
* 生成指定UIntRange范围内的无符号随机字节
* @param range 指定的无符号整数范围
* @return 在范围内转换为无符号字节的随机值
*/
@JvmStatic
fun nextByte(range: UIntRange): UByte = nextByte(range.first.toUByte(), range.last.toUByte())
/**
* 生成随机整数
* @return 随机整数值
*/
@JvmStatic
fun nextInt(): Int = secureRandom.nextInt()
/**
* 生成小于指定最大值的随机整数
* @param max 最大值(不包含)
* @return 0到max-1范围内的随机整数
*/
@JvmStatic
fun nextInt(max: Int): Int = secureRandom.nextInt(max)
/**
* 生成指定范围内的随机整数
* @param min 最小值(包含)
* @param max 最大值(包含)
* @return 在min到max范围内的随机整数
*/
@JvmStatic
fun nextInt(min: Int, max: Int): Int = random.nextInt(min..max)
/**
* 生成指定IntRange范围内的随机整数
* @param range 指定的整数范围
* @return 在范围内的随机整数
*/
@JvmStatic
fun nextInt(range: IntRange): Int = random.nextInt(range)
/**
* 生成随机短整数
* @return 在Short范围内的随机短整数
*/
@JvmStatic
fun nextShort(): Short = secureRandom.nextInt(Short.MIN_VALUE.toInt(), Short.MAX_VALUE.toInt()).toShort()
/**
* 生成小于指定最大值的随机短整数
* @param max 最大值(包含)
* @return 在Short.MIN_VALUE到max范围内的随机短整数
*/
@JvmStatic
fun nextShort(max: Short): Short = secureRandom.nextInt(Short.MIN_VALUE.toInt(), max.toInt()).toShort()
/**
* 生成指定范围内的随机短整数
* @param min 最小值(包含)
* @param max 最大值(包含)
* @return 在min到max范围内的随机短整数
*/
@JvmStatic
fun nextShort(min: Short, max: Short): Short = secureRandom.nextInt(min.toInt(), max.toInt()).toShort()
/**
* 生成指定IntRange范围内的随机短整数
* @param range 指定的整数范围
* @return 在范围内转换为短整数的随机值
*/
@JvmStatic
fun nextShort(range: IntRange): Short = secureRandom.nextInt(range.first, range.last).toShort()
/**
* 生成随机长整数
* @return 随机长整数值
*/
@JvmStatic
fun nextLong(): Long = secureRandom.nextLong()
/**
* 生成小于指定最大值的随机长整数
* @param max 最大值(不包含)
* @return 0到max-1范围内的随机长整数
*/
@JvmStatic
fun nextLong(max: Long): Long = secureRandom.nextLong(max)
/**
* 生成指定范围内的随机长整数
* @param min 最小值(包含)
* @param max 最大值(包含)
* @return 在min到max范围内的随机长整数
*/
@JvmStatic
fun nextLong(min: Long, max: Long): Long = random.nextLong(min..max)
/**
* 生成指定LongRange范围内的随机长整数
* @param range 指定的长整数范围
* @return 在范围内的随机长整数
*/
@JvmStatic
fun nextLong(range: LongRange): Long = random.nextLong(range)
/**
* 生成随机布尔值
* @return 随机true或false
*/
@JvmStatic
fun nextBoolean(): Boolean = secureRandom.nextBoolean()
/**
* String类型的扩展函数 - 从字符串中随机选择字符生成指定长度的新字符串
* @param length 要生成的字符串长度
* @return 由原字符串中随机字符组成的新字符串
*/
@JvmStatic
fun String.randomString(length: Int): String = String(CharArray(length) {
this[nextInt(0..<this.length)]
})
/**
* 生成包含数字和字母的随机字符串
* @param length 要生成的字符串长度
* @return 包含0-9、a-z、A-Z字符的随机字符串
*/
@JvmStatic
fun randomString(length: Int): String =
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".randomString(length)
/**
* Array类型的扩展函数 - 从数组中随机选择一个元素
* @param T 数组元素类型
* @return 数组中的随机元素
*/
@JvmStatic
fun <T> Array<T>.randomItem(): T = this[nextInt(0..<this.size)]
/**
* ByteArray类型的扩展函数 - 从字节数组中随机选择一个元素
* @return 字节数组中的随机字节
*/
@JvmStatic
fun ByteArray.randomItem(): Byte = this[nextInt(0..<this.size)]
/**
* IntArray类型的扩展函数 - 从整数数组中随机选择一个元素
* @return 整数数组中的随机整数
*/
@JvmStatic
fun IntArray.randomItem(): Int = this[nextInt(0..<this.size)]
/**
* LongArray类型的扩展函数 - 从长整数数组中随机选择一个元素
* @return 长整数数组中的随机长整数
*/
@JvmStatic
fun LongArray.randomItem(): Long = this[nextInt(0..<this.size)]
/**
* FloatArray类型的扩展函数 - 从浮点数数组中随机选择一个元素
* @return 浮点数数组中的随机浮点数
*/
@JvmStatic
fun FloatArray.randomItem(): Float = this[nextInt(0..<this.size)]
/**
* DoubleArray类型的扩展函数 - 从双精度浮点数数组中随机选择一个元素
* @return 双精度浮点数数组中的随机双精度浮点数
*/
@JvmStatic
fun DoubleArray.randomItem(): Double = this[nextInt(0..<this.size)]
/**
* BooleanArray类型的扩展函数 - 从布尔数组中随机选择一个元素
* @return 布尔数组中的随机布尔值
*/
@JvmStatic
fun BooleanArray.randomItem(): Boolean = this[nextInt(0..<this.size)]
/**
* CharArray类型的扩展函数 - 从字符数组中随机选择一个元素
* @return 字符数组中的随机字符
*/
@JvmStatic
fun CharArray.randomItem(): Char = this[nextInt(0..<this.size)]
/**
* ShortArray类型的扩展函数 - 从短整数数组中随机选择一个元素
* @return 短整数数组中的随机短整数
*/
@JvmStatic
fun ShortArray.randomItem(): Short = this[nextInt(0..<this.size)]
/**
* Collection类型的扩展函数 - 从集合中随机选择一个元素
* @param T 集合元素类型
* @return 集合中的随机元素
*/
@JvmStatic
fun <T> Collection<T>.randomItem(): T = this.elementAt(nextInt(0..<this.size))
}
@@ -1,67 +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 RandomInt.kt
* LastUpdate 2026-01-28 10:46:02
* UpdateUser MingLiPro
*/
@file:JvmName("RandomInt")
package com.mingliqiye.utils.random
import java.security.SecureRandom
val secureRandom: SecureRandom by lazy {
SecureRandom.getInstanceStrong()
}
fun SecureRandom.nextInt(min: Int, max: Int): Int {
return min + nextInt(max - min)
}
/**
* 生成指定范围内的随机整数
* @param min 最小值(包含)
* @param max 最大值(不包含)
* @return 随机整数
*/
fun randomIntNoHave(min: Int, max: Int): Int {
var min = min
var max = max
if (min > max) {
val t = min
min = max
max = t
}
if (min == max) {
return min
}
return secureRandom.nextInt(min, max)
}
/**
* 生成指定范围内的随机整数
* @param min 最小值(包含)
* @param max 最大值(包含)
* @return 随机整数
*/
fun randomInt(min: Int, max: Int): Int {
var max = max
return randomIntNoHave(min, ++max)
}
@@ -1,54 +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 RandomString.kt
* LastUpdate 2026-02-05 11:12:36
* UpdateUser MingLiPro
*/
@file:JvmName("RandomString")
package com.mingliqiye.utils.random
/**
* 生成指定长度和字符集的随机字符串
*
* @param length 要生成的随机字符串长度
* @param chars 用于生成随机字符串的字符集
* @return 指定长度的随机字符串
*/
fun randomString(length: Int, chars: String): String {
val charsd: Array<String> = chars.split("".toRegex()).filter { !it.isEmpty() }.toTypedArray().println()
val sb = StringBuilder(length)
// 循环生成随机字符并拼接
for (i in 0..<length) {
val index = randomInt(0, charsd.size - 1)
sb.append(charsd[index])
}
return sb.toString()
}
/**
* 生成指定长度的随机字符串,使用默认字符集(数字+大小写字母)
*
* @param length 要生成的随机字符串长度
* @return 指定长度的随机字符串
*/
fun randomString(length: Int): String {
return randomString(
length, "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
)
}
@@ -0,0 +1,55 @@
/*
* 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 ReflectUtils.kt
* LastUpdate 2026-06-21 10:40:58
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.reflect
import com.mingliqiye.utils.io.SIO.ifOr
import java.lang.reflect.AnnotatedElement
import java.lang.reflect.Method
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.KMutableProperty
import kotlin.reflect.KProperty
import kotlin.reflect.jvm.javaMethod
object ReflectUtils {
private val walker: StackWalker = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)
inline fun <reified T : Annotation> AnnotatedElement.getAnnotation() = this.getAnnotation(T::class.java)
inline fun <reified T : Any> T.ktClass(): KClass<T> = T::class
var <T : Any> KMutableProperty<T>.value: T
get() = this.getter.call()
set(t: T) = this.setter.call(t)
val <T : Any> KProperty<T>.javaGetter: Method
get() = this.getter.javaMethod!!
val <T : Any> KMutableProperty<T>.javaSetter: Method
get() = this.getter.javaMethod!!
val <T : Any> KFunction<T>.java: Method
get() = this.javaMethod!!
fun getStackFrame(skip: Long = 0, limit: Long = 0): List<StackWalker.StackFrame> {
return walker.walk {
it.skip(skip + 2).ifOr(limit == 0L) {
limit(limit)
}.toList()
}
}
}
@@ -1,263 +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 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,120 +16,142 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile ResourceUtils.kt
* LastUpdate 2026-02-05 11:09:16
* LastUpdate 2026-05-23 10:28:28
* UpdateUser MingLiPro
*/
package com.mingliqiye.utils.resource
import java.io.IOException
import com.mingliqiye.utils.exception.NotFoundResourceException
import java.nio.charset.Charset
/**
* 工具类,用于从类路径中加载资源文件。
*/
object ResourceUtils {
/**
* 从默认类路径中加载指定名称的资源文件,并以字节数组形式返回。
* 从类路径中读取资源文件并返回字节数组(使用 reified 类型参数)
*
* @param resourceName 资源文件的名称(相对于类路径根目录)。
* @return 资源文件的内容作为字节数组。
* @throws IOException 如果资源未找到或读取失败时抛出。
* 这是一个内联扩展函数,利用 reified 关键字在编译时获取具体类型 T 的 Class 对象
*
* @param T 用于获取 ClassLoader 的类型参数(通常传入调用方的类)
* @param path 资源文件的路径(相对于 T 所在的包,或以 / 开头的绝对路径)
* @return 资源的字节数组
* @throws NotFoundResourceException 当资源不存在时抛出
*
* 使用示例:
* ```kotlin
* // 在当前类的包下查找 config.json
* val data = getResourceAsByteArray<MyClass>("config.json")
*
* // 使用绝对路径(从 classpath 根目录)
* val data = getResourceAsByteArray<MyClass>("/assets/config.json")
* ```
*/
@JvmStatic
@Throws(IOException::class)
fun getResource(resourceName: String): ByteArray {
return getResource(resourceName, ResourceUtils::class.java)
inline fun <reified T> getResourceAsByteArray(path: String): ByteArray {
// 将 reified T 的 KClass 转换为 Java 的 Class 对象,传递给重载方法
return getResourceAsByteArray(path, T::class.java)
}
/**
* 从指定类的类路径中加载指定名称的资源文件,并以字节数组形式返回。
* 从类路径中读取资源文件并返回字符串(使用 reified 类型参数)
*
* @param resourceName 资源文件的名称(相对于类路径根目录)。
* @param clazz 用于定位资源的类。
* @return 资源文件的内容作为字节数组。
* @throws IOException 如果资源未找到或读取失败时抛出。
* @param T 用于获取 ClassLoader 的类型参数
* @param resource 资源文件路径
* @param charset 字符编码,默认为系统默认字符集
* @return 资源文件的字符串内容
* @throws NotFoundResourceException 当资源不存在时抛出
*
* 使用示例:
* ```kotlin
* // 读取文本文件,使用默认编码
* val content = getResourceAsString<MyClass>("data.txt")
*
* // 指定 UTF-8 编码
* val content = getResourceAsString<MyClass>("data.txt", Charsets.UTF_8)
* ```
*/
@JvmStatic
@Throws(IOException::class)
fun getResource(resourceName: String, clazz: Class<*>): ByteArray {
return clazz.getResourceAsStream(resourceName)?.use {
it.readBytes()
} ?: throw IOException("Resource not found: $resourceName")
inline fun <reified T> getResourceAsString(
resource: String,
charset: Charset = Charset.defaultCharset(),
): String {
// 将 reified T 的 Class 对象传递给重载方法
return getResourceAsString(resource, charset, T::class.java)
}
/**
* 从默认类路径中加载指定名称的资源文件,并以字符串形式返回。
* 从类路径中读取资源文件并返回字符串(Java 友好重载版本)
*
* @param resourceName 资源文件的名称(相对于类路径根目录)。
* @return 资源文件的内容作为字符串(使用UTF-8编码)。
* @throws IOException 如果资源未找到或读取失败时抛出。
* 此方法标记为 @JvmStatic,使其可以在 Java 代码中以静态方法形式调用
*
* @param path 资源文件路径
* @param charset 字符编码
* @param clazz 用于获取 ClassLoader 的参考类
* @return 资源文件的字符串内容
* @throws NotFoundResourceException 当资源不存在时抛出
*
* Java 调用示例:
* ```java
* // 在 Java 中调用
* String content = YourClass.getResourceAsString("config.json", StandardCharsets.UTF_8, MyClass.class);
* ```
*/
@JvmStatic
@Throws(IOException::class)
fun getStringResource(resourceName: String): String {
return getStringResource(resourceName, ResourceUtils::class.java)
fun getResourceAsString(path: String, charset: Charset, clazz: Class<*>): String {
// 先读取为字节数组,再按指定字符集解码为字符串
return String(getResourceAsByteArray(path, clazz), charset)
}
/**
* 从指定类的类路径中加载指定名称的资源文件,并以字符串形式返回。
* 从类路径中读取资源文件并返回字符串(使用默认字符集,Java 友好重载)
*
* @param resourceName 资源文件的名称(相对于类路径根目录)。
* @param clazz 用于定位资源的类。
* @return 资源文件的内容作为字符串(使用UTF-8编码)。
* @throws IOException 如果资源未找到或读取失败时抛出。
* @param path 资源文件路径
* @param clazz 用于获取 ClassLoader 的参考类
* @return 资源文件的字符串内容
* @throws NotFoundResourceException 当资源不存在时抛出
*/
@JvmStatic
@Throws(IOException::class)
fun getStringResource(resourceName: String, clazz: Class<*>): String {
return clazz.getResourceAsStream(resourceName)?.use {
it.readBytes().toString(charset = Charsets.UTF_8)
} ?: throw IOException("Resource not found: $resourceName")
fun getResourceAsString(path: String, clazz: Class<*>): String {
// 委托给上面的方法,使用系统默认字符集
return getResourceAsString(path, Charset.defaultCharset(), clazz)
}
/**
* 从调用者的类路径中加载指定名称的资源文件,并以字符串形式返回。
* 从类路径中读取资源文件并返回字节数组(核心实现方法)
*
* @param resourceName 资源文件的名称(相对于类路径根目录)。
* @return 资源文件的内容作为字符串(使用UTF-8编码)。
* @throws IOException 如果资源未找到或读取失败时抛出。
* 这是所有方法的核心实现,负责实际的资源查找和读取工作
*
* @param path 资源文件路径
* - 如果以 "/" 开头:表示从 classpath 根目录查找
* - 如果不以 "/" 开头:表示相对于 clazz 所在包的路径
* @param clazz 参考类,用于确定相对路径的基准包
* @return 资源的完整字节数组(使用 readAllBytes() 一次性读取)
* @throws NotFoundResourceException 当资源文件不存在时抛出,错误信息会显示完整的查找路径
*
* 资源查找规则说明:
* 1. 如果 path = "config.properties" 且 clazz = com.example.MyClass
* 实际查找路径:/com/example/config.properties
*
* 2. 如果 path = "/config.properties"
* 实际查找路径:/config.properties(classpath 根目录)
*
* 异常消息示例:
* - 找不到文件时抛出:"/com/example/config.properties is not found"
*/
@JvmStatic
@Throws(IOException::class)
fun getStringResourceCallers(resourceName: String): String {
return getStringResource(resourceName, getCallerClass())
}
fun getResourceAsByteArray(path: String, clazz: Class<*>): ByteArray {
// 尝试从类路径中获取资源的输入流
val stream = clazz.getResourceAsStream(path)
?: throw NotFoundResourceException(
// 构建详细的错误信息:显示实际查找的完整路径
// 如果 path 不以 "/" 开头,则拼接类的包路径(将包名中的点替换为斜杠)
(if (!path.startsWith("/"))
"/${clazz.packageName.replace(".", "/")}/$path" // 相对路径:相对于 clazz 的包
else
path // 绝对路径:直接使用原路径
) + " is not found" // 添加 " is not found" 后缀
)
/**
* 从调用者的类路径中加载指定名称的资源文件,并以字节数组形式返回。
*
* @param resourceName 资源文件的名称(相对于类路径根目录)。
* @return 资源文件的内容作为字节数组。
* @throws IOException 如果资源未找到或读取失败时抛出。
*/
@JvmStatic
@Throws(IOException::class)
fun getResourceCallers(resourceName: String): ByteArray {
return getResource(resourceName, getCallerClass())
}
/**
* 获取当前调用栈中第一个非ResourceUtils类的调用者类。
*
* @return 调用者类对象;如果未找到则返回ResourceUtils类本身。
*/
private fun getCallerClass(): Class<*> {
val stackTrace = Thread.currentThread().stackTrace
for (i in 2 until stackTrace.size) {
val className = stackTrace[i].className
try {
val clazz = Class.forName(className)
if (clazz != ResourceUtils::class.java) {
return clazz
}
} catch (e: ClassNotFoundException) {
continue
}
}
return ResourceUtils::class.java
// 读取输入流中的所有字节并返回
// Kotlin 的扩展函数,等同于 Java 9+ 的 InputStream.readAllBytes()
return stream.readAllBytes()
}
}
@@ -16,15 +16,15 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile Jackson3JsonApiAutoConfiguration.kt
* LastUpdate 2026-02-26 14:24:33
* LastUpdate 2026-06-21 10:40:58
* 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.Jackson3JsonApi
import com.mingliqiye.utils.json.api.base.JsonApi
import com.mingliqiye.utils.logger.MingLiLoggerFactory
import org.springframework.boot.autoconfigure.AutoConfigureAfter
@@ -16,16 +16,16 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile SystemUtil.kt
* LastUpdate 2026-03-11 08:44:41
* LastUpdate 2026-03-27 09:35:40
* UpdateUser MingLiPro
*/
@file:JvmName("SystemUtils")
package com.mingliqiye.utils.system
import com.mingliqiye.utils.random.randomByte
import java.lang.management.ManagementFactory
import java.net.*
import com.mingliqiye.utils.random.Random.nextBytes as randomByte
/**
* 操作系统名称属性,延迟初始化
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile DateTime.kt
* LastUpdate 2026-03-07 11:02:42
* LastUpdate 2026-03-14 16:12:08
* UpdateUser MingLiPro
*/
@@ -54,7 +54,7 @@ import kotlin.time.Instant
format = "date-time"
)
class DateTime private constructor(
private var localDateTime: LocalDateTime, private val zoneId: ZoneId = ZoneId.systemDefault()
private var localDateTime: LocalDateTime, private val zoneId: ZoneId = ZoneId.systemDefault(),
) : Serializable {
companion object {
@@ -105,6 +105,18 @@ class DateTime private constructor(
return DateTime(localDateTime)
}
/**
* 根据 LocalDateTime 创建 DateTime 实例。
*
* @param localDateTime LocalDateTime 对象
* @return 返回对应的 DateTime 实例
*/
@JvmStatic
fun of(instant: java.time.Instant, zoneId: ZoneId = ZoneId.systemDefault()): DateTime {
return DateTime(LocalDateTime.ofInstant(instant, zoneId))
}
/**
* 解析时间字符串并生成 DateTime 实例。
*
@@ -115,7 +127,7 @@ class DateTime private constructor(
*/
@JvmStatic
fun parse(
timestr: String, formatter: String, fillZero: Boolean
timestr: String, formatter: String, fillZero: Boolean,
): DateTime {
return DateTime(
LocalDateTime.parse(
@@ -127,7 +139,7 @@ class DateTime private constructor(
@JvmStatic
fun parse(
timestr: String
timestr: String,
): DateTime {
val formatterString = Formatter.STANDARD_DATETIME_MILLISECOUND9.value
@@ -148,7 +160,7 @@ class DateTime private constructor(
*/
@JvmStatic
fun parse(
timestr: String, formatter: Formatter, fillZero: Boolean
timestr: String, formatter: Formatter, fillZero: Boolean,
): DateTime {
return parse(timestr, formatter.value, fillZero)
}
@@ -232,7 +244,7 @@ class DateTime private constructor(
*/
@JvmStatic
fun of(
year: Int, month: Int, day: Int, hour: Int, minute: Int
year: Int, month: Int, day: Int, hour: Int, minute: Int,
): DateTime {
return DateTime(LocalDateTime.of(year, month, day, hour, minute))
}
@@ -250,7 +262,7 @@ class DateTime private constructor(
*/
@JvmStatic
fun of(
year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int
year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int,
): DateTime {
return DateTime(
LocalDateTime.of(year, month, day, hour, minute, second)
@@ -271,7 +283,7 @@ class DateTime private constructor(
*/
@JvmStatic
fun of(
year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int, nano: Int
year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int, nano: Int,
): DateTime {
return DateTime(
LocalDateTime.of(year, month, day, hour, minute, second, nano)
@@ -311,6 +323,9 @@ class DateTime private constructor(
java.time.Instant.ofEpochMilli(epochMilli).atZone(zoneId).toLocalDateTime(), zoneId
)
}
fun LocalDateTime.toDateTime(): DateTime = of(this)
fun Date.toDateTime(): DateTime = of(this)
}
/**
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -16,7 +16,7 @@
* ProjectName mingli-utils
* ModuleName mingli-utils.main
* CurrentFile UUID.kt
* LastUpdate 2026-03-12 10:07:08
* LastUpdate 2026-06-21 10:40:58
* UpdateUser MingLiPro
*/
@@ -25,8 +25,7 @@ package com.mingliqiye.utils.uuid
import com.mingliqiye.utils.array.copyTo
import com.mingliqiye.utils.base.BaseCodec
import com.mingliqiye.utils.base.BaseType
import com.mingliqiye.utils.random.randomByte
import com.mingliqiye.utils.random.secureRandom
import com.mingliqiye.utils.random.Random
import com.mingliqiye.utils.system.macAddressBytes
import com.mingliqiye.utils.time.DateTime
import com.mingliqiye.utils.time.DateTimeOffset
@@ -38,6 +37,7 @@ import java.nio.ByteBuffer
import java.security.MessageDigest
import java.time.temporal.ChronoUnit
import java.util.concurrent.atomic.AtomicLong
import com.mingliqiye.utils.random.Random.nextBytes as randomByte
import java.util.UUID as JUUID
@@ -62,7 +62,7 @@ class UUID : Serializable {
private var lastTimestamp = 0L
private var clockSequence = secureRandom.nextInt(0x3FFF + 1)
private var clockSequence = Random.nextInt(0x3FFF + 1)
private val clockSeqHolder = AtomicLong(0)
/**
@@ -227,8 +227,8 @@ class UUID : Serializable {
.to100NanoTime() and 0x0FFFFFFFFFFFFFFFL
val timeHigh = (timestamp ushr 12) and 0xFFFFFFFFFFFFL
val timeMid = timestamp and 0x0FFFL
val clockSeq = secureRandom.nextInt(16384) and 0x3FFF
val node = secureRandom.nextLong() and 0x0000FFFFFFFFFFFFL
val clockSeq = Random.nextInt(16384) and 0x3FFF
val node = Random.nextLong() and 0x0000FFFFFFFFFFFFL
val buffer = ByteBuffer.allocate(16)
buffer.putLong((timeHigh shl 16) or (0x6000L) or (timeMid and 0x0FFF))
buffer.putShort((0x8000 or (clockSeq and 0x3FFF)).toShort())
@@ -253,7 +253,7 @@ class UUID : Serializable {
buffer.putInt((instant shr 16).toInt())
buffer.putShort((instant).toShort())
buffer.put(randomByte(2))
buffer.putLong(secureRandom.nextLong())
buffer.putLong(Random.nextLong())
val bytes = buffer.array()
bytes[6] = (bytes[6].toInt() and 0x0F or 0x70).toByte()
bytes[8] = (bytes[8].toInt() and 0x3F or 0x80).toByte()