Sunday, December 16, 2007

J2EE Review 1: RMI implementation

1. Declare Remote Interface
For example:
import java.rmi.*;
public interface MyRMIServer extends java.rmi.Remote{...}

Note that methods in the interface must throw RemoteException.
2. Implement Remote Interface
import java.rmi.*;
import java.rmi.server.*;
public class MyRMIServerImpl extends UnicastRemoteObject implements MyRMIServer{...}
3. Generate Stub (and Skeleton)
Use rmic command, not that after Java 1.2, no skeleton will be generated by default.
If you want to get the source file for the stub, use the keepgenerated flag.
rmic MyRMIServerImpl -keepgenerated
4. Register Remote Object
The process of registering an object with the RMI registry is called binding. There are 2 methods in the java.rmi.Naming class can bind an object to the registry. The bind() methods throws the AlreadyBoundException if the binding already exists, while rebind() method replaces any existing registry entry with the new one. unbind() is used to remove an object from the registry.
4a. Start rmi registry
use the command line
rmiregistry
to start registry on the default RMI port 1099.
use the command
rmiregistry 5555
to start the registry on port 5555
4b. Register object
import java.rmi.*;
public class StartMyRMIServer{
public static void main(String[] args){
try{
MyRMIServerImpl mrsi=new MyRMIServerImpl();
Naming.rebind("rmi://localhost:5500/MyRMIService",mrsi);
System.out.println("My RMI Service is waiting for the requests on port 5500 ...");
}catch(Exception ex){
ex.printStackTrace();
}
}
}
4c. Alternative: Combining 4a and 4b using the following code
import java.rmi.*;
import java.rmi.registry.LocateRegistry;
public class StartMyRMIServer{
public static void main(String[] args){
try{
LocateRegistry.createRegistry(5500);
MyRMIServerImpl mrsi=new MyRMIServerImpl();
Naming.rebind("rmi://localhost:5500/MyRMIService",mrsi);
System.out.println("My RMI Service is waiting for the requests on port 5500 ...");
}catch(Exception ex){
ex.printStackTrace();
}
}
}
5. Create RMI Client
import java.rmi.*;
import java.util.Vector;
public class MyRMIClient{
public static void main(String[] args){
try{
if(System.getSecurityManager()==null){
System.setSecurityManager(new RMISecurityManager());
}
MyRMIServer myServer=(MyRMIServer)Naming.lookup("rmi://localhost:5555/MyRMIService");
}
......

6. Create a policy file
Policy files contain permissions granted to users of this application. Here's an example of security.policy.
grant{
// Allow the client to connect to any port above 1024
permission java.net.SocketPermission "*:1024-", "connect";
};
7. Run RMI Client
java -Djava.security.policy=security.policy MyRMIClient

No comments: