Thanks to visit codestin.com
Credit goes to www.slideshare.net

ADVANCE JAVA
ADVANCE JAVA
Author Profile
 Ankit Desai
 Ph.D. Scholar, IET, Ahmedabad University
 Education: M. Tech. (C.E.), B. E. (I. T.)
 Experience: 8 years (Academic and Research)
 Research Interest: IoT, Big Data Analytics, Machine
Learning, Data Mining, Algorithms.
Classified e-Material 2
ADVANCE JAVA
Classified e-Material 3
Introduction
to
Java Remote Method (RMI)
Invocation
ADVANCE JAVA
Classified e-Material 4
Overview of the Session
 Introduce the architecture of Java RMI
 Demonstrate how to build a simple distributed
system using Java RMI
 Investigate the advanced features of Java RMI
ADVANCE JAVA
Classified e-Material 5
The Goal of RMI
 To extend the Java Object model to support
programming with distributed Objects
 The intention is to make distributed programming
as easy as standard Java programming
 Focus on application logic not distribution
ADVANCE JAVA
Classified e-Material 6
A Simple Overview
 Java RMI allows one Java object to call methods on
another Java object in a different JVM
Local
Object
Remote
Object
Client JVM
Server JVM
Method parameters
Result or exception
ADVANCE JAVA
Classified e-Material 7
Distributed Programming
 Java RMI is interface based
 A remote object (or distributed service) is specified
by its interface
 “interfaces define behaviour and classes define
implementations”
 Termed Remote Interfaces
Interface Implementation
Client Program Server Program
RMI
System
ADVANCE JAVA
Classified e-Material 8
Distributed Programming (cont.)
 Before you invoke a method on a remote object you
need a reference to this object
 Look for an object with a specific interface type
 There are many ways to find this information
 Discovery Protocols
 Naming Service e.g. RMI Registry
ADVANCE JAVA
Classified e-Material 9
The RMI Registry
 The RMI Registry is a naming service
 Separately Running service
 Initiated using Java’s “rmiregistry” tool
 Server programs register remote objects
 Give the object a name it can be found using
 Client programs lookup object references that match
this service name
 Registry names have a URL format
 rmi://<hostname>:<port>/<ServiceName>
 E.g. rmi://localhost:1099/CalculatorService
 E.g. rmi://194.80.36.30:1099/ChatService
ADVANCE JAVA
Classified e-Material 10
The RMI Registry Interface
 void rebind (String name, Remote obj)
 This method is used by the server to register the
identifier of a remote object by name.
 void bind (String name, Remote obj)
 This method can alternatively be used by a server to
register a remote object by name, but if the name is
already bound to a remote object reference an
exception is thrown.
 void unbind (String name, Remote obj)
 This method removes a binding.
 Remote lookup(String name)
 This method is used by the clients to lookup a remote
object by name. A remote object reference is
returned.
ADVANCE JAVA
Classified e-Material 11
Lookup in Java RMI
RMIRegistry
Server
naming.rebind(“rmi://localhost:1099/TestS
ervice”, RemoteObjectReference)
Client
naming.lookup(“rmi://localhost:1099/
TestService”)
Interface Remote Object
Client Program Server Program
Local Machine
ADVANCE JAVA
Classified e-Material 12
The RMI Architecture
Client Program
Interface
Server Program
Implementation
Client Program Server Program
Remote Reference Layer Remote Reference Layer
Transport Layer
ADVANCE JAVA
Classified e-Material 13
Stubs and Skeleton Layer
 Stubs and skeletons
are generated from
the remote interface
 Using the “rmic” Java
tool
 Stub communicates
with a skeleton rather
than the remote object
 This a Proxy approach
 Marshalls the
parameters and results
to be sent across the
wire
 After java 1.1 skeletons
were made obsolete and
RMI now uses reflection
to direct a request to an
object
Interface
Client
Stub
Server
Skel
ADVANCE JAVA
Classified e-Material 14
Parameter Passing
 Parameter Passing in Java RMI is different from
standard Java
 Reminder: In Java, primitives are passed by value,
Objects are passed by reference
 In Java RMI
 Objects and primitives are passed by value
 Remote objects are passed by reference
 You must be aware of the differences!
 Otherwise you'll generate logical bugs that are
difficult to identify
ADVANCE JAVA
Classified e-Material 15
Parameter Passing (2)
 RMI-Pass by Value
 All ordinary objects and primitives are serialised and
a copy is passed
 Any changes to the copy do not affect the original
 It is your job to ensure your Objects can be
serialised!
 RMI-Pass by Reference
 Remote Object is the parameter, a stub (reference) is
sent
 the stub is used to modify the object, the original
object is modified
ADVANCE JAVA
Classified e-Material 16
A Chat Server Example
ChatServer
ChatServer
ChatServer
ChatServerImpl
Login(..)
Chat(..)
Chas: Hello
Dave: ASL?
Client A
Client B
Server
ADVANCE JAVA
Classified e-Material 17
Building a Java RMI system
An RMI system must be composed of the
following parts:
1. An interface definition of the remote services;
2. The implementations of the remote services;
3. Stub and skeleton files;
4. A server to host the remote services;
5. An RMI Naming service
6. A client program that uses the remote
services.
ADVANCE JAVA
Classified e-Material 18
Step 1 - Define the Remote Interface
 Declare the methods you'd like to call remotely
 This interface must extend java.rmi.Remote
 Each method must declare java.rmi.RemoteException
in its throws clause
 You can have multiple remote interfaces
 Remember about parameter passing
 Remote objects must be passed as remote interface
types
 Local objects must be serializable
ADVANCE JAVA
Classified e-Material 19
Example ChatServer Interface
public interface ChatServer extends
java.rmi.Remote {
public void login(String name, String password)
throws java.rmi.RemoteException;
public void logout(String name)
throws java.rmi.RemoteException;
public void chat(String name, String message)
throws java.rmi.RemoteException;
}
ADVANCE JAVA
Classified e-Material 20
Step 2 - Implement the remote service
 Your class must implement the Remote interface
 Extend this class with UnicastRemoteObject
 Must provide a constructor that throws a
RemoteException.
 Call super() in the constructor
 This activates code in UnicastRemoteObject that
performs the RMI linking and remote object
initialization.
ADVANCE JAVA
Classified e-Material 21
Example Remote Object (ChatServiceImpl)
public class ChatServerImpl
extends java.rmi.server.UnicastRemoteObject implements
ChatServer {
public ChatServerImpl() throws java.rmi.RemoteException
{
Super();
}
public void login(String name, String pass) throws
java.rmi.RemoteException{
// Method Implementation
}
public void logout(String name) throws
java.rmi.RemoteException{
// Method Implementation
}
public void chat(String name, String msg) throws
java.rmi.RemoteException{
// Method Implementation
}
}
ADVANCE JAVA
Classified e-Material 22
Step 3 – Generate Stubs & Skeletons
 Generate the Remote Interface stub
 This stub contains information that allows it to
connect to a remote object, which contains the
implementation of the methods
 RMI provides a tool called rmic to generate stubs
 Use rmic on the remote object
 e.g. rmic ChatServerImpl
 The files: *impl_Stub.class and *impl_Skel.class will
be created
ChatServer RMIC
ChatServerImpl_Stub.class
ChatServerImpl_Skel.class
ADVANCE JAVA
Classified e-Material 23
Step 4 – Create the Server
 The server is a Java application
 Creates one or more instances of remote objects
 Binds at least one of the remote objects to a name in
the RMI registry
 Uses the Naming.rebind() operation
ADVANCE JAVA
Classified e-Material 24
Example Chat Server
public class ChattingServer {
public ChattingServer() {
try {
ChatServer c = new
ChatServerImpl();
Naming.rebind("rmi://localhost
/ChatService", c);
}
catch (Exception e) {
System.out.println("Server Error: " +
e);
}
}
public static void main(String args[]) {
//Create the new Calculator
server
new ChattingServer();
}
}
Create the
remote
object
RMIRegistry
Register the
object
ADVANCE JAVA
Classified e-Material 25
Step 5 – Create the Client
 Get a remote reference by calling Naming.lookup()
 Remember - Lookup by service name
 Receives a stub object for the requested remote
object
 Loads code for the stub either locally or remotely
 Invoke methods directly on the reference
 Much like on standard Java objects
Stub class NetworkFile System OR
ADVANCE JAVA
Classified e-Material 26
Example Chat Client
public class calculatorclient {
public static void main(String[] args) {
try {
// Get a reference to the remote object through the rmiregistry
ChatServer c = (ChatServer)
Naming.lookup("rmi://localhost/ChatService");
// Now use the reference c to call remote methods
c.login(“Chas”,”*****”);
c.chat(“Chas”, “Hello”);
// Catch the exceptions that may occur - rubbish URL, Remote exception
} catch (RemoteException re) {
System.out.println("RemoteException“+re);
}
}
}
Interface
ADVANCE JAVA
Classified e-Material 27
Java RMI Advanced Features
 Serialisation
 Callbacks
 Remote Activation
ADVANCE JAVA
Classified e-Material 28
Serialisation
 To pass user created objects as parameters in RMI
they must be serialisable
 This is easy in Java – simply make the class
implement the Serializable interface
 If you want to optimise the serialisation you can
overide the methods of serializable with your own
implementation e.g. ObjectInput(Output)Stream
 Transforming an Object in a stream of bytes
 Can be sent across the network
ADVANCE JAVA
Classified e-Material 29
Callbacks
 In many applications the server may want to
callback the client
 All messages in the chat system are displayed on a
central server
 You could change the server to callback every client
with each new chat message allowing the message
to be displayed on each client
 Callbacks are just a reverse RMI
 You create a remote object on the client and pass this
reference to the server, who can invoke it directly
ADVANCE JAVA
Classified e-Material 30
Using Callbacks in Chat
ChatServer
ChatServer
ChatServer
ChatServerImpl
Login(.., Callback
Ref)
Chat(..)
Chas: Hello
Dave: ASL?
Client A Client B
Server
Chas: Hello
Dave: ASL?
Callback
Impl Callback
Impl
Callback
Callback
Display(Name.
Msg)
ADVANCE JAVA
Classified e-Material 31
Remote Activation
 Server hosting remote objects continuously execute
 This wastes system resources
 Ideally, a Remote Object would be dormant until it
was invoked
 Java RMI Remote Activation provides this process
 Rather than a server program, you register each
object with the rmid daemon
 Unfortunately this is complex to program!
 See on-line tutorials on web site to find out how to do
it
 Ask the demonstrators

Java RMI

  • 1.
  • 2.
    ADVANCE JAVA Author Profile Ankit Desai  Ph.D. Scholar, IET, Ahmedabad University  Education: M. Tech. (C.E.), B. E. (I. T.)  Experience: 8 years (Academic and Research)  Research Interest: IoT, Big Data Analytics, Machine Learning, Data Mining, Algorithms. Classified e-Material 2
  • 3.
    ADVANCE JAVA Classified e-Material3 Introduction to Java Remote Method (RMI) Invocation
  • 4.
    ADVANCE JAVA Classified e-Material4 Overview of the Session  Introduce the architecture of Java RMI  Demonstrate how to build a simple distributed system using Java RMI  Investigate the advanced features of Java RMI
  • 5.
    ADVANCE JAVA Classified e-Material5 The Goal of RMI  To extend the Java Object model to support programming with distributed Objects  The intention is to make distributed programming as easy as standard Java programming  Focus on application logic not distribution
  • 6.
    ADVANCE JAVA Classified e-Material6 A Simple Overview  Java RMI allows one Java object to call methods on another Java object in a different JVM Local Object Remote Object Client JVM Server JVM Method parameters Result or exception
  • 7.
    ADVANCE JAVA Classified e-Material7 Distributed Programming  Java RMI is interface based  A remote object (or distributed service) is specified by its interface  “interfaces define behaviour and classes define implementations”  Termed Remote Interfaces Interface Implementation Client Program Server Program RMI System
  • 8.
    ADVANCE JAVA Classified e-Material8 Distributed Programming (cont.)  Before you invoke a method on a remote object you need a reference to this object  Look for an object with a specific interface type  There are many ways to find this information  Discovery Protocols  Naming Service e.g. RMI Registry
  • 9.
    ADVANCE JAVA Classified e-Material9 The RMI Registry  The RMI Registry is a naming service  Separately Running service  Initiated using Java’s “rmiregistry” tool  Server programs register remote objects  Give the object a name it can be found using  Client programs lookup object references that match this service name  Registry names have a URL format  rmi://<hostname>:<port>/<ServiceName>  E.g. rmi://localhost:1099/CalculatorService  E.g. rmi://194.80.36.30:1099/ChatService
  • 10.
    ADVANCE JAVA Classified e-Material10 The RMI Registry Interface  void rebind (String name, Remote obj)  This method is used by the server to register the identifier of a remote object by name.  void bind (String name, Remote obj)  This method can alternatively be used by a server to register a remote object by name, but if the name is already bound to a remote object reference an exception is thrown.  void unbind (String name, Remote obj)  This method removes a binding.  Remote lookup(String name)  This method is used by the clients to lookup a remote object by name. A remote object reference is returned.
  • 11.
    ADVANCE JAVA Classified e-Material11 Lookup in Java RMI RMIRegistry Server naming.rebind(“rmi://localhost:1099/TestS ervice”, RemoteObjectReference) Client naming.lookup(“rmi://localhost:1099/ TestService”) Interface Remote Object Client Program Server Program Local Machine
  • 12.
    ADVANCE JAVA Classified e-Material12 The RMI Architecture Client Program Interface Server Program Implementation Client Program Server Program Remote Reference Layer Remote Reference Layer Transport Layer
  • 13.
    ADVANCE JAVA Classified e-Material13 Stubs and Skeleton Layer  Stubs and skeletons are generated from the remote interface  Using the “rmic” Java tool  Stub communicates with a skeleton rather than the remote object  This a Proxy approach  Marshalls the parameters and results to be sent across the wire  After java 1.1 skeletons were made obsolete and RMI now uses reflection to direct a request to an object Interface Client Stub Server Skel
  • 14.
    ADVANCE JAVA Classified e-Material14 Parameter Passing  Parameter Passing in Java RMI is different from standard Java  Reminder: In Java, primitives are passed by value, Objects are passed by reference  In Java RMI  Objects and primitives are passed by value  Remote objects are passed by reference  You must be aware of the differences!  Otherwise you'll generate logical bugs that are difficult to identify
  • 15.
    ADVANCE JAVA Classified e-Material15 Parameter Passing (2)  RMI-Pass by Value  All ordinary objects and primitives are serialised and a copy is passed  Any changes to the copy do not affect the original  It is your job to ensure your Objects can be serialised!  RMI-Pass by Reference  Remote Object is the parameter, a stub (reference) is sent  the stub is used to modify the object, the original object is modified
  • 16.
    ADVANCE JAVA Classified e-Material16 A Chat Server Example ChatServer ChatServer ChatServer ChatServerImpl Login(..) Chat(..) Chas: Hello Dave: ASL? Client A Client B Server
  • 17.
    ADVANCE JAVA Classified e-Material17 Building a Java RMI system An RMI system must be composed of the following parts: 1. An interface definition of the remote services; 2. The implementations of the remote services; 3. Stub and skeleton files; 4. A server to host the remote services; 5. An RMI Naming service 6. A client program that uses the remote services.
  • 18.
    ADVANCE JAVA Classified e-Material18 Step 1 - Define the Remote Interface  Declare the methods you'd like to call remotely  This interface must extend java.rmi.Remote  Each method must declare java.rmi.RemoteException in its throws clause  You can have multiple remote interfaces  Remember about parameter passing  Remote objects must be passed as remote interface types  Local objects must be serializable
  • 19.
    ADVANCE JAVA Classified e-Material19 Example ChatServer Interface public interface ChatServer extends java.rmi.Remote { public void login(String name, String password) throws java.rmi.RemoteException; public void logout(String name) throws java.rmi.RemoteException; public void chat(String name, String message) throws java.rmi.RemoteException; }
  • 20.
    ADVANCE JAVA Classified e-Material20 Step 2 - Implement the remote service  Your class must implement the Remote interface  Extend this class with UnicastRemoteObject  Must provide a constructor that throws a RemoteException.  Call super() in the constructor  This activates code in UnicastRemoteObject that performs the RMI linking and remote object initialization.
  • 21.
    ADVANCE JAVA Classified e-Material21 Example Remote Object (ChatServiceImpl) public class ChatServerImpl extends java.rmi.server.UnicastRemoteObject implements ChatServer { public ChatServerImpl() throws java.rmi.RemoteException { Super(); } public void login(String name, String pass) throws java.rmi.RemoteException{ // Method Implementation } public void logout(String name) throws java.rmi.RemoteException{ // Method Implementation } public void chat(String name, String msg) throws java.rmi.RemoteException{ // Method Implementation } }
  • 22.
    ADVANCE JAVA Classified e-Material22 Step 3 – Generate Stubs & Skeletons  Generate the Remote Interface stub  This stub contains information that allows it to connect to a remote object, which contains the implementation of the methods  RMI provides a tool called rmic to generate stubs  Use rmic on the remote object  e.g. rmic ChatServerImpl  The files: *impl_Stub.class and *impl_Skel.class will be created ChatServer RMIC ChatServerImpl_Stub.class ChatServerImpl_Skel.class
  • 23.
    ADVANCE JAVA Classified e-Material23 Step 4 – Create the Server  The server is a Java application  Creates one or more instances of remote objects  Binds at least one of the remote objects to a name in the RMI registry  Uses the Naming.rebind() operation
  • 24.
    ADVANCE JAVA Classified e-Material24 Example Chat Server public class ChattingServer { public ChattingServer() { try { ChatServer c = new ChatServerImpl(); Naming.rebind("rmi://localhost /ChatService", c); } catch (Exception e) { System.out.println("Server Error: " + e); } } public static void main(String args[]) { //Create the new Calculator server new ChattingServer(); } } Create the remote object RMIRegistry Register the object
  • 25.
    ADVANCE JAVA Classified e-Material25 Step 5 – Create the Client  Get a remote reference by calling Naming.lookup()  Remember - Lookup by service name  Receives a stub object for the requested remote object  Loads code for the stub either locally or remotely  Invoke methods directly on the reference  Much like on standard Java objects Stub class NetworkFile System OR
  • 26.
    ADVANCE JAVA Classified e-Material26 Example Chat Client public class calculatorclient { public static void main(String[] args) { try { // Get a reference to the remote object through the rmiregistry ChatServer c = (ChatServer) Naming.lookup("rmi://localhost/ChatService"); // Now use the reference c to call remote methods c.login(“Chas”,”*****”); c.chat(“Chas”, “Hello”); // Catch the exceptions that may occur - rubbish URL, Remote exception } catch (RemoteException re) { System.out.println("RemoteException“+re); } } } Interface
  • 27.
    ADVANCE JAVA Classified e-Material27 Java RMI Advanced Features  Serialisation  Callbacks  Remote Activation
  • 28.
    ADVANCE JAVA Classified e-Material28 Serialisation  To pass user created objects as parameters in RMI they must be serialisable  This is easy in Java – simply make the class implement the Serializable interface  If you want to optimise the serialisation you can overide the methods of serializable with your own implementation e.g. ObjectInput(Output)Stream  Transforming an Object in a stream of bytes  Can be sent across the network
  • 29.
    ADVANCE JAVA Classified e-Material29 Callbacks  In many applications the server may want to callback the client  All messages in the chat system are displayed on a central server  You could change the server to callback every client with each new chat message allowing the message to be displayed on each client  Callbacks are just a reverse RMI  You create a remote object on the client and pass this reference to the server, who can invoke it directly
  • 30.
    ADVANCE JAVA Classified e-Material30 Using Callbacks in Chat ChatServer ChatServer ChatServer ChatServerImpl Login(.., Callback Ref) Chat(..) Chas: Hello Dave: ASL? Client A Client B Server Chas: Hello Dave: ASL? Callback Impl Callback Impl Callback Callback Display(Name. Msg)
  • 31.
    ADVANCE JAVA Classified e-Material31 Remote Activation  Server hosting remote objects continuously execute  This wastes system resources  Ideally, a Remote Object would be dormant until it was invoked  Java RMI Remote Activation provides this process  Rather than a server program, you register each object with the rmid daemon  Unfortunately this is complex to program!  See on-line tutorials on web site to find out how to do it  Ask the demonstrators