/** * Copyright (C) 2009 Scalable Solutions. */ package se.scalablesolutions.akka.serialization import org.codehaus.jackson.map.ObjectMapper import com.google.protobuf.Message import com.twitter.commons.Json import reflect.Manifest import sbinary.DefaultProtocol import java.io.{StringWriter, ByteArrayOutputStream, ObjectOutputStream} object SerializationProtocol { val SBINARY = 1 val SCALA_JSON = 2 val JAVA_JSON = 3 val PROTOBUF = 4 val JAVA = 5 val AVRO = 6 } /** * @author Jonas Bonér */ trait Serializable { def toBytes: Array[Byte] } /** * Serialization protocols. * * @author Jonas Bonér */ object Serializable { /** * Example on how to use the SBinary serialization protocol: *
* case class User(val usernamePassword: Tuple2[String, String],
* val email: String,
* val age: Int)
* extends Serializable.SBinary[User] {
* def this() = this(null, null, 0)
* import sbinary.DefaultProtocol._
* implicit object UserFormat extends Format[User] {
* def reads(in : Input) = User(
* read[Tuple2[String, String]](in),
* read[String](in),
* read[Int](in))
* def writes(out: Output, value: User) = {
* write[Tuple2[String, String]](out, value.usernamePassword)
* write[String](out, value.email)
* write[Int](out, value.age)
* }
* }
* def fromBytes(bytes: Array[Byte]) = fromByteArray[User](bytes)
* def toBytes: Array[Byte] = toByteArray(this)
* }
*
* @author Jonas Bonér
*/
trait SBinary[T <: AnyRef] extends Serializable {
def fromBytes(bytes: Array[Byte]): T
def toBytes: Array[Byte]
}
/**
* @author Jonas Bonér
*/
trait JSON extends Serializable {
def toJSON: String
}
/**
* @author Jonas Bonér
*/
abstract class JavaJSON extends JSON {
def toJSON: String = {
val out = new StringWriter
// FIXME: is this mapper expensive to create? Should I cache it away?
val mapper = new ObjectMapper
mapper.writeValue(out, this)
out.close
out.toString
}
def toBytes: Array[Byte] = {
val bos = new ByteArrayOutputStream
val out = new ObjectOutputStream(bos)
val mapper = new ObjectMapper
mapper.writeValue(out, this)
out.close
bos.toByteArray
}
}
/**
* @author Jonas Bonér
*/
trait ScalaJSON extends JSON {
def toJSON: String = Json.build(this).toString
def toBytes: Array[Byte] = toJSON.getBytes("UTF-8")
}
/**
* @author Jonas Bonér
*/
trait Protobuf[T] extends Serializable {
def fromBytes(bytes: Array[Byte]): T = getMessage.toBuilder.mergeFrom(bytes).asInstanceOf[T]
def toBytes: Array[Byte] = getMessage.toByteArray
def getMessage: Message
}
}