Newsletter sign-up
View all newsletters

Sign up for our Enterprise Java Newsletter

Enterprise Java

Get smart with proxies and RMI

Use dynamic class loading to implement smart proxies in RMI

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone

Page 3 of 4

A smart proxy must, therefore, implement java.io.Serializable, while not implementing an interface that extends java.rmi.Remote. At the same time, the proxy must implement the same interface as the server object. That allows the client to use the proxy as if it was the server object. Achieving all three of those goals might appear a little tricky, however. How does the proxy implement the server object's interface and not implement java.rmi.Remote? The answer lies in refactoring the way remote objects are typically implemented.

Conventional remote objects

"Beg your pardon, sir, but your excuse, 'We've always done it this way,' is the most damaging phrase in the language."

-Rear Admiral Grace Hopper, Ret.



Suppose that you want remote access to a Door object that contains methods, which return the door location and detect if the door is open. To implement that in Java RMI, you need to define an interface that extends java.rmi.Remote. That interface would also declare the methods that comprise the object's remote interface. Likewise, you need to define a class that implements that interface and can be exported as a remote object. The easiest way to define that class is to extend java.rmi.server.UnicastRemoteObject. That leads to the design shown in the UML class diagram below.

Figure 1. Door and DoorImpl class diagram



The remote interface, Door, extends java.rmi.Remote and declares the interface you need for Door objects. DoorImpl is the class that actually implements the Door interface. DoorImpl also extends java.rmi.server.UnicastRemoteObject so that instances of it can be accessed remotely.

Below is the code that you could use to implement that design:

/**
* Define the remote interface of a Door.
* @author M. Jeff Wilson
* @version 1.0
*/
public interface Door extends java.rmi.Remote
{
    String getLocation() throws java.rmi.RemoteException;
    boolean isOpen() throws java.rmi.RemoteException;
}
/**
* Define the remote object that implements the Door interface.
* @author M. Jeff Wilson
* @version 1.0
*/
public class DoorImpl extends java.rmi.server.UnicastRemoteObject
   implements Door
{
    private final String name;
    private boolean open = false;
    public DoorImpl(String name) throws java.rmi.RemoteException
    {
       super();
       this.name = name;
    }
    // in this implementation, each Door's name is the same as its
    // location.
    // we're also assuming the name will be unique.
    public String getLocation() { return name; }
    public boolean isOpen() { return open; }
    // assume the server side can call this method to set the
    // state of this door at any time
    void setOpen(boolean open) { this.open = open; }
    // convenience method for server code
    String getName() { return name; }
    // override various Object utility methods
    public String toString() { return "DoorImpl:["+ name +"]"; }
    // DoorImpls are equivalent if they are in the same location
    public boolean equals(Object obj)
    {
       if (obj instanceof DoorImpl)
       {
          DoorImpl other = (DoorImpl)obj;
          return name.equals(other.name);
       }
       return false;
    }
    public int hashCode() { return toString().hashCode(); }
}


Now that you've defined and implemented the Door interface, the next step is to allow remote clients to access Door's various instances. One way to do that is to bind each instance of DoorImpl to the RMI registry. The client would then have to construct a URL that contained the name of each Door it wanted, and do a naming service lookup on each Door to retrieve its RMI stub. That not only clutters up the RMI registry with a lot of names (one for each Door), but it is unnecessary work for the client as well. A better approach is to have one object bound in the RMI registry that keeps a collection of all the Doors in the server. Clients can look up the name of that object in the registry, then make remote method calls on the object to retrieve specific Doors. The design of such a DoorServer is shown in Figure 2. Notice that DoorServer and DoorServerImpl looks a lot like Door and DoorImpl because you are defining another remote interface (DoorServer) and the class that implements it (DoorServerImpl). One difference is that DoorServerImpl hangs on to a collection of DoorImpl. It will use that collection to fulfill its public Door.getDoor(String location) method.

Figure 2. DoorServer class diagram



Here's one possible implementation of the DoorServer design:

/**
* We need a class to serve Door objects to clients.
* First, create the server's remote interface.
* @author M. Jeff Wilson
* @version 1.0
*/
public interface DoorServer extends java.rmi.Remote
{
    Door getDoor(String location) throws java.rmi.RemoteException;
}
/**
* Define the class to implement the DoorServer interface.
* @author M. Jeff Wilson
* @version 1.0
*/
public class DoorServerImpl extends
java.rmi.server.UnicastRemoteObject implements DoorServer {
    /**
    * HashMap used to store instances of DoorImpl. The map will be keyed
    * by each DoorImpl's name attribute, so it is implied that two Doors
    * with the same name are equivalent.
    */
    private java.util.Hashtable hash = new java.util.Hashtable();
    public DoorServerImpl() throws java.rmi.RemoteException
    {
       // add a door to the hashmap
       DoorImpl impl = new DoorImpl("location1");
       hash.put(impl.getName(), impl);
    }
    /**
    * @param location - String value of the Door's location
    * @return an object that implements Door, given the location
    */
    public Door getDoor (String location)
    {
       return (Door)hash.get(location);
    }
    /**
    * Bootstrap the server by creating an instance of DoorServer and
    * binding its name in the RMI registry.
    */
    public static void main(String[] args)
    {
       System.setSecurityManager(new java.rmi.RMISecurityManager());
       // make the remote object available to clients
       try
       {
          DoorServerImpl server = new DoorServerImpl();
          java.rmi.Naming.rebind("rmi://host/DoorServer", server);
       }
       catch (Exception e)
       {
          e.printStackTrace();
          System.exit(1);
       }
    }
}


Finally, to wrap things up, the client code that gets an instance of Door might look like this:

try
{
    // get the DoorServer from the RMI registry
    DoorServer server = (DoorServer)Naming.lookup("rmi://host/DoorServer");
    // Use DoorServer to get a specific Door
    Door theDoor = server.getDoor("location1");
    // invoke methods on the returned Door
    if (theDoor.isOpen())
    {
       // handle the door-open case ...
    }
}
catch (Exception e)
{
    e.printStackTrace();
}


In that implementation, the client has to find the DoorServer by asking the RMI registry for it (via the call to Naming.lookup(URL)). Once the DoorServer is found, the client can ask for specific Door instances by calling DoorServer.getDoor(String), passing the Door's location.

Most tutorials and books on RMI suggest you create the Door interface and the DoorImpl class in this way, so that Door extends java.rmi.Remote, and DoorImpl extends java.rmi.server.UnicastRemoteObject and implements Door. To add a smart proxy for DoorImpl, however, you need to create a class that implements java.io.Serializable, and also implements Door, without also implementing java.rmi.Remote. However, since Door extends java.rmi.Remote, that is impossible.

Factoring out the remoteness

What is needed is a way to separate the server object's interface from its remoteness. The solution depends on the fact that Java, while it doesn't allow multiple inheritance of classes, does allow interfaces to extend more than one parent interface. Therefore, you can refactor the design for Door and DoorImpl to look like this:

Figure 3. The refactored class diagram



Notice that Door does not extend java.rmi.Remote. Instead, I've added a new interface, DoorRemote, that extends both Door and java.rmi.Remote. DoorImpl implements that new interface.

The following code shows the implementation of the new design:

/**
* Define the Door interface.
* @author M. Jeff Wilson
* @version 1.1
*/
public interface Door /* don't extend java.rmi.Remote */
{
    String getLocation() throws java.rmi.RemoteException;
    boolean isOpen() throws java.rmi.RemoteException;
}
/**
* Add the 'remoteness' to Door. Notice that you don't have to
* redeclare the methods in interface Door, just inherit both
* from Door and java.rmi.Remote.
* @author M. Jeff Wilson
* @version 1.0
*/
public interface DoorRemote extends java.rmi.Remote, Door
{
}
/**
* Define the remote object that implements the Door interface.
* @author M. Jeff Wilson
* @version 1.1
*/
public class DoorImpl extends java.rmi.server.UnicastRemoteObject
implements DoorRemote
{
    private final String name;
    private boolean open = false;
    public DoorImpl(String name) throws java.rmi.RemoteException
    {
       super();
       this.name = name;
    }
    // in this implementation, each Door's name is the same as its location.
    // we're also assuming the location will be unique
    public String getLocation() { return name; }
    public boolean isOpen() { return open; }
    // assume the server side can call this method to set the
    // state of this door at any time
    void setOpen(boolean open) { this.open = open; }
    // convenience method for server code
    String getName() { return name; }
    // override various Object utility methods
    public String toString() { return "DoorImpl:["+ name +"]"; }
    // DoorImpls are equivalent if they are in the same location
    public boolean equals(Object obj)
    {
       if (obj instanceof DoorImpl)
       {
          DoorImpl other = (DoorImpl)obj;
          return name.equals(other.name);
       }
       return false;
    }
    public int hashCode() { return toString().hashCode(); }
}


Defining the proxy

Now Door is not a remote interface (that is, it doesn't extend java.rmi.Remote). The remoteness is added by the DoorRemote interface, since it extends both Door and java.rmi.Remote. The semantics and behavior of DoorImpl haven't changed; when DoorServer.getDoor(String) is called, the RMI stub for DoorImpl is returned to the client. But splitting the interfaces that way lets you add a new class that implements Door, is serializable, but isn't remote. Let's add that class and call it DoorProxy.

/**
* Define a proxy for Door. Currently, the implementation of Door's
* methods are stubbed out.
* @author M. Jeff Wilson
* @version 1.0
*/
public class DoorProxy implements java.io.Serializable, Door
{
    public String getLocation() throws java.rmi.RemoteException
    {
       return null;
    }
    public boolean isOpen() throws java.rmi.RemoteException
    {
       return false;
    }
}


Since DoorProxy implements java.io.Serializable, a remote call can return a copy of it. DoorProxy also implements Door, so it appears the same to a client as a remote reference to a DoorImpl object.

For DoorProxy to be a true proxy, however, it needs to be able to store a reference to another object -- in this case, DoorImpl -- and forward method calls to the reference. You can easily accomplish this:

Figure 4. DoorProxy class diagram



/**
* Define a proxy for Door. In this version, all methods are
* delegated to the remote object.
* @author M. Jeff Wilson
* @version 1.1
*/
public class DoorProxy implements java.io.Serializable, Door
{
    // store a copy of the remote interface to a DoorImpl
    private DoorRemote impl = null;
    /**
    * Construct a DoorProxy.
    * @param impl - the remote reference to delegate to.
    */
    DoorProxy(DoorRemote impl)
    {
       this.impl = impl;
    }
    public String getLocation() throws java.rmi.RemoteException
    {
       // delegate to impl
       return impl.getLocation();
    }
    public boolean isOpen() throws java.rmi.RemoteException
    {
       // delegate to impl
       return impl.isOpen();
    }
}


A constructor has been added to DoorProxy to ensure that every instance created has a reference to a DoorRemote object. That reference will really be an instance of DoorImpl but, since the client doesn't need to know about anything more than the remote interface (DoorRemote), the details of DoorImpl are hidden from it. (It's also necessary to get the code to work because, when RMI serializes a DoorProxy, it's going to instantiate an RMI stub and replace the reference to DoorImpl with a reference to that stub. To do that, the impl field must be able to hold either a DoorImpl or its stub.)

Now if the client makes a remote method call that returns a DoorProxy, the DoorProxy's data is serialized and a copy of the object is instantiated in the client VM. As RMI serializes the DoorProxy, it notices that the impl field is a reference to an object that should be replaced by its RMI stub, so it replaces it. The result is that the DoorProxy instantiated in the client contains a remote reference to a DoorImpl object and can delegate its calls via RMI to that server object.

Now that you have the smart proxy, you need to make sure there's a way the client can get one. The easiest way to accomplish that is to change DoorServerImpl.getDoor(String) to return a properly constructed DoorProxy instead of a DoorImpl:

/**
* Define the class to implement the DoorServer interface.
* @author M. Jeff Wilson
* @version 1.1
*/
public class DoorServerImpl extends java.rmi.server.UnicastRemoteObject
    implements DoorServer
{
    /**
    * HashMap used to store instances of DoorImpl. The map will be keyed
    * by each DoorImpl's name attribute, so it is implied that two Doors
    * with the same name are equivalent.
    */
    private java.util.Hashtable hash = new java.util.Hashtable();
    public DoorServerImpl() throws java.rmi.RemoteException
    {
       // add a door to the hashmap
       DoorImpl impl = new DoorImpl("location1");
       hash.put(impl.getName(), impl);
    }
    /**
    * Changed to return the proxy.
    * @param location - String value of the Door's location
    * @return an object that implements Door, given the location
    */
    public Door getDoor (String location)
    {
       DoorImpl impl = (DoorImpl)hash.get(location);
       return new DoorProxy(impl);
    }
    /**
    * Bootstrap the server by creating an instance of DoorServer and
    * binding its name in the RMI registry.
    */
    public static void main(String[] args)
    {
       System.setSecurityManager(new java.rmi.RMISecurityManager());
       // make the remote object available to clients
       try
       {
          DoorServerImpl server = new DoorServerImpl();
          java.rmi.Naming.rebind("rmi://host/DoorServer", server);
       }
       catch (Exception e)
       {
          e.printStackTrace();
          System.exit(1);
       }
    }
}


The client code doesn't change; it still requests and gets a reference to an object that implements Door. Originally, it got the RMI stub to a DoorImpl object; now it gets a DoorProxy object. But since the client doesn't know about anything other than the Door interface, that substitution is invisible to it.

  • Digg
  • Reddit
  • SlashDot
  • Stumble
  • del.icio.us
  • Technorati
  • dzone
Comments (1)
Login
Forgot your account info?

thanksBy Anonymous on May 7, 2009, 6:26 amThank you very much for this excellent tutorial. Even though I will probably not use such model this time, it finally explained to me everything important that's...

Reply | Read entire comment

View all comments

Add comment
Anonymous comments subject to approval. Register here for member benefits.
Have a JavaWorld account? Log in here. Register now for a free account.
Resources