user manual

Chapter 11: Writing enterprise bean clients 107
Client view of an enterprise bean
persistent storage). Later, you can retrieve the handle from storage and use it
to reestablish a reference to the enterprise bean.
However, you can only use the remote interface handle to recreate the
reference to the bean; you cannot use it to recreate the bean itself. If another
process has removed the bean, or the system crashed or shutdown and
removed the bean instance, then an exception is thrown when the client
application tries to use the handle to reestablish its reference to the bean.
When you are not sure that the bean instance will still be in existence, rather
than using a handle to the remote interface, you can store the bean's home
handle and recreate the bean object later by invoking the bean's create or find
methods.
After the client creates a bean instance, it can use the getHandle() method to
obtain a handle to this instance. Once it has the handle, it can write it to a
serialized file. Later, the client program can read the serialized file, casting the
object that it reads in to a Handle type. Then, it calls the getEJBObject() method
on the handle to obtain the bean reference, casting the results of
getEJBObject() to the correct type for the bean.
To illustrate, the CartClient program might do the following to utilize a handle
to the CartBean session bean:
import java.io;
import javax.ejb.Handle;
...
Cart cart;
...
cart = home.create(cardHolderName, creditCardNumber, expirationDate);
// call getHandle on the cart object to get its handle
cartHandle = cart.getHandle();
// write the handle to serialized file
FileOutputStream f = new FileOutputStream ("carthandle.ser");
ObjectOutputStream o = new ObjectOutputStream(f);
o.writeObject(myHandle);
o.flush();
o.close();
...
// read handle from file at later time
FileInputStream fi = new FileInputStream ("carthandle.ser");
ObjectInputStream oi = new ObjectInputStream(fi);
//read the object from the file and cast it to a Handle
cartHandle = (Handle)oi.readObject();
oi.close();
...
// Use the handle to reference the bean instance
try {
Object ref = context.lookup("cart");
Cart cart1 = (Cart) javax.rmi.PortableRemoteObject.narrow(ref,
Cart.class);
...
} catch (RemoteException e) {
...