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

com.github.pjfanning.pekko.serialization.jackson216.PekkoSerializationModule.scala Maven / Gradle / Ivy

/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * license agreements; and to You under the Apache License, version 2.0:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * This file is part of the Apache Pekko project, which was derived from Akka.
 */

/*
 * Copyright (C) 2019-2022 Lightbend Inc. 
 */

package com.github.pjfanning.pekko.serialization.jackson216

import com.fasterxml.jackson.core.{JsonGenerator, JsonParser, ObjectCodec}
import com.fasterxml.jackson.databind.{DeserializationContext, JsonNode, SerializerProvider}
import com.fasterxml.jackson.databind.deser.std.StdScalarDeserializer
import com.fasterxml.jackson.databind.ser.std.StdScalarSerializer
import org.apache.pekko.serialization.jackson216.ActorSystemAccess
import org.apache.pekko.serialization.{SerializationExtension, Serializer, Serializers}

final class PekkoSerializationSerializer extends StdScalarSerializer[AnyRef](classOf[AnyRef]) with ActorSystemAccess {
  def serialization = SerializationExtension(currentSystem())
  override def serialize(value: AnyRef, jgen: JsonGenerator, provider: SerializerProvider): Unit = {
    val serializer: Serializer = serialization.findSerializerFor(value)
    val serId = serializer.identifier
    val manifest = Serializers.manifestFor(serializer, value)
    val serialized = serializer.toBinary(value)
    jgen.writeStartObject()
    jgen.writeStringField("serId", serId.toString)
    jgen.writeStringField("serManifest", manifest)
    jgen.writeBinaryField("payload", serialized)
    jgen.writeEndObject()
  }
}

final class PekkoSerializationDeserializer
    extends StdScalarDeserializer[AnyRef](classOf[AnyRef])
    with ActorSystemAccess {

  def serialization = SerializationExtension(currentSystem())

  def deserialize(jp: JsonParser, ctxt: DeserializationContext): AnyRef = {
    val codec: ObjectCodec = jp.getCodec()
    val jsonNode = codec.readTree[JsonNode](jp)
    val id = jsonNode.get("serId").textValue().toInt
    val manifest = jsonNode.get("serManifest").textValue()
    val payload = jsonNode.get("payload").binaryValue()
    serialization.deserialize(payload, id, manifest).get
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy