unit 5

Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 66

Remote Method Invocation

 The main difference between a distributed and non-


distributed Java program is that a distributed program
is made up of multiple parts that work together across
a network, while a non-distributed program is a
standalone application that doesn't rely on a remote
service:
 Distributed programs
 These programs are made up of independent
computers, called nodes, that communicate with each
other over a network. Distributed systems can be used
to scale horizontally by adding more nodes to the
network. They can also be designed to be fault-
tolerant, so that if one node fails, the other nodes can
take over. Java is a popular language for building
distributed systems because of its portability, strong
typing, and rich libraries.
Non-distributed programs
These programs are standalone
applications that don't rely on a remote
service. Non-distributed applications are
generally simpler and require less
troubleshooting than distributed
applications
The RMI (Remote Method Invocation) is an
API that provides a mechanism to create
distributed application in java. The RMI
allows an object to invoke methods on an
object running in another JVM.

The RMI provides remote communication


between the applications using two
objects stub and skeleton.
• Remote Method Invocation (RMI) is an API that allows an
object to invoke a method on an object that exists in
another address space, which could be on the same
machine or on a remote machine. Through RMI, an object
running in a JVM present on a computer (Client-side) can
invoke methods on an object present in another JVM
(Server-side). RMI creates a public remote server object
that enables client and server-side communications
through simple method calls on the server object.

• Stub Object: The stub object on the client machine builds


an information block and sends this information to the
server.

• The block consists of


• An identifier of the remote object to be used
• Method name which is to be invoked
• Parameters to the remote JVM
Understanding stub and
skeleton

RMI uses stub and skeleton object for


communication with the remote object.
A remote object is an object whose
method can be invoked from another JVM.
Let's understand the stub and skeleton
objects:
Stub

• The stub is an object, acts as a gateway for the


client side. All the outgoing requests are routed
through it. It resides at the client side and
represents the remote object. When the caller
invokes method on the stub object, it does the
following tasks:
• It initiates a connection with remote Virtual
Machine (JVM),
• It writes and transmits (marshals) the
parameters to the remote Virtual Machine (JVM),
• It waits for the result
• It reads the return value or exception, and
• It finally, returns the value to the caller.
Skeleton

• The skeleton is an object, acts as a gateway for


the server side object. All the incoming requests
are routed through it. When the skeleton receives
the incoming request, it does the following tasks:
• It reads the parameter for the remote method
• It invokes the method on the actual remote
object, and
• It writes and transmits (marshals) the result to the
caller.
• In the Java 2 SDK, an stub protocol was introduced
that eliminates the need for skeletons.
Working of RMI
The communication between client and
server is handled by using two
intermediate objects: Stub object (on client
side) and Skeleton object (on server-side)
as also can be depicted from below media
as follows:
• These are the steps to be followed
sequentially to implement Interface as
defined below as follows:
• Defining a remote interface
• Implementing the remote interface
• Creating Stub and Skeleton objects from the
implementation class using rmic (RMI compiler)
• Start the rmiregistry
• Create and execute the server application
program
• Create and execute the client application
program
• Understanding requirements for the distributed
applications
• If any application performs these tasks, it can be
distributed application.
• .The application need to locate the remote
method
• It need to provide the communication with the
remote objects, and
• The application need to load the class definitions
for the objects.
• The RMI application have all these features, so it
is called the distributed application.
• Java RMI Example
• There is given the 6 steps to write the RMI
program.
• Create the remote interface
• Provide the implementation of the remote
interface
• Compile the implementation class and create the
stub and skeleton objects using the rmic tool
• Start the registry service by rmiregistry tool
• Create and start the remote application
• Create and start the client application

• RMI Example
• In this example, we have followed all the 6
steps to create and run the rmi application.
• The client application need only two files,
remote interface and client application.
• In the rmi application, both client and
server interacts with the remote interface.
• The client application invokes methods on
the proxy object, RMI sends the request to
the remote JVM.
• The return value is sent back to the proxy
object and then to the client application.
• 1) create the remote interface
• For creating the remote interface, extend the
Remote interface and declare the
RemoteException with all the methods of the
remote interface. Here, we are creating a remote
interface that extends the Remote interface.
There is only one method named add() and it
declares RemoteException.
• import java.rmi.*;
• public interface Adder extends Remote{
• public int add(int x,int y)throws RemoteExcep
tion;
• }
 A remote interface in Java is a marker interface
that defines a set of methods that can be called
from a remote Java virtual machine (JVM):
 Extends java.rmi.Remote
 A remote interface must extend the interface
java.rmi.Remote, either directly or indirectly.
 Declares remote methods
 Each method in a remote interface must declare
java.rmi.RemoteException in its throws clause, in
addition to any application-specific exceptions.
 Declares remote objects
 A remote object declared as a parameter or
return value must be declared as the remote
interface, not the implementation class.
• 2) Provide the implementation of the remote interface
• Now provide the implementation of the remote interface. For providing the
implementation of the Remote interface, we need to
• Either extend the UnicastRemoteObject class,
• or use the exportObject() method of the UnicastRemoteObject class
• In case, you extend the UnicastRemoteObject class, you must define a
constructor that declares RemoteException.
• import java.rmi.*;
• import java.rmi.server.*;
• public class AdderRemote extends UnicastRemoteObject implements Adder
{
• AdderRemote()throws RemoteException{
• super();
• }
• public int add(int x,int y){return x+y;}
• }

3) create the stub and skeleton objects
using the rmic tool.
Next step is to create stub and skeleton
objects using the rmi compiler. The rmic
tool invokes the RMI compiler and creates
stub and skeleton objects.
rmic AdderRemote
4) Start the registry service by the
rmiregistry tool
Now start the registry service by using the
rmiregistry tool. If you don't specify the
port number, it uses a default port number.
In this example, we are using the port
number 5000.
rmiregistry 5000
5) Create and run the server application
Now rmi services need to be hosted in a
server process. The Naming class provides
methods to get and store the remote
object. The Naming class provides 5
methods.
• In this example, we are binding the remote
object by the name GPP.
• import java.rmi.*;
• import java.rmi.registry.*;
• public class MyServer{
• public static void main(String args[]){
• try{
• Adder stub=new AdderRemote();
• Naming.rebind("rmi://localhost:5000/
GPP",stub);
• }catch(Exception e){System.out.println(e);}
• }
• }
• 6) Create and run the client application
• At the client we are getting the stub object by
the lookup() method of the Naming class and
invoking the method on this object. In this
example, we are running the server and client
applications, in the same machine so we are
using localhost. If you want to access the
remote object from another machine, change
the localhost to the host name (or IP address)
where the remote object is located.

• import java.rmi.*;
• public class MyClient{
• public static void main(String args[]){
• try{
• Adder stub=(Adder)Naming.lookup("rmi://
localhost:5000/sonoo");
• System.out.println(stub.add(34,4));
• }catch(Exception e){}
• }
• }
 Parameter Passing in Remote Method Invocation
 An argument to, or a return value from, a remote object can be any
object that is serializable. This includes primitive types, remote objects,
and non-remote objects that implement
the java.io.Serializable interface. For more details on how to make
classes serializable, see the "Java Object Serialization Specification."
Classes, for parameters or return values, that are not available locally
are downloaded dynamically by the RMI system. See the section
on "Dynamic Class Loading" for more information on how RMI
downloads parameter and return value classes when reading
parameters, return values and exceptions.

 Passing Non-remote Objects
 A non-remote object, that is passed as a parameter of a remote
method invocation or returned as a result of a remote method
invocation, is passed by copy; that is, the object is serialized
using the object serialization mechanism of the Java SE
platform.
 So, when a non-remote object is passed as an argument or
return value in a remote method invocation, the content of the
non-remote object is copied before invoking the call on the
remote object.
 When a non-remote object is returned from a remote method
invocation, a new object is created in the calling virtual
machine.
 Passing Remote Objects
 When passing an exported remote object as a parameter or
return value in a remote method call, the stub for that remote
object is passed instead. Remote objects that are not exported
will not be replaced with a stub instance. A remote object
passed as a parameter can only implement remote interfaces.
 2.6.3 Referential Integrity
 If two references to an object are passed from one JVM to
another JVM in parameters (or in the return value) in a single
remote method call and those references refer to the same
object in the sending JVM, those references will refer to a
single copy of the object in the receiving JVM. More generally
stated: within a single remote method call, the RMI system
maintains referential integrity among the objects passed as
parameters or as a return value in the call.
 2.6.4 Class Annotation
 When an object is sent from one JVM to another in a remote
method call, the RMI system annotates the class descriptor in
the call stream with information (the URL) of the class so that
the class can be loaded at the receiver. It is a requirement
that classes be downloaded on demand during remote method
invocation.
 2.6.5 Parameter Transmission
 Parameters in an RMI call are written to a stream that is a subclass of the
class java.io.ObjectOutputStream in order to serialize the parameters to the destination of the remote
call. The ObjectOutputStream subclass overrides the replaceObject method to replace each exported
remote object with its corresponding stub instance. Parameters that are objects are written to the
stream using the ObjectOutputStream's writeObject method. The ObjectOutputStream calls
the replaceObject method for each object written to the stream via the writeObject method (that
includes objects referenced by those objects that are written). The replaceObject method of RMI's
subclass of ObjectOutputStream returns the following:
 If the object passed to replaceObject is an instance of java.rmi.Remote and that object is exported to
the RMI runtime, then it returns the stub for the remote object. If the object is an instance
of java.rmi.Remote and the object is not exported to the RMI runtime, then replaceObject returns the
object itself. A stub for a remote object is obtained via a call to the
method java.rmi.server.RemoteObject.toStub.
 If the object passed to replaceObject is not an instance of java.rmi.Remote, then the object is simply
returned.
 RMI's subclass of ObjectOutputStream also implements the annotateClass method that annotates the
call stream with the location of the class so that it can be downloaded at the receiver. See the
section "Dynamic Class Loading" for more information on how annotateClass is used.
 Since parameters are written to a single ObjectOutputStream, references that refer to the same object
at the caller will refer to the same copy of the object at the receiver. At the receiver, parameters are
read by a single ObjectInputStream.
 Any other default behavior of ObjectOutputStream for writing objects (and
similarly ObjectInputStream for reading objects) is maintained in parameter passing. For example, the
calling of writeReplace when writing objects and readResolve when reading objects is honored by
RMI's parameter marshal and unmarshal streams.
 In a similar manner to parameter passing in RMI as described above, a return value (or exception) is
written to a subclass of ObjectOutputStream and has the same replacement behavior as parameter
transmission.
 2.6.5 Parameter Transmission
 Parameters in an RMI call are written to a stream that is a
subclass of the class java.io.ObjectOutputStream in order
to serialize the parameters to the destination of the
remote call. The ObjectOutputStream subclass overrides
the replaceObject method to replace each exported
remote object with its corresponding stub instance.
Parameters that are objects are written to the stream
using the ObjectOutputStream's writeObject method.
The ObjectOutputStream calls the replaceObject method
for each object written to the stream via
the writeObject method (that includes objects referenced
by those objects that are written).
The replaceObject method of RMI's subclass
of ObjectOutputStream returns the following:
 If the object passed to replaceObject is an instance
of java.rmi.Remote and that object is exported to the RMI runtime, then
it returns the stub for the remote object. If the object is an instance
of java.rmi.Remote and the object is not exported to the RMI runtime,
then replaceObject returns the object itself. A stub for a remote object
is obtained via a call to the
method java.rmi.server.RemoteObject.toStub.
 If the object passed to replaceObject is not an instance
of java.rmi.Remote, then the object is simply returned.
 RMI's subclass of ObjectOutputStream also implements
the annotateClass method that annotates the call stream with the
location of the class so that it can be downloaded at the receiver. See
the section "Dynamic Class Loading" for more information on
how annotateClass is used.
 Since parameters are written to a single ObjectOutputStream,
references that refer to the same object at the caller will refer to the
same copy of the object at the receiver. At the receiver, parameters
are read by a single ObjectInputStream.
 Any other default behavior
of ObjectOutputStream for writing objects (and
similarly ObjectInputStream for reading objects) is
maintained in parameter passing. For example, the
calling of writeReplace when writing objects
and readResolve when reading objects is honored
by RMI's parameter marshal and unmarshal
streams.
 In a similar manner to parameter passing in RMI as
described above, a return value (or exception) is
written to a subclass of ObjectOutputStream and
has the same replacement behavior as parameter
transmission.
 Parameter Passing in Remote Method Invocation
 An argument to, or a return value from, a remote object can be any
Java type that is serializable. This includes Java primitive types,
remote Java objects, and nonremote Java objects that implement
the java.io.Serializable interface. For more details on how to make
classes serializable, see the Java "Object Serialization
Specification." For applets, if the class of an argument or return
value is not available locally, it is loaded dynamically via the
AppletClassLoader. For applications, these classes are loaded by
the class loader that loaded the application; this is either the
default class loader (which uses the local class path) or the
RMIClassLoader (which uses the server's codebase).Some classes
may disallow their being passed (by not being serializable), for
example for security reasons. In this case the remote method
invocation will fail with an exception.

 Parameter Passing in Remote Method Invocation
 An argument to, or a return value from, a remote object can be
any Java type that is serializable. This includes Java primitive
types, remote Java objects, and nonremote Java objects that
implement the java.io.Serializable interface. For more details
on how to make classes serializable, see the Java "Object
Serialization Specification." For applets, if the class of an
argument or return value is not available locally, it is loaded
dynamically via the AppletClassLoader. For applications, these
classes are loaded by the class loader that loaded the
application; this is either the default class loader (which uses
the local class path) or the RMIClassLoader (which uses the
server's codebase).Some classes may disallow their being
passed (by not being serializable), for example for security
reasons. In this case the remote method invocation will fail
with an exception.
 Passing Nonremote Objects
 A nonremote object, that is passed as a parameter of a remote
method invocation or returned as a result of a remote method
invocation, is passed by copy.That is, when a nonremote object
appears in a remote method invocation, the content of the nonremote
object is copied before invoking the call on the remote object. By
default, only the nonstatic and nontransient fields are copied.
 Similarly, when a nonremote object is returned from a remote method
invocation, a new object is created in the calling virtual machine.

2.6.2 Passing Remote Objects
 When passing a remote object as a parameter, the stub for the
remote object is passed. A remote object passed as a parameter can
only implement remote interfaces.

JavaBean

 A JavaBean is a Java class that should follow the


following conventions:
 It should have a no-arg constructor.
 It should be Serializable.
 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.
JavaBeans
are classes that encapsulate many objects
into a single object (the bean). It is a Java
class that should follow the following
conventions:
Must implement Serializable.
It should have a public no-arg constructor.
All properties in java bean must be private
with public getters and setter methods.
Advantages of JavaBean

 The following are the advantages of JavaBean:/p>


 The JavaBean properties and methods can be exposed to
another application.
 It provides an easiness to reuse the software
components.
 Disadvantages of JavaBean
 The following are the disadvantages of JavaBean:
 JavaBeans are mutable. So, it can't take advantages of
immutable objects.
 Creating the setter and getter method for each property
separately may lead to the boilerplate code.
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
 Illustration of JavaBean Class
 A simple example of JavaBean Class is mentioned below:
 JAVA
 // Java program to illustrate the
 // structure of JavaBean class
 public class TestBean {
 private String name;

 public void setName(String name) {
 this.name = name;
 }

 public String getName() { return name; }
 }
 Setter and Getter Methods in Java
 Setter and Getter Methods in Java properties are mentioned below:
 Properties for setter methods:
 It should be public in nature.
 The return type a should be void.
 The setter method should be prefixed with the set.
 It should take some argument i.e. it should not be a no-arg method.
 Properties for getter methods:
 It should be public in nature.
 The return type should not be void i.e. according to our
requirement, return type we have to give the return type.
 The getter method should be prefixed with get.
 It should not take any argument.
 For Boolean properties getter method name can be prefixed
with either “get” or “is”. But recommended to use “is”.
 JAVA
 // Java program to illustrate the
 // getName() method on boolean type attribute
 public class Test {
 private boolean empty;

 public boolean getName(){
 return empty;
 }

 public boolean isempty(){
 return empty;
 }
 }
 Example of JavaBean Class
 Example 1:
 Below is the implementation of the JavaBean Class:
 JAVA
 // Java Program of JavaBean class
 package geeks;

 public class Student {
 private int id;
 private String name;

 // Constructor
 public Student() {}


 // Setter for Id
 public void setId(int id) { this.id = id; }

 // Getter for Id
 public int getId() { return id; }

 // Setter for Name
 public void setName(String name) { this.name =
name; }

 // Getter for Name
 public String getName() { return name; }
}
 Example 2:
 Below is the implementation of the JavaBean class:
 JAVA
 // Java program to access JavaBean class
 package geeks;

 // Driver Class
 public class Test {
 // main function
 public static void main(String args[])
 {
 // object is created
 Student s = new Student();

 // setting value to the object
 s.setName("GFG");

 System.out.println(s.getName());
 }
 }
 Output:
 GFG
 A JavaBean property may be read, 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.
Beans Development Kit,
 BDK can refer to the Beans Development Kit, a tool for developing and
testing JavaBeans components, or the Bot Developer Kit for Java, a tool for
managing multiple bot instances:

 The Beans Development Kit (BDK) is intended to support the early


development of JavaBeansTM components and to act as a standard
reference base for both bean developers and tool vendors.
 Beans Development Kit
 Is a development environment to create, configure, and test JavaBeans.
 The features of BDK environment are:
  Provides a GUI to create, configure, and test JavaBeans.
  Enables you to modify JavaBean properties and link multiple JavaBeans
in an
 application using BDK.
  Provides a set of sample JavaBeans.
  Enables you to associate pre-defined events with sample JavaBeans.
 Beans Development Kit (BDK)
 A tool for developing and testing JavaBeans
components:
 Purpose: The BDK is intended for bean developers
and tool vendors, not application developers. It can
be used as a standalone development tool or as a
testing tool.
 Features: The BDK includes a reference bean
container called the BeanBox, which lets you test
beans, place and arrange beans, connect beans
together, and save and reload applications. The
BDK also includes example beans and reusable
example source code.
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

 import java.awt.*;
 import java.applet.*;
 import java.io.*;

 public class SimpleBean extends Applet implements


Serializable
{
 Button bean;
 public void init()
 {
 bean = new Button("This is my first java bean");
 add(bean);
 }
}
 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 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.

You might also like