2011-12-21 11:25:40 +01:00
|
|
|
/**
|
2012-01-19 18:21:06 +01:00
|
|
|
* Copyright (C) 2009-2012 Typesafe Inc. <http://www.typesafe.com>
|
2011-12-21 11:25:40 +01:00
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
package akka.serialization
|
|
|
|
|
|
|
|
|
|
import com.google.protobuf.Message
|
|
|
|
|
|
2011-12-29 16:17:19 +01:00
|
|
|
/**
|
|
|
|
|
* This Serializer serializes `com.google.protobuf.Message`s
|
|
|
|
|
*/
|
2011-12-21 11:25:40 +01:00
|
|
|
class ProtobufSerializer extends Serializer {
|
|
|
|
|
val ARRAY_OF_BYTE_ARRAY = Array[Class[_]](classOf[Array[Byte]])
|
2011-12-29 16:17:19 +01:00
|
|
|
def includeManifest: Boolean = true
|
2011-12-30 22:00:49 +01:00
|
|
|
def identifier = 2
|
2011-12-21 11:25:40 +01:00
|
|
|
|
2011-12-30 19:20:24 +01:00
|
|
|
def toBinary(obj: AnyRef): Array[Byte] = obj match {
|
|
|
|
|
case m: Message ⇒ m.toByteArray
|
|
|
|
|
case _ ⇒ throw new IllegalArgumentException("Can't serialize a non-protobuf message using protobuf [" + obj + "]")
|
2011-12-21 11:25:40 +01:00
|
|
|
}
|
|
|
|
|
|
2011-12-30 19:20:24 +01:00
|
|
|
def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]], classLoader: Option[ClassLoader] = None): AnyRef =
|
|
|
|
|
clazz match {
|
|
|
|
|
case None ⇒ throw new IllegalArgumentException("Need a protobuf message class to be able to serialize bytes using protobuf")
|
|
|
|
|
case Some(c) ⇒ c.getDeclaredMethod("parseFrom", ARRAY_OF_BYTE_ARRAY: _*).invoke(null, bytes).asInstanceOf[Message]
|
|
|
|
|
}
|
2011-12-21 11:25:40 +01:00
|
|
|
}
|