All Downloads are FREE. Search and download functionalities are using the official Maven repository.

kr.jadekim.jext.redisson.codec.GsonCodec.kt Maven / Gradle / Ivy

The newest version!
package kr.jadekim.jext.redisson.codec

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import io.netty.buffer.ByteBufAllocator
import io.netty.buffer.ByteBufInputStream
import io.netty.buffer.ByteBufOutputStream
import org.redisson.client.codec.BaseCodec
import org.redisson.client.protocol.Decoder
import org.redisson.client.protocol.Encoder
import org.redisson.codec.JsonCodec
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import kotlin.reflect.KClass

class GsonCodec(
    val typeToken: TypeToken,
    private val gson: Gson = Gson(),
) : BaseCodec(), JsonCodec {

    constructor(clazz: Class, gson: Gson = Gson()) : this(TypeToken.get(clazz), gson)

    constructor(klass: KClass, gson: Gson = Gson()) : this(klass.java, gson)

    private val encoder = Encoder {
        val out = ByteBufAllocator.DEFAULT.buffer()

        return@Encoder try {
            val stream = ByteBufOutputStream(out)
            val writer = OutputStreamWriter(stream)
            gson.toJson(it, writer)
            writer.flush()
            stream.buffer()
        } catch (e: Exception) {
            out.release()
            throw e
        }
    }

    private val decoder = Decoder { buf, _ ->
        gson.fromJson(InputStreamReader(ByteBufInputStream(buf)), typeToken)
    }

    override fun getEncoder(): Encoder = encoder

    override fun getDecoder(): Decoder = decoder

    override fun getValueEncoder(): Encoder = encoder

    override fun getValueDecoder(): Decoder = decoder

    override fun getClassLoader(): ClassLoader {
        if (gson.javaClass.classLoader != null) {
            return gson.javaClass.classLoader
        }

        return super.getClassLoader()
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy