pekko/kernel/src/main/scala/serialization/Serializable.scala

93 lines
2.1 KiB
Scala
Raw Normal View History

2009-07-21 13:59:12 +02:00
/**
* Copyright (C) 2009 Scalable Solutions.
*/
package se.scalablesolutions.akka.serialization
import org.codehaus.jackson.map.ObjectMapper
import com.google.protobuf.Message
2009-07-21 13:59:12 +02:00
import com.twitter.commons.Json
import reflect.Manifest
import sbinary.DefaultProtocol
import java.io.{StringWriter, ByteArrayOutputStream, ObjectOutputStream}
2009-07-21 13:59:12 +02:00
object SerializationProtocol {
val SBINARY = 1
val SCALA_JSON = 2
val JAVA_JSON = 3
val PROTOBUF = 4
val JAVA = 5
val AVRO = 6
}
2009-07-21 13:59:12 +02:00
/**
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
trait Serializable {
def toBytes: Array[Byte]
}
2009-07-21 13:59:12 +02:00
/**
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
object Serializable {
/**
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
trait JSON[T] extends Serializable {
def body: T
def toJSON: String
2009-07-21 13:59:12 +02:00
}
/**
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
trait JavaJSON[T] extends JSON[T]{
private val mapper = new ObjectMapper
2009-07-21 13:59:12 +02:00
def toJSON: String = {
val out = new StringWriter
mapper.writeValue(out, body)
2009-07-21 13:59:12 +02:00
out.close
out.toString
}
def toBytes: Array[Byte] = {
val bos = new ByteArrayOutputStream
val out = new ObjectOutputStream(bos)
mapper.writeValue(out, body)
2009-07-21 13:59:12 +02:00
out.close
bos.toByteArray
}
}
/**
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
trait ScalaJSON[T] extends JSON[T] {
def toJSON: String = Json.build(body).toString
def toBytes: Array[Byte] = Json.build(body).toString.getBytes
}
/**
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
trait Protobuf extends Serializable {
def toBytes: Array[Byte]
def getSchema: Message
}
2009-07-21 13:59:12 +02:00
/**
* <pre>
* import sbinary.DefaultProtocol._
* def fromBytes(bytes: Array[Byte]) = fromByteArray[String](bytes)
* def toBytes: Array[Byte] = toByteArray(body)
* </pre>
* @author <a href="http://jonasboner.com">Jonas Bon&#233;r</a>
*/
trait SBinary extends Serializable {
def fromBytes(bytes: Array[Byte])
def toBytes: Array[Byte]
2009-07-21 13:59:12 +02:00
}
}