Distributed Java Programming With RMI and CORBA
Qusay H. Mahmoudjanuary 2002
The Java Remote Method Invocation (RMI) mechanism and the Common Object Request Broker Architecture (CORBA) are the two most important and widely used distributed object systems. Each system has its own features and shortcomings. Both are being used in the industry for various applications ranging from e-commerce to health care. Selecting which of these two distribution mechanisms to use for a project is a tough task. This article presents an overview of RMI and CORBA, and more importantly it shows how to develop a useful application for downloading files From remote hosts. it Then:
Presents a brief overview of distributed object systems Provides a brief overview of RMI and CORBA Gives you a flavor of the effort involved in developing applications in RMI and CORBA Shows how to transfer files from remote machines using RMI and CORBA Provides a brief comparison of RMI and Corba
The Client / Server Model
The client / server model is a form of distributed computing in which one program (the client) communicates with another program (the server) for the purpose of exchanging information In this model, both the client and server usually speak the same language. - a protocol that both the client and server understand - so. is able to communication.
While the client / server model can be implemented in various ways, it is typically done using low-level sockets. Using sockets to develop client / server systems means that we must design a protocol, which is a set of commands agreed upon by the client and server through which they will be able to communicate. As an example, consider the HTTP protocol that provides a method called GET, which must be implemented by all web servers and used by web clients (browsers) in order to retrieve documents.The Distributed Objects model
A distributed object-based system is a collection of objects that isolates the requesters of services (clients) from the providers of services (servers) by a well-defined encapsulating interface. In other words, clients are isolated from the implementation of services as data ............... ..
In the distributed object-based model, a client sends a message to an object, which in turns interprets the message to decide what service to perform. This service, or method, selection could be performed by either the object or a broker. The Java ...........................
RMI
RMI is a distributed object system that enables you to easily develop distributed Java applications. Developing distributed applications in RMI is simpler than developing with sockets since there is no need to design a protocol, which is an error-prone task. In RMI, the developer has the illusion of calling a local method from a local class file, when in fact the arguments are shipped to the remote target and interpreted, and the results are sent back to the callers.The Genesis of an RMI Application
Developing a Distributed Application Using RMI Involves The Following Steps:
DEFINE A Remote Interface Implement The Remote Interface Develop The Server Develop A Client Generate Stubeletons, Start The Rmi Registry, Server, and Client
We will now Examine these Steps Through The Development of a File Transfer Application.
Example: File Transfer Application
This application allows a client to transfer (or download) any type of file (plain text or binary) from a remote machine. The first step is to define a remote interface that specifies the signatures of the methods to be provided by the server and invoked BY Clients.
Define a Remote Interface
The remote interface for the file download application is shown in Code Sample 1. The interface FileInterface provides one method downloadFile that takes a String argument (the name of the file) and returns the data of the file as an array of bytes.
Code Sample 1: FileInterface.java
Import java.rmi.remote;
Import java.rmi.remoteexception;
Public interface fileInterface extends remote {
Public Byte [] Downloadfile (String FileName) Throws
RemoteException;
}
Note The Following Characteristics About The FileInterface:
It must be declared public, in order for clients to be able to load remote objects which implement the remote interface. It must extend the Remote interface, to fulfill the requirement for making the object a remote one. Each method in the interface must throw a Java.rmi.RemoteException.Implement the remote interface
The next step is to implement the interface FileInterface. A sample implementation is shown in Code Sample 2. Note that in addition to implementing the FileInterface, the FileImpl class is extending the UnicastRemoteObject. This indicates that the FileImpl class is used to create a single, Non-Replicated, Remote Object That Uses Rmi's Default Tcp-based Transport for Communication.
Code Sample 2: fileImpl.java
Import java.io. *;
Import java.rmi. *;
Import java.rmi.server.UnicastRemoteObject;
Public Class FileImpl Extends UnicastRemoteObject
Implements fileInterface {
PRIVATE STRING NAME;
Public fileIMPL (String s) throws remoteexception {
Super ();
Name = s;
}
Public Byte [] Downloadfile (String FileName) {
Try {
File File = New File (filename);
BYTE BUFFER [] = new byte [(int) file.length ()];
BufferedInputStream Input = New
BufferedInputStream (New FileInputStream (FileName);
Input.read (Buffer, 0, Buffer.Length);
INPUT.CLOSE ();
Return (Buffer);
} catch (exception e) {
System.out.println ("FileImpl:" E.getMessage ());
E.PrintStackTrace ();
Return (NULL);
}
}
}
Develop The Server
THIRD Step is to develop a server. There are Three Things That The Server Needs to do:
Create an instance of the RMISecurityManager and install it Create an instance of the remote object (FileImpl in this case) Register the object created with the RMI registry A sample implementation is shown in Code Sample 3.Code Sample 3:. FileServer.java
Import java.io. *;
Import java.rmi. *;
Public class fileserver {
Public static void main (String Argv []) {
IF (system.getsecuritymanager () == null) {
System.SetSecurityManager (New RMISecurityManager ());
}
Try {
FileInterface FI = New FileImpl ("FileServer");
Naming.rebind ("// 127.0.0.1/fileserver", fi);
} catch (exception e) {
System.out.println ("FileServer:" E.getMessage ());
E.PrintStackTrace ();
}
}
}
The statement Naming.rebind ( "// 127.0.0.1/FileServer", fi) assumes that the RMI registry is running on the default port number, which is 1099. However, if you run the RMI registry on a different port number it must Be Specified in That Statement. for Example, IF The RMI Registry Is Running on Port 4500, The Statement Becomes:
Naming.rebind ("// 127.0.0.1:4500/fileserver", fi)
Also, IT Is Important To Note Here That We Assute The RMI Registry and The Server Will Be Running on The Same Machine. IF The ARE NOT, The Rebind Method.
Develop aclient
The next step is to develop a client. The client remotely invokes any methods specified in the remote interface (FileInterface). To do so however, the client must first obtain a reference to the remote object from the RMI registry. Once a reference is obtained , the downloadFile method is invoked A client implementation is shown in Code Sample 4. in this implementation, the client accepts two arguments at the command line:. the first one is the name of the file to be downloaded and the second one is the address Of the machine from which the file is to be downloaded, which is the machine That Is Running the file server.code sample 4: fileclient.java
Import java.io. *;
Import java.rmi. *;
Public class fileclient {
Public static void main (String Argv []) {
IF (argv.length! = 2) {
System.out.println ("USAGE: Java FileClient FileName Machinename);
System.exit (0);
}
Try {
String name = "//" argv [1] "/ fileserver";
FileInterface Fi = (fileInterface) Naming.lookup (name);
Byte [] filedata = fi.downloadfile (Argv [0]);
File File = New File (Argv [0]);
BufferedoutputStream Output = New
BufferedoutputStream (New FileoutputStream (file.getname ()));
Output.write (FileData, 0, FileData.Length);
Output.flush ();
Output.close ();
} catch (exception e) {
System.err.Println ("FileServer Exception:" E.GetMessage ());
E.PrintStackTrace ();
}
}
}
Running the application
.
To Generate Stubs and Skeletons, Use the RMIC Compiler:
Prompt> RMIC FileImpl
This will generate two files: FileImpl_Stub.class and FileImpl_Skel.class The stub is a client proxy and the skeleton is a server skeleton.The next step is to compile the server and the client Use the javac compiler to do this Note however... If The Server and Client Are Developed on Two DiffERENT MACHINES, IN ORDER TO Compile The Client You NEED A COPY OF THE INTERFACE (FileInterface).
Finally, it is time to start the RMI registry and run the server and client. To start the RMI registry on the default port number, use the command rmiregistry or start rmiregistry on Windows. To start the RMI registry on a different port number, provide The Port Number as an argument to the rmi registry:
Prompt> RMIREGISTRY Portnumber
Once the RMI registry is running, you can start the server FileServer However, since the RMI security manager is being used in the server application, you need a security policy to go with it Here is a sample security policy..:
Grant {
Permission java.security.Allpermission "" ""
}
Note: This is Just A Sample Policy. It allows anyone to do anything. For your mission critical application, you need to specify More Constraint Security Policies.
Now, in order to start the server you need a copy of all the classes (including stubs and skeletons) except the client class (FileClient.class). To start the server use the following command, assuming that the security policy is in a file Named policy.txt:
Prompt> java -djava.security.policy = policy.txt FileServer
To Start The Client ON A Different Machine, You NEED A COPY OF THE Remote Interface (FileInterface.class) and stub (fileImpl_stub.class). To start the client use the command:
prompt> java FileClient fileName machineNamewhere fileName is the file to be downloaded and machineName is the machine where the file is located (the same machine runs the file server). If everything goes ok then the client exists and the file downloaded is on the local machine .
To run the client we mentioned that you need a copy of the interface and stub. A more appropriate way to do this is to use RMI dynamic class loading. The idea is you do not need copies of the interface and the stub. Instead, they can be located in a shared directory for the server and the client, and whenever a stub or a skeleton is needed, it is downloaded automatically by the RMI class loader To do this you run the client, for example, using the following command.: Java -djava.rmi.server.codebase = http:// hostname / locationOfClasses FileClient FileName Machinename. For more information on this, please see Dynamic Code Loading Using RMI.
Corba
The Common Object Request Broker Architecture (or CORBA) is an industry standard developed by the Object Management Group (OMG) to aid in distributed objects programming. It is important to note that CORBA is simply a specification. A CORBA implementation is known as an ORB (or Object Request Broker). There are several CORBA implementations available on the market such as VisiBroker, ORBIX, and others. JavaIDL is another implementation that comes as a core package with the JDK1.3 or above.
CORBA was designed to be platform and language independent. Therefore, CORBA objects can run on any platform, located anywhere on the network, and can be written in any language that has Interface Definition Language (IDL) mappings.
Similar to RMI, CORBA objects are specified with interfaces. Interfaces in CORBA, however, are specified in IDL. While IDL is similar to C , it is important to note that IDL is not a programming language. For a detailed introduction to CORBA, please See Distributed Programming with Java: Chapter 11 (Overview of Corba) .The Genesis of a CORBA Application
There Are A Number of Stes Involved in Developing Corba Applications. Thase Are:
....................... ..
We now explain each step by walking you through the development of a CORBA-based file transfer application, which is similar to the RMI application we developed earlier in this article. Here we will be using the JavaIDL, which is a core package of JDK1. 3 .
Define the interface
When defining a CORBA interface, think about the type of operations that the server will support. In the file transfer application, the client will invoke a method to download a file. Code Sample 5 shows the interface for FileInterface. Data is a new type introduced Using the TypedEf Keyword. A SEQUENCE IN IDL IS SIMILAR TO ARRAY EXCEPT THAT A SEQUENCE DOS NOT HAVE A FIXED SIZE. An OcTet IS An 8-bit Quantity That Is Equivalent to the Java Type Byte.
Note that the downloadFile method takes one parameter of type string that is declared in IDL defines three parameter-passing modes:. In (for input from client to server), out (for output from server to client), and inout (used for both Input and output.
Code Sample 5: FileInterface.IDL
Interface fileInterface {
TypedEf sequern
Data Downloadfile (in string filename);
Once You Finish Defining The Idl Interface, You Are Ready To Compile It. The JDK1.3 Comes with The Idlj Compiler, Which IS Used To Map IDL Definitions Into Java Declarations and Statements.
The idlj compiler accepts options that allow you to specify if you wish to generate client stubs, server skeletons, or both. The -f
Now, Let's Compile The FileInterface.idl and generate Server-Side Skeletons. Using the command:
Prompt> idlj -fserver fileInterface.idl
This command generates several files such as skeletons, holder and helper classes, and others. An important file that gets generated is the _FileInterfaceImplBase, which will be subclassed by the class that implements the interface.
IMPLEMENT The Interface
Now, we provide an implementation to the downloadFile method. This implementation is known as a servant, and as you can see from Code Sample 6, the class FileServant extends the _FileInterfaceImplBase class to specify that this servant is a CORBA object.
Code Sample 6: FileServant.java
Import java.io. *;
Public class fileservant extends _fileinterfaceImplbase {
Public Byte [] Downloadfile (String FileName) {
File File = New File (filename);
BYTE BUFFER [] = new byte [(int) file.length ()];
Try {
BufferedInputStream Input = New
BufferedInputStream (New FileInputStream (FileName);
Input.read (Buffer, 0, Buffer.Length);
INPUT.CLOSE ();
} catCH (Exception E) {system.out.println ("FileServant Error:" E.getMessage ());
E.PrintStackTrace ();
}
Return (Buffer);
}
}
Develop The Server
The next Step is developing The Corba Server. The File Server Class, Shown In Core Sample 7, Implements a CORBA Server That DoLLOWING:
Initializes The Orb Creates A FileServant Object Registers The Object In The Corba Naming Service (COS Naming) Prints A Status Message Waits for Incoming Client Requests
Code Sample 7: FILESERVER.JAVA
Import java.io. *;
Import org.omg.cosnaming. *;
Import Org.omg.cosnaming.namingContextPackage. *;
Import org.omg.corba. *;
Public class fileserver {
Public static void main (string args []) {
Try {
// Create and Initialize the ORB
ORB ORB = Orb.init (args, null);
// Create the servant and register it with the orb
FileServant FileRef = New FileServant ();
Orb.connect (fileRef);
// Get the root naming context
Org.omg.corba.Object objref =
Orb.resolve_initial_references ("Nameservice");
NamingContext ncref = NamingContextHelper.narrow (Objref);
// bind the object reason in naming
NameComponent NC = New NameComponent ("FileTransfer", ""
Namecomponent path [] = {nc};
Ncref.rebind (path, fileref);
System.out.Println ("Server Started ....");
// Wait for Invocations from Clom Clom Clom Clom Clom Clom Clom Cliants
Java.lang.object sync = new java.lang.Object ();
Synchronized (sync) {
Sync.wait ();
}
} catch (exception e) {
System.err.Println ("Error:" E.GetMessage ());
E.PrintStackTrace (System.out);
}
}
}
Once the FileServer has an ORB, it can register the CORBA service. It uses the COS Naming Service specified by OMG and implemented by Java IDL to do the registration. It starts by getting a reference to the root of the naming service. This returns a . generic CORBA object to use it as a NamingContext object, it must be narrowed down (in other words, casted) to its proper type, and this is done using the statement: NamingContext ncRef = NamingContextHelper.narrow (objRef);
. ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
Develop aclient
The next step is to develop a client. An implementation is shown in Code Sample 8. Once a reference to the naming service has been obtained, it can be used to access the naming service and find other services (for example the FileTransfer service). When the FileTransfer Service Is Found, The Downloadfile Method Is Invoked.
Code Sample 8: FileClient
Import java.io. *;
Import java.util. *;
Import org.omg.cosnaming. *;
Import org.omg.corba. *;
Public class fileclient {
Public static void main (String Argv []) {
Try {
// Create and Initialize the ORB
ORB ORB = Orb.init (Argv, Null);
// Get the root naming context
Org.omg.corba.Object objref =
Orb.resolve_initial_references ("Nameservice");
NamingContext ncref = NamingContextHelper.narrow (Objref);
NameComponent NC = New NameComponent ("FileTransfer", ""
// resolve the object reference in naming
Namecomponent path [] = {nc};
FileInterfaceOperations FileRef =
FileInterfaceHelper.Narrow (ncref.resolve (path));
IF (argv.length <1) {
System.out.println ("USAGE: JAVA FileClient FileName);
// Save the file
File File = New File (Argv [0]);
Byte data [] = fileref.downloadfile (argv [0]);
BufferedoutputStream Output = New
BufferedOutputStream (New FileoutputStream (Argv [0]));
Output.write (Data, 0, Data.length);
Output.flush ();
Output.close ();
} catch (exception e) {
System.out.println ("FileClient Error:" E.getMessage ());
E.PrintStackTrace ();
}
}
}
Running the application
The final step is to run the application. Theere several subs-steps involved:
Running the the CORBA naming service. This can be done using the command tnameserv. By default, it runs on port 900. If you can not run the naming service on this port, then you can start it on another port. To start it on port 2500, for example, use the following command: prompt> tnameserv -ORBinitialPort 2500 Start the server This can be done as follows, assuming that the naming service is running on the default port number:. prompt> java FileServer If the naming service is running on a different port number, say 2500, then you need to specify the port using the ORBInitialPort option as follows:. prompt> java FileServer -ORBInitialPort 2500 Generate stubs for the client Before we can run the client, we need to generate stubs for the . client to do that, get a copy of the FileInterface.idl file and compile it using the idlj compiler specifying that you wish to generate client-side stubs, as follows: prompt> idlj -fclient FileInterface.idl Run the client Now you. Can Run The Client USIN g the following command, assuming that the naming service is running on port 2500. prompt> java FileClient hello.txt -ORBInitialPort 2500 Where hello.txt is the file we wish to download from the server.Note: if the naming service is running on . a different host, then use the -ORBInitialHost option to specify where it is running For example, if the naming service is running on port number 4500 on a host with the name gosling, then you start the client as follows:
Prompt> java fileclient hello.txt -orbinitialhost gosling -orbinitialport 4500
Alternatively, these Options Can Be Specified At The Code Level Using Properties. So instead of initializing the orb as:
ORB ORB = Orb.init (Argv, Null);
IT can be initialized specifying what the corba server machine (called gosling) and the name service's port number (to be 2500) as Follows: Properties PROPS = New Properties ();
Props.Put ("Org.omg.Corba.orbinitialHost", "Gosling");
Props.Put ("ORB.OMG.CORBA.ORBINITIALPORT", "2500");
ORB ORB = Orb.init (args, props);
Exercise
In the file transfer application, the client (in both cases RMI and CORBA) needs to know the name of the file to be downloaded in advance. No methods are provided to list the files available on the server. As an exercise, you may want to enhance the application by adding another method that lists the files available on the server. Also, instead of using a command-line client you may want to develop a GUI-based client. When the client starts up, it invokes a method on the Server to get a list of files the files available a menu displaying the files available to select one or more files to be downloaded as shown in Figure 1.
Figure 1: gui-based file transfer client
CORBA vs. RMI
Code-wise, it is clear that RMI is simpler to work with since the Java developer does not need to be familiar with the Interface Definition Language (IDL) In general, however, CORBA differs from RMI in the following areas.:
CORBA interfaces are defined in IDL and RMI interfaces are defined in Java. RMI-IIOP allows you to write all interfaces in Java (see RMI-IIOP). CORBA supports in and out parameters, while RMI does not since local objects are passed by copy and remote objects are passed by reference. CORBA was designed with language independence in mind. This means that some of the objects can be written in Java, for example, and other objects can be written in C and yet they all can interoperate. Therefore, CORBA is an ideal mechanism for bridging islands between different programming languages. On the other hand, RMI was designed for a single language where all objects are written in Java. Note however, with RMI-IIOP it is possible to achieve interoperability. CORBA objects are not garbage collected. As we mentioned, CORBA is language independent and some languages (C for example) does not support garbage collection. This can be considered a disadvantage since once a CORBA object is created, it co Ntinues to EXIST Until you get rid of it
Developing distributed object-based applications can be done in Java using RMI or JavaIDL (an implementation of CORBA). The use of both technologies is similar since the first step is to define an interface for the object. Unlike RMI, however, where interfaces are defined in Java, CORBA interfaces are defined in the Interface Definition Language (IDL). This, however, adds another layer of complexity where the developer needs to be familiar with IDL, and equally important, its mapping to Java.