George Blank University Lecturer

Java RMI
Introduction to RMI

Java and the Web
‡ Java¶s popularity is due to its suitability for use on the World Wide Web (WWW). ‡ Several Web browsers have support for Java:
± Netscape Navigator ± Internet Explorer ± HotJava

‡ Java incorporates audio, video, and animation directly on the web page.

Method Modifiers ‡ ‡ ‡ ‡ ‡ Instance Methods Class Methods Abstract Methods Native Methods Final Methods .

Method Modifiers with Effect on Scoping ‡ public: Method can be accessed by any class ‡ private: methods accessed only by class methods ‡ friendly: methods accessed by other methods in the same package ‡ protected: methods accessed by subclass methods. .

except there is no data associated with the interface.Interfaces ‡ A Java interface is similar to a class. ‡ Example: public interface MyInterface { methods-with no implementation details final variables } .

‡ Interfaces are used to approximate multiple inheritances . ‡ A class that extends another class is guaranteed to support the contracts entered into by its superclass. ‡ The methods are only declarations.Properties of Interfaces ‡ The variables in an interface must be final.

The native code is not easily portable across different hardware platforms. (JNI section by Rekha Telkar) .Java Native Interface (JNI) ‡ The Java Native Interface (JNI) is part of the core JDK and provides a framework for interfacing to native code. JNI was developed to bridge the gap. So using native code takes way one of the major advantages of java.

. and wish to make it accessible to Java code through the JNI.When to use JNI ‡ When the standard Java class library does not support the platform-dependent features needed by the application. ‡ You want to implement a small portion of time-critical code in a lower-level language such as assembly. ‡ You need to use a library written in another language.

± Call Java methods. . and update Java objects (including arrays and strings). ± Perform runtime type checking. ± Load classes and obtain class information. ± Catch and throw exceptions.JNI Capabilities ‡ You can use native methods to: ± Create. inspect.

Enabling Java code with JNI ‡ You can use the JNI with the Invocation API to enable an arbitrary native application to embed the Java VM. . Programmers can make their existing applications Java-enabled without having to link with the VM source code.

.registry ‡ Enhanced security of Java 2 requires a security policy implementation.rmi.Remote Method Invocation ‡ RMI provides the means to invoke methods remotely. and java.rmi.server. java.rmi. ‡ RMI allows for applications to communicate and execute across multiple systems on a network. ‡ RMI is supported by the java.

Parts in a RMI System ‡ Interface definitions for remote services ‡ ‡ ‡ ‡ Implementations of the remote services Stub and Skeleton files A server to host the remote services An RMI Naming service that allows clients to find the remote services ‡ A class file provider (an HTTP or FTP server) .

RMI process Java Client Client Method arguments Client Stub Network transport results Server Skeleton Not needed In Java 2 Java Server Called Method Network Transport Network .

RMI Server. . ‡ The client calls Naming.bind() method. and Registry ‡ The server process registers the remote object X with the registry using the Naming. which contacts the registry and obtains a stub object for X. Client. ‡ The client then uses the stub as if it is a local object.lookup().

Stub Class ‡ A stub for a remote object is the clientside proxy for the remote object. The client-side stub responsibilities are shown on the next slide. Such a stub implements all the interfaces that are supported by the remote object implementation. .

‡ Informing the remote reference layer that the call is complete.Stub Class Responsibilities ‡ Initiating a call to the remote object (by calling the remote reference layer). ‡ Marshaling arguments to a marshal stream (obtained from the remote reference layer). ‡ Unmarshaling the return value or exception from a marshal stream. ‡ Informing the remote reference layer that the call should be invoked. .

± Marshaling the return value of the call or an exception (if one occurred) onto the marshal stream. .Skeleton Class ‡ A skeleton for a remote object is a server-side entity that contains a method which dispatches calls to the actual remote object implementation. The skeleton is responsible for: ± Unmarshaling arguments from the marshal stream. ± Making the up-call to the actual remote object implementation.

Remote Reference Layer ‡ The remote reference layer deals with the lower level transport interface and is responsible for carrying out a specific remote reference protocol which is independent of the client stubs and server skeletons. The remote reference layer has two cooperating components: the client-side and the serverside components. .

the client and server-side components perform the specific remote reference semantics.Remote Reference Layer (2) ‡ The client-side component contains information specific to the remote server (or servers. During each method invocation. if the remote reference is to a replicated object) and communicates via the transport to the server-side component. .

the server-side component implements the specific remote reference semantics prior to delivering a remote method invocation to the skeleton. if a remote object is part of a replicated object. .Remote Reference Layer (3) ‡ For example. the client-side component can forward the invocation to each replica rather than just a single remote object. ‡ In a corresponding manner.

Remote Reference Layer (4) ‡ For example. a connectionless transport may be implemented beneath the abstraction .The remote reference layer transmits data to the transport layer via the abstraction of a stream-oriented connection. Although connections present a streams-based interface. The transport takes care of the implementation details of connections. the server side could handle ensuring atomic multiple delivery by communicating with other servers in the replica group.

RMI Registry ‡ The Registry tracks the addresses of the remote objects exported by applications ‡ It is the central management point for RMI ‡ Does not actually invoke remote methods ‡ Bind() links the object in the registry ‡ Rebind() replaces object with a new one .

rmi runtime decodes the result. ‡ Finally. . encodes the results. ‡ The server then invokes the method. and sends it back.rmi runtime encodes the arguments and sends them over the network to a server that decodes them.Parameter Passing ‡ When a remote procedure is executed. the java. the client-side java.

Parameter Marshalling ‡ RMI stubs are responsible for packaging parameters used in a remote method in a block of bytes using the big-endian byte order. . This is called parameter marshalling. A receiver object on the server must unmarshall the parameters or report errors.

‡ Create Security Policy .Building RMI Applications ‡ Define remote interfaces ‡ Create classes that implement the interfaces ‡ Create stub and skeleton classes for the implementation classes.

A Distributed Hello World Program Using RMI ‡ It uses an applet to make a remote method call to the server from which it was downloaded to retrieve the message "Hello World!". ³Hello World!´ is displayed on the client browser. . ‡ When the applet runs.

‡ Start the Remote Object Registry. Server. and Applet .Steps Involved ‡ Write The HTML and Java Source Files. ‡ Compile and Deploy Class Files and HTML Files.

(HelloApplet.java) ‡ The HTML code for the web page that references the applet.java) ‡ The Java remote object (server) which implements the remote interface.Source Files ‡ The Java remote interface.html) . (hello. (HelloImpl.java) ‡ The Java applet that remotely invokes the remote method. sayHello(). (Hello.

rmi.rmi.The Remote Interface ‡ Must be public. ‡ Extends the interface java. ‡ Each method must declare java.Remote. .RemoteException in its throws clause ‡ A remote object passed as an argument or return value must be declared as the remote interface.

rmi. import java.rmi.Remote Interface package examples. } . public interface Hello extends java.RemoteException.RemoteException. import java.hello.Remote { String sayHello() throws java.Remote.rmi.rmi.

. ‡ Create and install a security manager. ‡ Define the constructor for the remote object.The Implementation Class ‡ Specify the remote interface(s) being implemented. ‡ Provide implementations for the methods that can be invoked remotely.

for bootstrapping purposes.The Implementation Class (Cont¶d) ‡ Create one or more instances of a remote object. ‡ Register at least one of the remote objects with the RMI remote object registry. .

hello.rmi.RemoteException.server.rmi. import java. import java. import java. } .Server Code (1) package examples.Naming.UnicastRemoteObject.rmi. import java. public class HelloImpl extends UnicastRemoteObject implements Hello { public HelloImpl() throws RemoteException { super().rmi.RMISecurityManager.

} .Server Code (2) // Implementation of remote method public String sayHello() { return "Hello World!".

} .setSecurityManager(new RMISecurityManager()).Server Code (3) main begins public static void main(String args[]) { // Create and install a security manager if (System.getSecurityManager() == null) { System.

out.Server Code (4) main ends try { HelloImpl obj = new HelloImpl().njit.println("HelloServer bound in registry").printStackTrace(). // Bind this object instance to the name "HelloServer" Naming.edu/HelloServer". } catch (Exception e) { System. } } } . obj).rebind("//afsxx.out. e.getMessage()).println("HelloImpl err: " + e. System.

Activatable) ‡ To bind to a different port. obj). for example 2001. the HelloImpl class can be used to create a remote object that: ± Uses RMI's default sockets-based transport for communication ± Runs all the time (In Java 2 SDK.edu:2001/HelloServer".njit. using Remote Object Activation.rmi. . use: Naming.rebind("//afsxx. rather than running all the time ± extend java.Notes on Server Code ‡ By extending remote class UnicastRemoteObject.activation. the object can be activated (created) when a client requests it.

including objects. or return values from. which is a clientside proxy for the remote object. which means that all data members (or fields) of an object are copied.Notes on Server Code (contd) ‡ Arguments to. ‡ By default. as long as those objects implement the interface java. A reference to a remote object is actually a reference to a stub.io. remote methods can be any data type for the Java platform. local objects are passed by copy. .Serializable. except those marked as static or transient ‡ Remote objects are passed by reference.

and RMI clients need to download RMI stubs (as well as any other custom classes or interfaces needed to communicate with the RMI server). ‡ If no security manager is specified. ‡ Client Applets use the security manager already installed in the client browser. aside from what can be found in the local CLASSPATH.Notes on Server Code (contd) ‡ Security manager guarantees that the classes that get loaded perform only allowed operations. no class loading. . by RMI clients or servers. ‡ If the client were an application rather than an applet. ‡ A security manager is required in any JVM that needs to download code. is allowed. Security manager would need to be installed.

import java.applet. public class HelloApplet extends Applet { String message = "". import java.rmi. import java.hello. import java. .Graphics.rmi.RemoteException.A Remote Service Applet package examples.Applet.Naming.awt. // "obj" is the identifier that we'll use // to refer to the remote object that // implements the "Hello" interface Hello obj = null.

printStackTrace(). } } . message = obj. e.out.println("Applet exception: " + e.getHost() + "/HelloServer").lookup("//" + getCodeBase(). } catch (Exception e) { System.getMessage()).Remote Applet Code (2) public void init() { try { Hello obj = (Hello)Naming.sayHello().

25. } } . 50).Remote Applet Code (3) public void paint(Graphics g) { g.drawString(message.

. causing the string "Hello World!" to be displayed in the drawing area of the applet. ‡ The applet invokes the remote sayHello method on the server's remote object.Notes on Client Applet ‡ The applet gets a reference to the remote object implementation (advertised as "HelloServer") from the server host's rmiregistry. ‡ The applet invokes the paint method.

html) <HTML> <title>Hello World</title> <center> <h1>Hello World</h1> </center> <p> <applet codebase="myclasses/ " code="examples.hello.The Web Page (hello.HelloApplet" width=500 height=120> </applet> </HTML> .

Compiling the Java Source Code ‡ Create a directory myclasses in your public_html on AFS and compile the java code: ‡ javac -d $HOME/public_html/myclasses Hello.java HelloApplet.java HelloImpl.java .

hello.Generate Stubs and Skeletons rmic -d $HOME/public_html/myclasses examples.class HelloImpl_Skel.class (before Java 2 only) .HelloImpl The following files are created in the directory: $HOME/public_html/myclasses/examples/hello HelloImpl_Stub.

2 -d $HOME/public_html/myclasses examples.2 option ‡ rmic ±v1. skeleton classes are obsolete.HelloImpl ‡ This creates only HelloImpl_Stub. RMI uses reflection to make the connection to the remote service object.class .hello.1 clients. ‡ If you will never need support for 1.Java 2 SDK Stubs ‡ In the Java 2 SDK implementation of RMI. rmic can be run with the -v1.

Deploying Applet (1) ‡ Move the HTML File (hello.html) to the Deployment Directory: $HOME/public_html/ .

SocketPermission "*:1024-65535". permission java. Replace * with name or IP of client to restrict access .Sample Policy File for User (.net.SocketPermission "*:80".accept".policy) in $HOME grant { permission java.java.net. "connect". }."connect.

Security Policy ‡ In a Unix environment. gives an explanation. Some students have expressed a preference for the explanation in Core Java 2. pages 351-368. ‡ To create a security policy. The default policy might work in Windows. Just Java 2. . see a Java text book. you will probably need to create a Security Policy for the Client Application but not for an applet.

UNIX: rmiregistry & ‡ Windows: start rmiregistry ‡ To start on a port other than the default 1099.Start the Remote Object Registry ‡ The RMI registry is a simple server-side bootstrap name server that allows remote clients to get a reference to a remote object. for example port 2001: rmiregistry 2001 & . ‡ Start registry on server .

java.HelloImpl The output should look like this: HelloServer bound in registry .security.edu/~username/myclasses / Djava.njit.Starting the Server java Djava.hello.server.rmi.codebase=http://afsxx.policy examples.policy=$HOME/.

so that the stub class can be dynamically downloaded to the registry and then to the client. ‡ Run the server.server. setting the codebase property to be the location of the implementation stubs.Starting the Server ‡ When starting the server.server. Because the codebase property in this example references a directory.codebase property must be specified. the java.codebase .rmi. make sure that any other classes that may need to be downloaded have also been installed in the directory referenced by java.rmi.

server.security.codebase property has been set properly to specify where the class files are located on the server.policy property for the server to set permissions. .Starting the Server ‡ Note: A stub class is dynamically downloaded to a client's virtual machine only when the class is not already available locally and the java. ‡ You can also specify the java.rmi.

or if the class files can't be located at the source (they aren't really being made available for download) or if you misspell the property name. ‡ You will also need to use a VPN if you access the RMI server from off-campus because AFS security does not allow remote connections from unsigned applets.lang. you'll get thrown a java.rmi.ClassNotFoundException.Common Exception ‡ If you forget the trailing slash on the codebase property. Otherwise you will get a Java.ConnectException .

Therefore.html & Or use the Browser URL: http://afsxx.html String Hello World should display.njit.Running the Applet appletviewer http://afsxx. . Note: The Applet sandbox allows them to connect only to their host URL.edu/~usrname/hello.njit. the AFS hostname should be of the AFS machine on which the RMI server is running.edu/~usrname/hello.

That will not work as Web server access to AFS is now disabled.njit.Output Browser Note: Use web. Appletviewer . not afsxx as shown.edu.

Advantages of RMI ‡ ‡ ‡ ‡ ‡ ‡ ‡ Object-Oriented Safe and Secure Easy to Write/Easy to Use Connects to Existing/Legacy Systems (JNI) Write Once. Run Anywhere Distributed Garbage Collection Parallel Computing .

Garbage collection is difficult if the server and client run on different machines. .Garbage Collection ‡ The Java Virtual Machine has an automatic garbage collector that will reclaim the memory from any object that has been discarded by the running program. The RMI subsystem implements a reference counting-based distributed garbage collection (DGC) algorithm to provide automatic memory management facilities for remote server objects.

When a client drops the reference. the remote object is free of any live client references. It is then placed on the weak reference list and subject to periodic garbage collection. the server increases the object reference count by one and marks the object as "dirty". the DGC decreases its reference count by one and marks the object as "clean. When a reference is made." When the reference count reaches zero. .How DGC works ‡ The remote server keeps track of all external client references.

not language independent Firewalls are not supported Naming service is not persistent No load balancing .RMI Limitations ‡ ‡ ‡ ‡ ‡ ‡ ‡ RMI is not full featured middleware No mechanism for object description No server events Java only.

Example
‡ Users fill in the fields of an expense report. Clients communicate with the server using RMI. The server stores the expense reports in a database using JDBC.

Remote Interface
import java.rmi.*; public interface ExpenseServer extends Remote { Policy getPolicy() throws RemoteException; void submitReport(ExpenseReport report) throws RemoteException, InvalidReportException; }

The Policy Interface
public interface Policy { void checkValid(ExpenseEntry entry) throws PolicyViolationException; }

// throws exception if not OK add the entry to the expense report } catch (PolicyViolationException e) { show the error to the user } } server.Client Code Policy curPolicy = server.submitReport(report).getPolicy(). .checkValid(entry). while (user keeps adding entries) { try { curPolicy.

server. import java.rmi. class ExpenseServerImpl extends UnicastRemoteObject implements ExpenseServer .*.rmi.*.Server Code (1) import java.

.write the report into the db.Server Code (2) { ExpenseServerImpl() throws RemoteException { // . } public Policy getPolicy() { return new TodaysPolicy().set up server state... } } .. } public void submitReport(ExpenseReport report) { // .....

// no receipt required throw new PolicyViolationException( "Need a receipt").dollars() < 20) return.Implementing a Policy public class TodaysPolicy implements Policy { public void checkValid(ExpenseEntry entry) throws PolicyViolationException { if (entry. } } .

dollars() < 20) return.isMeal() && entry. } } . // no receipt required throw new PolicyViolationException( "Need a receipt").New Policy Implementation public class TomorrowsPolicy implements Policy { public void checkValid(ExpenseEntry entry) throws PolicyViolationException { if (entry.

‡ RMI extends the Java object model beyond a single virtual machine address space.Summary ‡ Java RMI is a distributed object model for the Java platform. . ‡ RMI uses object serialization to convert object graphs to byte streams for transport.

public interface RemOp extends Remote { public void call() throws RemoteException. } .Defining Interfaces ‡ All methods that can be run remotely must be declared as part of an interface that extends Remote .

equals(). .Creating Classes that Implement the Interfaces ‡ Classes that implement the remote interfaces must be subclasses of the RemoteObject class. and toString(). ‡ RemoteObject provides support for the hashCode().

rmi. import java.server.rmi.Interface Class Example (1) package rmi1. import java.*. .*.

rebind(³operator´. return.setSecurityManager( new StubSecurityManager()).printStackTrace(). } } .Interface Class Example (2) public class RemImpl extends UnicastRemoteServer implements RemoOp { public static void main(String[] args) { System. new RemImpl()). } catch (Exception x) { x. try { Naming.

println(getName()).out.println(³Location: ³ + System. } .Interface Class Example (3) public RemImpl() throws RemoteException { } public void call() throws RemoteException { System.out.getProperty(³LOCATION´)). System.

} } .Interface Class Example (4) public String getName() { return ³Remote operation: ³ + hashCode().

rmi. import java.Interface Class Example (5) package rmi1.server. import java.rmi.*.*. .

} catch (Exception x) { x.lookup(³operator´).call(). ro.exit(-1). } } } . System.Interface Class Example (6) public class OpTest { public static void main(String[] args) { System.setSecurityManager( new StubSecurityManager()): try { RemOp ro = (RemOp) Naming.printStackTrace().

OpTest Output: Remote operation: 841549921 Location: server .registry.rmi.Running the rmi1 Example ‡ java java.RegistryImpl ‡ java -DLOCATION=server rmi1.RemImpl ‡ java -DLOCATION=client rmi1.

RMI Security ‡ One of the most common problems encountered with RMI is a failure due to security constraints. For example. ‡ The security policy can be set by constructing a SecurityManager object and calling the setSecurityManager method of the System class. checkConnect (String host. int port). The SecurityManager class has a large number of methods whose name begins with check. .

This usually causes the program to terminate with a message such as: java.SocketPermission 127. then the call throws an exception.resolve) .0.Security Continued ‡ If the current security policy does not allow connection to this host and port.net.AccessControlException: access denied (java.0.security.1:1099 connect.

Java-RMI vs. . CORBA and DCOM ‡ Java-RMI is a Java-specific middleware spec that allows client Java programs to invoke server Java objects as if they were local. ‡ Java-RMI is tightly coupled with the Java language.

This is impossible in DCOM or CORBA at present. . ‡ Because of this.Comparison Continued ‡ Since Java-RMI is tightly coupled with The Java Language. Java-RMI can work with true sub-classes. parameters passed during method calls between machines can be true Java Objects.

it can request that its class information be sent over the network. . Java-RMI supports Distributed Garbage Collection that ties into the local Garbage Collectors in each JVM.Comparison Continued ‡ If a process in an RMI system receives an object of a class that it has never seen before. ‡ Over and above all this.

Trouble Shooting
‡ If a JVM that is exporting remote objects does not have the java.rmi.server.codebase property set correctly, you will get a class not found error. ‡ Default port for RMI RegistryImpl is 1099. If it is already in use, you will get a
java.net.SocketException: Address already in use.

‡ Do not try to use the loopback address, 127.0.0.1 improperly. It does not work on a network. ‡ RMI is subject to Connection Exceptions that are idiosyncratic and difficult to overcome. This is one of the most common topics in RMI discussions.

Problems Encountered
‡ A java.rmi.NotBoundException was overcome by bypassing the start command and starting the server directly. This is not recommended, as the program will not exit normally. NOTE: A probable cause is another version of Java on the system that is referenced by the start command. ‡ Several java.rmi.UnmarshallException were caused by classes not in the class path. Some students just had to add the current directory: set classpath=.¶%classpath%

Problems Encountered
‡ An Incompatible Type Exception error occurred when a group failed to cast a returned reference to the <ClassName>_stub type. ‡ A java.security.AccessControlException required creating a policy file and referencing it as
java -Djava.security.policy=c:\rmi.policy <YourClient./<YourServer>

‡ Don¶t overlook standard programming errors like syntax errors, missing try blocks, and naming and typing mistakes.

Hints ‡ When you have a problem.RemoteInterface. ‡ You must start the registry (Windows command) start rmiregistrystart ‡ All remote interfaces must extend java.rmi. The client policy file permits connection to a specific referenced port number.rmi. ‡ Security management and implementing class policies are complex and difficult in RMI. you may have to kill all your processes and restart everything.UnicastRemoteObject. . and all remote objects must extend java.

rmi.useLocalHostname=true .* indicates things that may vary.RemoteServer.Lessons Learned ‡ You can get a trace of the server activity using java -Djava.server.rmi.rmi.logCalls=true <YourServer> ‡ Properties beginning java. ‡ You can find the host name of a caller of a remote method with java.server.rmi.rmi. you need to force a fully qualified host name with java.getClientHost ‡ On a server with multiple host names.server.* are part of published RMI spec and docs. while sun.

try java -version to see which version your environment defaults to.Environment Conflicts ‡ If you may have multiple versions of Java on your system.bat file may set some environment values that you might not think about. and that your Windows autoexec. . Remember that different versions seldom work together.

You may wish to find a simpler example.neu. because it includes a lot of material that goes beyond the basics. One excellent one was at ± http://www.edu/home/kenb/com3337/rmi_tut.ccs.Good RMI explanation ‡ The example from the Sun Web site is difficult to get working.ht ml .

2 adds activation.4 adds server-side stack trace retention. Service Provider Interface for RMIClassLoader and Dynamic Server Host Name. ‡ Java 1.3 adds enhancements to serialization ‡ Java 2 SDK. ‡ Java 2 SDK. the use of custom socket protocols and security policies.0. version 1.1 added core RMI support.RMI Versions ‡ Java 2 SDK. ‡ Java 1.2 was an interim release. and should not be used for RMI. version 1. version 1. but usually requires running applets in the applet viewer. .

html .sun. doc.2/docs/guide/rmi/getstart.ht ml ‡ http://java.com/marketing/collateral/javarmi.java.com/j2se/1.References ‡ http://java.com/developer/onlineTrainin g/rmi/RMI.html ‡ http://developer.com/j2se/1.4/docs/relnotes/features.sun.sun.4.html ‡ http://java.sun.