pekko/akka-actor/src/main/scala/akka/serialization/Serializer.scala

75 lines
2.2 KiB
Scala
Raw Normal View History

package akka.serialization
/**
* Copyright (C) 2009-2011 Typesafe Inc. <http://www.typesafe.com>
*/
import java.io.{ ObjectOutputStream, ByteArrayOutputStream, ObjectInputStream, ByteArrayInputStream }
import akka.util.ClassLoaderObjectInputStream
object Serializer {
2011-12-29 16:11:56 +01:00
type Identifier = Int
}
2011-07-19 19:28:17 +02:00
/**
* A Serializer represents a bimap between an object and an array of bytes representing that object
*/
trait Serializer extends scala.Serializable {
/**
2011-12-29 16:11:56 +01:00
* Completely unique value to identify this implementation of Serializer, used to optimize network traffic
* Values from 0 to 16 is reserved for Akka internal usage
*/
def identifier: Serializer.Identifier
2011-07-19 19:28:17 +02:00
/**
* Serializes the given object into an Array of Byte
*/
def toBinary(o: AnyRef): Array[Byte]
2011-07-19 19:28:17 +02:00
2011-12-29 16:11:56 +01:00
/**
* Returns whether this serializer needs a manifest in the fromBinary method
*/
def includeManifest: Boolean
2011-07-19 19:28:17 +02:00
/**
* Produces an object from an array of bytes, with an optional type-hint and a classloader to load the class into
*/
2011-12-29 16:11:56 +01:00
def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]] = None, classLoader: Option[ClassLoader] = None): AnyRef
}
object JavaSerializer extends JavaSerializer
object NullSerializer extends NullSerializer
class JavaSerializer extends Serializer {
2011-12-29 16:11:56 +01:00
def includeManifest: Boolean = false
def identifier = 1: Serializer.Identifier
def toBinary(o: AnyRef): Array[Byte] = {
val bos = new ByteArrayOutputStream
val out = new ObjectOutputStream(bos)
out.writeObject(o)
out.close()
bos.toByteArray
}
def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]] = None,
classLoader: Option[ClassLoader] = None): AnyRef = {
val in =
if (classLoader.isDefined) new ClassLoaderObjectInputStream(classLoader.get, new ByteArrayInputStream(bytes)) else
new ObjectInputStream(new ByteArrayInputStream(bytes))
val obj = in.readObject
in.close()
obj
}
}
class NullSerializer extends Serializer {
val nullAsBytes = Array[Byte]()
2011-12-29 16:11:56 +01:00
def includeManifest: Boolean = false
def identifier = 0: Serializer.Identifier
def toBinary(o: AnyRef) = nullAsBytes
def fromBinary(bytes: Array[Byte], clazz: Option[Class[_]] = None, classLoader: Option[ClassLoader] = None): AnyRef = null
}