pekko/akka-remote/src/main/scala/akka/remote/serialization/ProtobufSerializer.scala

74 lines
2.7 KiB
Scala
Raw Normal View History

2011-12-21 11:25:40 +01:00
/**
* Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com>
2011-12-21 11:25:40 +01:00
*/
package akka.remote.serialization
2011-12-21 11:25:40 +01:00
import java.lang.reflect.Method
import java.util.concurrent.atomic.AtomicReference
import akka.actor.{ ActorRef, ExtendedActorSystem }
import akka.remote.WireFormats.ActorRefData
import akka.serialization.{ Serialization, BaseSerializer }
2011-12-21 11:25:40 +01:00
import com.google.protobuf.Message
import scala.annotation.tailrec
object ProtobufSerializer {
private val ARRAY_OF_BYTE_ARRAY = Array[Class[_]](classOf[Array[Byte]])
2012-05-15 17:16:46 +02:00
/**
* Helper to serialize an [[akka.actor.ActorRef]] to Akka's
* protobuf representation.
*/
def serializeActorRef(ref: ActorRef): ActorRefData = {
ActorRefData.newBuilder.setPath(Serialization.serializedActorPath(ref)).build
}
2012-05-15 17:16:46 +02:00
/**
* Helper to materialize (lookup) an [[akka.actor.ActorRef]]
* from Akka's protobuf representation in the supplied
2012-06-05 18:19:46 +02:00
* [[akka.actor.ActorSystem]].
2012-05-15 17:16:46 +02:00
*/
def deserializeActorRef(system: ExtendedActorSystem, refProtocol: ActorRefData): ActorRef =
system.provider.resolveActorRef(refProtocol.getPath)
}
2011-12-21 11:25:40 +01:00
/**
* This Serializer serializes `com.google.protobuf.Message`s
*/
class ProtobufSerializer(val system: ExtendedActorSystem) extends BaseSerializer {
2011-12-21 11:25:40 +01:00
private val parsingMethodBindingRef = new AtomicReference[Map[Class[_], Method]](Map.empty)
override def includeManifest: Boolean = true
2011-12-21 11:25:40 +01:00
override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = {
manifest match {
case Some(clazz)
@tailrec
def parsingMethod(method: Method = null): Method = {
val parsingMethodBinding = parsingMethodBindingRef.get()
parsingMethodBinding.get(clazz) match {
case Some(cachedParsingMethod) cachedParsingMethod
case None
import ProtobufSerializer.ARRAY_OF_BYTE_ARRAY
val unCachedParsingMethod = if (method eq null) clazz.getDeclaredMethod("parseFrom", ARRAY_OF_BYTE_ARRAY: _*) else method
if (parsingMethodBindingRef.compareAndSet(parsingMethodBinding, parsingMethodBinding.updated(clazz, unCachedParsingMethod)))
unCachedParsingMethod
else
parsingMethod(unCachedParsingMethod)
}
}
parsingMethod().invoke(null, bytes).asInstanceOf[Message]
case None throw new IllegalArgumentException("Need a protobuf message class to be able to serialize bytes using protobuf")
}
}
override def toBinary(obj: AnyRef): Array[Byte] = obj match {
case message: Message message.toByteArray
case _ throw new IllegalArgumentException(s"Can't serialize a non-protobuf message using protobuf [$obj]")
}
2013-01-09 01:47:48 +01:00
}