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

no.ks.kes.serdes.jackson.JacksonEventSerdes.kt Maven / Gradle / Ivy

There is a newer version: 4.5.0
Show newest version
package no.ks.kes.serdes.jackson

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.KotlinModule
import no.ks.kes.lib.*
import kotlin.reflect.KClass

class JacksonEventSerdes(events: Set>>,
                         private val objectMapper: ObjectMapper = ObjectMapper()
                                 .registerModule(Jdk8Module())
                                 .registerModule(JavaTimeModule())
                                 .registerModule(KotlinModule())
) : EventSerdes {
    private val events = events
            .map { getSerializationId(it) to it }
            .toMap()

    override fun deserialize(eventData: ByteArray, eventType: String): EventData<*> {
        return try {
            objectMapper.readValue(
                eventData,
                events[eventType]
                    ?.javaObjectType
                    ?: throw RuntimeException("No class registered for event type $eventType")
            )
        } catch (e: Exception) {
            throw  RuntimeException("Error during deserialization of eventType $eventType", e)
        }
    }
    override fun serialize(eventData: EventData<*>): ByteArray =
            try {
                objectMapper.writeValueAsBytes(eventData)
            } catch (e: Exception) {
                throw RuntimeException("Error during serialization of event: $eventData")
            }

    override fun > getSerializationId(eventClass: KClass): String {
        return getSerializationIdAnnotationValue(eventClass)
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy