Chapter 8 Creating Enterprise JavaBeans Clients


Serializing and deserializing bean proxies

Serialization allows you to save a bean proxy as a file. Deserialization allows you to extract the proxy from the file in another process or on another machine, and, if the component instance is still active, reestablish your session with the component.

To serialize a proxy

Call the getHandle method on the remote interface, which returns a javax.ejb.Handle instance. You can serialize the Handle instance using the standard Java serialization protocol, as shown in the example below:

String _serializeTo; // Name  of file to save to
Stateful1 proxy;     // Active  proxy instance

try {
  System.out.println("Serializing  to " + _serializeTo);
  Handle  handle = proxy.getHandle();
  FileOutputStream  ostream = new   FileOutputStream(_serializeTo);
  ObjectOutputStream  p = new   ObjectOutputStream(ostream);
  p.writeObject(handle);
  p.flush();
  ostream.close();
} catch  (Exception e)
    {
  System.out.println("Serialization  failed. Exception "     + e.toString());
  e.printStackTrace();
  return;
    }

To deserialize the proxy

Use the standard Java deserialization protocol to extract the Handle instance, then call getEJBObject to restore the proxy, as shown in the example below:

String _serializeFrom; // Name  of file to read from
Stateful1 proxy; 

try {
  System.out.println("Deserializing  proxy from "
    + _serializeFrom);
  FileInputStream  istream = new   FileInputStream(_serializeFrom);
  ObjectInputStream  p = new ObjectInputStream(istream);
  Handle  handle = (Handle)p.readObject();
  proxy = (Stateful1)  handle.getEJBObject();
  istream.close();
} catch  (Exception e) 
{
  System.out.println(
    "Deserialization  failed. Exception " 
    + e.toString());
  e.printStackTrace();
  return;
}

 


Copyright (C) 2004. Sybase Inc. All rights reserved.