Created
June 22, 2019 21:10
-
-
Save gclaramunt/d3b654d2e48470d9cd0658dcff74c9e7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package demo | |
import akka.serialization.SerializerWithStringManifest | |
import scalapb.{GeneratedMessage, GeneratedMessageCompanion} | |
import scala.reflect.runtime.{universe => ru} | |
/** | |
* Custom Serializer/Deserializer for scalapb protobuf generated classes | |
*/ | |
class ProtoSerDe extends SerializerWithStringManifest { | |
/** | |
* Serializer identifier | |
* @return Int | |
*/ | |
override def identifier: Int = 9002 | |
/** | |
* Get manifest (getClass.getName) | |
* @param o Object | |
* @return String | |
*/ | |
override def manifest(o: AnyRef): String = o.getClass.getName | |
/** | |
* Convert from object to binary | |
* @param o Object | |
* @return Array | |
*/ | |
override def toBinary(o: AnyRef): Array[Byte] = o match { | |
case z: GeneratedMessage => z.toByteArray | |
case _ => throw new Exception(s" not a GeneratedMessage $o") | |
} | |
/** | |
* Convert from binary to object | |
* @param bytes Array | |
* @param manifest String | |
* @return Object | |
*/ | |
override def fromBinary(bytes: Array[Byte], manifest: String): AnyRef = { | |
val runtimeMirror = ru.runtimeMirror(getClass.getClassLoader) | |
val module = runtimeMirror.staticModule(manifest) | |
val mm = runtimeMirror.reflectModule(module) | |
val obj = mm.instance.asInstanceOf[GeneratedMessageCompanion[_]] | |
obj.parseFrom(bytes).asInstanceOf[AnyRef] | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment