Tuesday, October 4, 2011

Scala serialize simple test case

A simple use case showing how to make scala classes serializable. This example checks that instances reference graph is entirely stored. When instances are restored, we modify the mutable java Properties instance to check that the change is seen both from service and server instance.
import java.io._

case class Common(properties:java.util.Properties) extends Serializable 
case class Server(name:String, ip:String, common:Common) extends Serializable
case class Service(server:Server, name:String, port:Int, common:Common) extends Serializable

val cmm1=Common(new java.util.Properties())
val srv1=Server("localhost", "127.0.0.1",cmm1)
val svc1=Service(srv1, "httpd", 80, cmm1)

val bufout = new ByteArrayOutputStream()
val obout = new ObjectOutputStream(bufout)

obout.writeObject(svc1)

val bufin = new ByteArrayInputStream(bufout.toByteArray)
val obin = new ObjectInputStream(bufin)

val svc2 = obin.readObject().asInstanceOf[Service]


assert(svc2 == svc1)

svc2.common.properties.put("toto", "tata")

assert(svc2.common == svc2.server.common)


CONTEXT : Linux Gentoo / Scala 2.9.1 / Java 1.6.0_26

1 comment:

  1. Thanks. When I ran the snippet, I got the error below.
    scala> obout.writeObject(svc1)
    java.io.NotSerializableException: java.io.ByteArrayOutputStream
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1548)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1509)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
    ... 60 elided

    ReplyDelete