akka.stream.alpakka.geode.internal.pdx.DelegatingPdxSerializer.scala Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of akka-stream-alpakka-geode_2.11 Show documentation
Show all versions of akka-stream-alpakka-geode_2.11 Show documentation
Alpakka is a Reactive Enterprise Integration library for Java and Scala, based on Reactive Streams and Akka.
/*
* Copyright (C) 2016-2018 Lightbend Inc.
*/
package akka.stream.alpakka.geode.internal.pdx
import java.util.Properties
import org.apache.geode.cache.Declarable
import org.apache.geode.pdx.{PdxReader, PdxSerializer, PdxWriter}
/**
* Geode ClientCache does not support more than one serializer.
*
* This serializer delegates to lazily registered serializer.
*/
class DelegatingPdxSerializer(
isPdxCompat: (Class[_], Class[_]) => Boolean
) extends PdxSerializer
with Declarable {
private var serializers = Map[Class[_], PdxSerializer]()
def register[V](serializer: PdxSerializer, clazz: Class[V]): Unit = synchronized {
if (!serializers.contains(clazz))
serializers += (clazz -> serializer)
}
/**
* Marshalls a class with a registered serializer.
*
* @return true on success
*/
override def toData(o: scala.Any, out: PdxWriter): Boolean =
serializers.get(o.getClass).map(_.toData(o, out)).isDefined
/**
* Unmarshalls with registered serializer.
*
* Tries to find a registered serializer for a given class
*
* - Lookup on class basis
* - Iterating through all serializer to find a compatible one
*
* By doing this, a java pojo can be unmarshalled from a scala case class (and vice versa)
*
* @return unmarshalled class or null
*/
override def fromData(clazz: Class[_], in: PdxReader): AnyRef =
serializers
.get(clazz)
.map(_.fromData(clazz, in))
.orElse(serializers.collectFirst {
case (c, ser) if isPdxCompat(c, clazz) =>
val v = ser.fromData(clazz, in)
if (v != null) register(ser, clazz)
v
})
.orNull
override def init(props: Properties): Unit = {}
}