0% found this document useful (0 votes)
19 views24 pages

Unit 3 RMI

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views24 pages

Unit 3 RMI

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

UNIT 3 RMI

RMI stands for Remote Method Invocation. It is a mechanism that allows an


object residing in one system (JVM) to access/invoke an object running on
another JVM.

RMI is used to build distributed applications; it provides remote communication


between Java programs. It is provided in the package java.rmi.

Architecture of an RMI Application

In an RMI application, we write two programs, a server program (resides on the


server) and a client program (resides on the client).

 Inside the server program, a remote object is created and reference of that
object is made available for the client (using the registry).
 The client program requests the remote objects on the server and tries to
invoke its methods.

The following diagram shows the architecture of an RMI application.

Let us now discuss the components of this architecture.


 Transport Layer − This layer connects the client and the server. It
manages the existing connection and also sets up new connections.
 Stub − A stub is a representation (proxy) of the remote object at client. It
resides in the client system; it acts as a gateway for the client program.
 Skeleton − This is the object which resides on the server
side. stub communicates with this skeleton to pass request to the remote
object.
 RRL(Remote Reference Layer) − It is the layer which manages the
references made by the client to the remote object.

Designing RMI application

To write an RMI Java application, you would have to follow the steps given
below −

 Define the remote interface


 Develop the implementation class (remote object)
 Develop the server program
 Develop the client program
 Compile the application
 Execute the application

Defining the Remote Interface

A remote interface provides the description of all the methods of a particular


remote object. The client communicates with this remote interface.

To create a remote interface −

 Create an interface that extends the predefined interface Remote which


belongs to the package.
 Declare all the business methods that can be invoked by the client in this
interface.
 Since there is a chance of network issues during remote calls, an
exception named RemoteException may occur; throw it.

Following is an example of a remote interface. Here we have defined an


interface with the name Hello and it has a method called printMsg().
import java.rmi.Remote;
import java.rmi.RemoteException;

// Creating Remote interface for our application


public interface Hello extends Remote {
void printMsg() throws RemoteException;
}

Developing the Implementation Class (Remote Object)

We need to implement the remote interface created in the earlier step. (We can
write an implementation class separately or we can directly make the server
program implement this interface.)

To develop an implementation class –

 Implement the interface created in the previous step.


 Provide implementation to all the abstract methods of the remote
interface.

Following is an implementation class. Here, we have created a class


named ImplExample and implemented the interface Hello created in the
previous step and provided body for this method which prints a message.

// Implementing the remote interface


public class ImplExample implements Hello {

// Implementing the interface method


public void printMsg() {
System.out.println("This is an example RMI program");
}
}

Developing the Server Program

An RMI server program should implement the remote interface or extend the
implementation class. Here, we should create a remote object and bind it to
the RMIregistry.
To develop a server program −

 Create a client class from where you want invoke the remote object.
 Create a remote object by instantiating the implementation class as shown
below.
 Export the remote object using the method exportObject() of the class
named UnicastRemoteObject which belongs to the
package java.rmi.server.
 Get the RMI registry using the getRegistry() method of
the LocateRegistry class which belongs to the package java.rmi.registry.
 Bind the remote object created to the registry using the bind() method of
the class named Registry. To this method, pass a string representing the
bind name and the object exported, as parameters.

Following is an example of an RMI server program.

import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class Server extends ImplExample {


public Server() {}
public static void main(String args[]) {
try {
// Instantiating the implementation class
ImplExample obj = new ImplExample();

// Exporting the object of implementation class


// (here we are exporting the remote object to the stub)
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);

// Binding the remote object (stub) in the registry


Registry registry = LocateRegistry.getRegistry();

registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}

Developing the Client Program

Write a client program in it, fetch the remote object and invoke the required
method using this object.

To develop a client program −

 Create a client class from where your intended to invoke the remote
object.
 Get the RMI registry using the getRegistry() method of
the LocateRegistry class which belongs to the package java.rmi.registry.
 Fetch the object from the registry using the method lookup() of the
class Registry which belongs to the package java.rmi.registry.
To this method, you need to pass a string value representing the bind
name as a parameter. This will return you the remote object.
 The lookup() returns an object of type remote, down cast it to the type
Hello.
 Finally invoke the required method using the obtained remote object.

Following is an example of an RMI client program.

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

public class Client {


private Client() {}
public static void main(String[] args) {
try {
// Getting the registry
Registry registry = LocateRegistry.getRegistry(null);

// Looking up the registry for the remote object


Hello stub = (Hello) registry.lookup("Hello");
// Calling the remote method using the obtained object
stub.printMsg();

// System.out.println("Remote method invoked");


} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}

Compiling the Application

To compile the application −

 Compile the Remote interface.


 Compile the implementation class.
 Compile the server program.
 Compile the client program.

Or,
Open the folder where you have stored all the programs and compile all
the Java files as shown below.
Javac *.java

Executing RMI application

Step 1 − Start the rmi registry using the following command.


start rmiregistry

This will start an rmi registry on a separate window as shown below.

Step 2 − Run the server class file as shown below.

Java Server

Step 3 − Run the client class file as shown below.

java Client
Verification − As soon you start the client, you would see the following output
in the server.

JavaBean

A JavaBean is a Java class that should follow the following conventions:

o It should have a no-arg constructor.


o It should be Serializable.
o It should provide methods to set and get the values of the properties, known
as getter and setter methods.

Why use JavaBean?

According to Java white paper, it is a reusable software component. A bean


encapsulates many objects into one object so that we can access this object from
multiple places. Moreover, it provides easy maintenance.
Simple example of JavaBean class

//Employee.java

package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}

How to access the JavaBean class?

To access the JavaBean class, we should use getter and setter methods.

package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}}

JavaBean Properties

A JavaBean property is a named feature that can be accessed by the user of the
object. The feature can be of any Java data type, containing the classes that you
define.

ad, write, read-only, or write-only. JavaBean features are accessed through two
methods in the JavaBean's implementation class:

1. getPropertyName ()
For example, if the property name is firstName, the method name would be
getFirstName() to read that property. This method is called the accessor.

2. setPropertyName ()

For example, if the property name is firstName, the method name would be
setFirstName() to write that property. This method is called the mutator.

Advantages of JavaBean

The following are the advantages of JavaBean:/p>

o The JavaBean properties and methods can be exposed to another


application.
o It provides an easiness to reuse the software components.

Disadvantages of JavaBean

The following are the disadvantages of JavaBean:

o JavaBeans are mutable. So, it can't take advantages of immutable objects.


o Creating the setter and getter method for each property separately may lead
to the boilerplate code.

Introspection

Introspection is the automatic process of analyzing a bean's design patterns to


reveal the bean's properties, events, and methods. This process controls the
publishing and discovery of bean operations and properties. This lesson
explains the purpose of introspection, introduces the Introspection API, and
gives an example of introspection code.

Purpose of Introspection

A growing number of Java object repository sites exist on the Internet in answer
to the demand for centralized deployment of applets, classes, and source code in
general. Any developer who has spent time hunting through these sites for
licensable Java code to incorporate into a program has undoubtedly struggled
with issues of how to quickly and cleanly integrate code from one particular
source into an application.

The way in which introspection is implemented provides great advantages,


including:

1. Portability - Everything is done in the Java platform, so you can write


components once, reuse them everywhere. There are no extra
specification files that need to be maintained independently from your
component code. There are no platform-specific issues to contend with.
Your component is not tied to one component model or one proprietary
platform. You get all the advantages of the evolving Java APIs, while
maintaining the portability of your components.
2. Reuse - By following the JavaBeans design conventions, implementing
the appropriate interfaces, and extending the appropriate classes, you
provide your component with reuse potential that possibly exceeds your
expectations.

Introspection API
The JavaBeans API architecture supplies a set of classes and interfaces to
provide introspection.

The BeanInfo (in the API reference documentation) interface of


the java.beans package defines a set of methods that allow bean implementors
to provide explicit information about their beans. By specifying BeanInfo for a
bean component, a developer can hide methods, specify an icon for the toolbox,
provide descriptive names for properties, define which properties are bound
properties, and much more.

The getBeanInfo(beanName) (in the API reference documentation) of


the Introspector (in the API reference documentation) class can be used by
builder tools and other automated environments to provide detailed information
about a bean. The getBeanInfo method relies on the naming conventions for the
bean's properties, events, and methods. A call to getBeanInfo results in the
introspection process analyzing the bean�s classes and superclasses.

The Introspector class provides descriptor classes with information about


properties, events, and methods of a bean. Methods of this class locate any
descriptor information that has been explicitly supplied by the developer
through BeanInfo classes. Then the Introspector class applies the naming
conventions to determine what properties the bean has, the events to which it
can listen, and those which it can send.
The following figure represents a hierarchy of the FeatureDescriptor classes:

Each class represented in this group describes a particular attribute of the bean.
For example, the isBound method of the PropertyDescriptor class indicates
whether a PropertyChangeEvent event is fired when the value of this property
changes.

Editing Bean Info with the NetBeans BeanInfo Editor

To open the BeanInfo dialog box, expand the appropriate class hierarchy to the
bean Patterns node. Right-click the bean Patterns node and choose BeanInfo
Editor from the pop-up menu. All elements of the selected class that match
bean-naming conventions will be displayed at the left in the BeanInfo Editor
dialog box as shown in the following figure:
Select one of the following nodes to view and edit its properties at the right of
the dialog box:

 BeanInfo
 Bean
 Properties
 Methods
 Event Sources

Special symbols (green and red) appear next to the subnode to indicate whether
an element will be included or excluded from the BeanInfo class.

If the Get From Introspection option is not selected, the node's subnodes are
available for inclusion in the BeanInfo class. To include all subnodes, right-
click a node and choose Include All. You can also include each element
individually by selecting its subnode and setting the Include in BeanInfo
property. If the Get From Introspection option is selected, the setting the
properties of subnodes has no effect in the generated BeanInfo code.

The following attributes are available for the nodes for each bean, property,
event sources, and method:

 Name - A name of the selected element as it appears in code.


 Preferred - An attribute to specify where this property appears in the
Inspector window under the Properties node.
 Expert - An attribute to specify where this property appears in the
Inspector window under the Other Properties node.
 Hidden - An attribute to mark an element for tool use only.
 Display Name Code - A display name of the property.
 Short Description Code - A short description of the property.
 Include in BeanInfo - An attribute to include the selected element in
the BeanInfo class.
 Bound - An attribute to make the bean property bound.
 Constrained - An attribute to make the bean property constrained.
 Mode - An attribute to set the property's mode and generate getter and
setter methods.
 Property Editor Class - An attribute to specify a custom class to act as a
property editor for the property.

For Event Source nodes, the following Expert properties are available:

 Unicast (read-only)
 In Default Event Set

Introspection Sample
The following example represents code to perform introspection:
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;

public class SimpleBean


{
private final String name = "SimpleBean";
private int size;

public String getName()


{
return this.name;
}

public int getSize()


{
return this.size;
}

public void setSize( int size )


{
this.size = size;
}

public static void main( String[] args )


throws IntrospectionException
{
BeanInfo info = Introspector.getBeanInfo( SimpleBean.class );
for ( PropertyDescriptor pd : info.getPropertyDescriptors() )
System.out.println( pd.getName() );
}
}

This example creates a non-visual bean and displays the following properties
derived from the BeanInfo object:

 class
 name
 size

Note that a class property was not defined in the SimpleBean class. This
property was inherited from the Object class. To get properties defined only in
the SimpleBean class, use the following form of the getBeanInfo method:

Introspector.getBeanInfo( SimpleBean.class, Object.class );

The Bean Developer Kit (BDK)

The Bean Developer Kit (BDK), available from the Java Soft site, is a simple
example of a tool that enables you to create, configure, and connect a set of
Beans. There is also a set of sample Beans with their source code. This section
provides-step-by-step instructions for installing and using this tool.
‘In this chapter, instructions are provided for a Windows 95/98/NT environment.
The procedure» for a.UNIX platform are similar, some of the commands arc
different.
Installing the BDK
The JDK must be installed on your machine for the DDKto work. Confirm that
the JOK tools are accessible from your environment. The’BDK can then be
downloaded from the Java Soft site’ (http://java.sun.com).Itis packaged as one
file that is a self-extracting archive. Follow the instructions to install it on tour
machine.
Starting the BDK
To start the DDK, follow these steps:
1. Change to the directory c:\bdk\beanbox.
2. Execute the batcl(·file called run.bat. This causes the BDK to display the
three windows shown Toolbox lists allof the different Beans that have been
included with the BDK. Bean Box provides an area to layout and connect the
Beans selected from the Too Box. Properties .
Using the BDK
This section describes how to create an application by using some of the Beans
provided with the BDK. First, the Molecule Bean displays at three-dimensional
view of a molecule. It may be configured to present one of the following
molecules: hy ironical. acid, benzene, counterintelligence, anticyclone, ethane, or
water. This compos net also has methods that allow the molecule to be rotated in
space along its X or Y axis. -Second, the Our Bean provides a push-button
functionality. We will have one.
Create and Configure an Instance of the ,Molecule Bean

Follow these steps to create o,.md configu.re an instance of the Molecule Bean.

1. Position the cursor on ‘the Tool Box entry labeled Molecule and click the left
mouse button. You should see the cursor change to a cross.
2. Move the cursor to the Bean Box display area and click the left mouse button
in
approximately the area where you wish the Bean to be displayed. You should
see a rectangular region appear that contains a display of a molecule. This
areas surrounded by a hatched. border, indicating that it is currently selected.
3. You can preposition the Molecule Bean by positioning the cursor over one of
the
hatched borders and dragging the Bean.
4. You can change the molecule that is displayed by changing the selection in the
Properties window. Notice that the Bean display changes immediately when
you change the selected molecule.

JAR file (Java Archive)





What is a JAR file (Java Archive)?


A Java Archive, or JAR file, contains all of the various components that make
up a self-contained, executable Java application, deployable Java applet or,
most commonly, a Java library to which any Java Runtime Environment can
link.

There are two key benefits of using a JAR file. The first is the ability to
aggregate hundreds, if not thousands, of different files that make up an
application. The second is the means to compress all of the contained files,
greatly reducing the size of the application, and making it easier to move the
JAR file over a network and between environments.

Contents of a JAR file


Java applications and libraries can contain hundreds of different files, including
compiled Java source code, a manifest file, XML-based configuration
data, JSON-based data files, images, sound clips and even security certificates.
A JAR file is simply an aggregation of all of these resources into a single,
compressed file.

Since a JAR file uses a standard compression algorithm, opening a JAR file is
as simple as changing its extension from .jar to .zip and extracting the
contents using a standard decompression tool.
Opening a
JAR file and exploring the contents

Although optional, it is recommended that JAR files contain a manifest file


named MANIFEST.MF in a folder named META-INF. This manifest file
contains metadata about the JAR, including properties such as the code version,
the primary author of the code and the name of the organization that maintains
the code.

Executable JAR files


For an executable JAR file that contains a stand-alone application, a Main-
Class attribute should exist that provides the name of the first piece of code for
the Java Runtime Environment (JRE) to invoke when the application is run.
Manifest
file MANIFEST.MF for the open source hibernate3.jar file
Java Archive apps
Each installation of the Java Development Kit (JDK) includes a
JAR utility (named jar.sh on Unix and jar.exe on Windows) that provides a
variety of helpful functions for working with JAR files, including the ability to:

 create new JAR files with a manifest file;


 extract all of the contents of a JAR file onto the file system;
 update an existing JAR file by adding files to it; and
 update a JAR file's existing manifest file
JAR file openers
To open a JAR file and extract the contents to the file system, you must use two
JAR utility switches, namely, "x" to extract the contents, and "f" to specify the
name of the JAR file being opened. The utility then extracts the contents to the
file system.

For example, the JAR utility command to extract the contents of a JAR file
named my_java_app.jar looks as follows:

> jar xf C:\techtarget\my_java_app.jar

The Java JAR command


The JAR utility can also help create a JAR file. To create a JAR file named
tss.jar that includes two files named Tech.class and Target.class, the command
looks as follows:

> jar cf tss.jar Tech.class Target.class

How to run a JAR files


Any Java code that has a method called "main" is considered to be a stand-alone
application. For example, the code below has a main method that triggers a
dialog box to pop up that says "Hello World" in it.

package theserverside;
import javax.swing.*;

public class HelloWorldApplication {

public static void main(String args[]){

String title = "Executable Java Application";

String message = "Hello World!";

JOptionPane.showMessageDialog(null, message, title, 1);

If this code was packaged in a JAR file, the JAR file would execute it because it
contains code that can be run directly by the JRE. However, to run the
executable JAR file, you don't use the JAR utility of the JDK. Instead, you use
the special java.exe utility, and, thus, the name of the jar file is specified.
The syntax to run an executable JAR file named my_java_app.jar using the
JDK's java.exe utility is as follows:

> java.exe -jar my_java_app.jar

Developing Beans using BDK

Following steps to be adopted to create a new Bean:

 Create the Java source file.

 Compile the source file.

 Create a manifest file.

 Generate a JAR file.

 Start the BDK.

 Test.

This example creates a simple bean button


Diagram 25.9 Type run in the command prompt

Working of the Code:

To create a bean, type the above code and save it as SimpleBean.java. Comiple
the above code using the javac.exe compiler as under:

javac SimpleBean.java

Create a manifest file with a .mf extension as under. The Manifest file is a text
file which contains the name of the class file.

SimpleBean.mf
Name: SimpleBean.class
Java-Bean: True

Creating a jar (Java Archive) file

As you are aware that javac.exe creates a separate .class file for every class
defined in the program. Hence, if a program has five classes, the compiler will
create five class file each with their respective name and a .class extension.

This proved to be drawback as the applet loader makes separate connections for
each file while loading the applet. To overcome this problem, the engineers at
Java Soft, the Sun Microsystems subsidiary for Java introduced the idea fo
compressing all the files together which can be unzipped at the applet's client
machine when the applet executes.

Jar is a zip or compression utility tailored to Java's needs. Pass the names of all
the files in the project to the JAR utility, which compresses all of them together
and creates a compressed file with a .jar extension.

Usage of JAR is as under:

jar [-cvfmOM][jar-file name][manifest-file name] list of .class file


Options:
Options: Description
-c Creates a new archive.
-t List table of contents for archive.
-x Extracts named (or all) files from archive.
-f Specify archive file name.
-m Include manifest information from specified manifest file.
-O Store only: use no Zip compression.
-M Do not create a manifest file for the entries.

Creating a JAR file for the example code created eariler on.

This will create a jar file:SimpleBean.jar. Copy this file in the jars directory
under the BDK folder and start the Bean Box. The ToolBox of the Bean Box
now displays the bean created underline.

Diagram 25.10 The SimpleBean can be dragged and dropped in the


BeanBox

You might also like