SlideShare a Scribd company logo
1 of 35
Download to read offline
1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Remote Method
Invocation
Remote Method Invocation2 www.corewebprogramming.com
Agenda
• Steps to build and RMI application
• Running and compiling an RMI program
• Eample: Retrieving a String remotely
• Example: Performing numerical integration
remotely
• Enterprise RMI configuration
• RMI Applets
Remote Method Invocation3 www.corewebprogramming.com
RMI: Remote Method Invocation
• Idea
– Distribute objects across different machines to take
advantage of hardware and dedicated software
– Developer builds network service and installs it on
specified machine
– User requests an instance of a class using URL syntax
– User uses object as though it were a regular, local object
• Network connections happen automatically behind
the scenes
• Java “serialization” lets you pass complex data
structures over the network without writing code to
parse and reconstruct them
Remote Method Invocation4 www.corewebprogramming.com
RMI Operations
• Stub Operation
– Package identifier of remote object
– Package method identifier
– Marshall parameters
– Send package to server skeleton
• Skeleton Operation
– Unmarshall Parameters
– Calls return value or exception
– Marshall method return
– Send package to client stub
Remote Method Invocation5 www.corewebprogramming.com
RMI Details
1. Starting: Build Four Required Classes
a. An interface for the remote object
• Used by both the client and the server
b. The RMI client
• This will look up the object on the remote server, cast it to the
type of the interface from Step 1, then use it like a local object.
• Note that as long as there is a “live” reference to the remote
object, an open network connection is maintained. The
connection will be automatically closed when the remote
object is garbage collected on the client.
c. The object implementation
• This object needs to implement the interface of Step a, and will
be used by the server
d. The RMI server
• This will create an instance of the object from Step c and
register it with a particular URL
Remote Method Invocation6 www.corewebprogramming.com
RMI Details, cont.
2. Compile and Run the System
a. Compile client and server.
• Compiles the remote object interface and implementation
automatically
b. Generate the client stub and the server skeleton
• Use the rmic compiler on the remote object implementation
for this.
– The client system will need the client class, the interface
class, and the client stub class
– If the client is an applet, these three classes must be
available from the applet’s home machine
– The server system will need the server class, the remote
object interface and implementation, and the server
skeleton class
Remote Method Invocation7 www.corewebprogramming.com
RMI Details, cont.
2. Compile and Run the System, cont.
c. Start the RMI registry
• This only needs to be done once, not for each remote object
• The current version of RMI requires this registry to be running
on the same system as server
d. Start the server
• This step must be on the same machine as the registry of
step c
e. Start the client
• This step can be done on an arbitrary machine
Remote Method Invocation8 www.corewebprogramming.com
A Very Simple RMI Example:
The Four Required Classes
1. The Interface for the Remote Object
– The interface should extend java.rmi.Remote, and
all its methods should throw
java.rmi.RemoteException
import java.rmi.*;
/** The RMI client will use this interface directly.
* The RMI server will make a real remote object that
* implements this, then register an instance of it
* with some URL.
*/
public interface Rem extends Remote {
public String getMessage() throws RemoteException;
}
Remote Method Invocation9 www.corewebprogramming.com
Simple Example,
Required Classes, cont.
2. The RMI Client
– Look up the object from the host using Naming.lookup, cast it
to the appropriate type, then use it like a local object
import java.rmi.*; // For Naming, RemoteException, etc.
import java.net.*; // For MalformedURLException
import java.io.*; // For Serializable interface
public class RemClient {
public static void main(String[] args) {
try {
String host = (args.length > 0) ? args[0] : "localhost";
Rem remObject = (Rem)Naming.lookup("rmi://" + host + "/Rem");
System.out.println(remObject.getMessage());
} catch(RemoteException re) {
System.out.println("RemoteException: " + re);
} catch(NotBoundException nbe) {
System.out.println("NotBoundException: " + nbe);
} catch(MalformedURLException mfe) {
System.out.println("MalformedURLException: " + mfe);
}
}
}
Remote Method Invocation10 www.corewebprogramming.com
Simple Example,
Required Classes, cont.
3. The Remote Object Implementation
– This class must extend UnicastRemoteObject and
implement the remote object interface defined earlier
– The constructor should throw RemoteException
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class RemImpl extends UnicastRemoteObject
implements Rem {
public RemImpl() throws RemoteException {}
public String getMessage() throws RemoteException {
return("Here is a remote message.");
}
}
Remote Method Invocation11 www.corewebprogramming.com
Simple Example,
Required Classes, cont.
4. The RMI Server
– The server builds an object and register it with a particular URL
– Use Naming.rebind (replace any previous bindings) or
Naming.bind (throw AlreadyBoundException if a previous
binding exists)
import java.rmi.*;
import java.net.*;
public class RemServer {
public static void main(String[] args) {
try {
RemImpl localObject = new RemImpl();
Naming.rebind("rmi:///Rem", localObject);
} catch(RemoteException re) {
System.out.println("RemoteException: " + re);
} catch(MalformedURLException mfe) {
System.out.println("MalformedURLException: " + mfe);
}
}
}
Remote Method Invocation12 www.corewebprogramming.com
Simple Example: Compiling and
Running the System
1. Compile the Client and the Server
Prompt> javac RemClient.java
– This compiles the Rem interface automatically
Prompt> javac RemServer.java
– This compiles the RemImpl object implementation automatically
2. Generate the Client Stub and Server Skeleton
Prompt> rmic RemImpl
– This builds RemImpl_Stub.class and
RemImpl_Skeleton.class
– The client machine needs Rem.class, RemClient.class,
and RemImpl_Stub.class
– The server machine needs Rem.class, RemImpl.class,
RemServer.class, and RemImpl_Skeleton.class
Remote Method Invocation13 www.corewebprogramming.com
Simple Example: Compiling and
Running the System, cont.
3. Start the RMI Registry
Server> rmiregistry
– On Unix systems you would probably add “&” to put the registry
process in the background
– You can also specify a port number; if omitted, port 1099 is used
4. Start the Server
Server> java RemServer
– Again, on Unix systems you would probably add “&” to put the
process in the background
5. Start the Client
Client> java RemClient hostname
Here is a remote message.
Remote Method Invocation14 www.corewebprogramming.com
A Better RMI Example,
Numerical Integration
1. Simple Iterative Program
to Calculate Sums:
2. Use to Approximate
Numeric Integrals of the Form:
3. MidPoint Rule:
4. Motivation for RMI
– Since smaller rectangles typically give better results, this can often
be very cpu-intensive
– RMI can make it available on a fast floating-point box
Remote Method Invocation15 www.corewebprogramming.com
Numerical Integration,
Example, cont.
public class Integral {
/** Returns the sum of f(x) from x=start to x=stop, where the function f
* is defined by the evaluate method of the Evaluatable object.
*/
public static double sum(double start, double stop,
double stepSize,
Evaluatable evalObj) {
double sum = 0.0, current = start;
while (current <= stop) {
sum += evalObj.evaluate(current);
current += stepSize;
}
return(sum);
}
public static double integrate(double start, double stop,
int numSteps,
Evaluatable evalObj) {
double stepSize = (stop - start) / (double)numSteps;
start = start + stepSize / 2.0;
return(stepSize * sum(start, stop, stepSize, evalObj));
}
}
Remote Method Invocation16 www.corewebprogramming.com
Numerical Integration,
Example, cont.
/** An interface for evaluating functions y = f(x) at a specific
* value. Both x and y are double-precision floating-point
* numbers.
*/
public interface Evaluatable {
public double evaluate(double value);
}
Remote Method Invocation17 www.corewebprogramming.com
Integration Example:
Four Required Classes
1. The RemoteIntegral Interface
• The interface shared by the client and server
import java.rmi.*;
public interface RemoteIntegral extends Remote {
public double sum(double start, double stop, double stepSize,
Evaluatable evalObj)
throws RemoteException;
public double integrate(double start, double stop,
int numSteps, Evaluatable evalObj)
throws RemoteException;
Remote Method Invocation18 www.corewebprogramming.com
Integration Example:
Four Required Classes, cont.
2. The Remote Integral Client
• Sends the RemoteIntegral an Evaluatable to integrate
public class RemoteIntegralClient {
public static void main(String[] args) {
try {
String host = (args.length > 0) ? args[0] : "localhost";
RemoteIntegral remoteIntegral =
(RemoteIntegral)Naming.lookup("rmi://" + host + "/RemoteIntegral");
for(int steps=10; steps<=10000; steps*=10) {
System.out.println("Approximated with " + steps + " steps:" +
"n Integral from 0 to pi of sin(x)=" +
remoteIntegral.integrate(0.0, Math.PI, steps, new Sin()));
}
System.out.println("'Correct' answer using Math library:" +
"n Integral from 0 to pi of sin(x)=" +
(-Math.cos(Math.PI) - -Math.cos(0.0)));
} catch(RemoteException re) {
System.out.println("RemoteException: " + re);
} catch(NotBoundException nbe) {
System.out.println("NotBoundException: " + nbe);
} catch(MalformedURLException mfe) {
System.out.println("MalformedURLException: " + mfe);
}
}
}
Remote Method Invocation19 www.corewebprogramming.com
Integration Example:
Four Required Classes, cont.
2. The Remote Integral Client, cont.
• Evaluatable Sin function
import java.io.Serializable;
class Sin implements Evaluatable, Serializable {
public double evaluate(double val) {
return(Math.sin(val));
}
public String toString() {
return("Sin");
}
}
Remote Method Invocation20 www.corewebprogramming.com
Integration Example:
Four Required Classes, cont.
3. The Remote Integral Implementation
• Remote object that calculates the integral value
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class RemoteIntegralImpl extends UnicastRemoteObject
implements RemoteIntegral {
public RemoteIntegralImpl() throws RemoteException {}
public double sum(double start, double stop, double stepSize,
Evaluatable evalObj) {
return(Integral.sum(start, stop, stepSize, evalObj));
}
public double integrate(double start, double stop, int numSteps,
Evaluatable evalObj) {
return(Integral.integrate(start, stop, numSteps, evalObj));
}
}
Remote Method Invocation21 www.corewebprogramming.com
Integration Example:
Four Required Classes, cont.
4. The Remote Integral Server
• Creates the RemoteIntegral and registers it with
the rmi registry
import java.rmi.*;
import java.net.*;
public class RemoteIntegralServer {
public static void main(String[] args) {
try {
RemoteIntegralImpl integral = new RemoteIntegralImpl();
Naming.rebind("rmi:///RemoteIntegral", integral);
} catch(RemoteException re) {
System.out.println("RemoteException: " + re);
} catch(MalformedURLException mfe) {
System.out.println("MalformedURLException: " + mfe);
}
}
}
Remote Method Invocation22 www.corewebprogramming.com
Integration Example: Compiling
and Running the System
1. Compile the Client and the Server
Prompt> javac RemoteIntegralClient.java
Prompt> javac RemoteIntegralServer.java
2. Generate the Client Stub and Server Skeleton
Prompt> rmic –v1.2 RemoteIntegralImpl
– Client requires: RemoteIntegral.class,
RemoteIntegralClient.class and
RemoteIntegralImpl_Stub.class
– Server requires: RemoteIntegral.class,
RemoteIntegralImpl.class, and
RemoteIntegralServer.class
– If the server and client are both running JDK 1.1, use the -v1.1
switch to produce the RMI 1.1 skeleton stub,
RemoteIntegralImpl_Skeleton, required by the server
Remote Method Invocation23 www.corewebprogramming.com
Integral Example: Compiling
and Running the System, cont.
3. Start the RMI Registry
Prompt> rmiregistry
4. Start the Server
Prompt> java RemoteIntegralServer
5. Start the Client
Prompt> java RemoteIntegralClient
Approximated with 10 steps:
Integral from 0 to pi of sin(x)=2.0082484079079745
Approximated with 100 steps:
Integral from 0 to pi of sin(x)=2.0000822490709877
Approximated with 1000 steps:
Integral from 0 to pi of sin(x)=2.0000008224672983
Approximated with 10000 steps:
Integral from 0 to pi of sin(x)=2.00000000822436
...
Remote Method Invocation24 www.corewebprogramming.com
Enterprise RMI Configuration
• Stub files need to be placed on a HTTP
server for downloading
– In Java 2, the RMI 1.2 protocol does not require the
skeleton
• Client must install an RMISecurityManager
to load the RMI classes remotely
System.setSecurityManager(new RMISecurityManager());
• Client requires a policy file to connect to
registry and HTTP server
Remote Method Invocation25 www.corewebprogramming.com
Policy File for Client
grant {
// rmihost - RMI registry and the server
// webhost - HTTP server for stub classes
permission java.net.SocketPermission
"rmihost:1024-65535", "connect";
permission java.net.SocketPermission
"webhost:80", "connect";
};
– Need to grant permission to ports 1024-65535 on the server
• The server communicates with the rmiregistry (and client)
on a randomly selected source port
– Alternatively, can set policies in java.policy located in
JAVA_HOME/lib/security/
Remote Method Invocation26 www.corewebprogramming.com
Enterprise RMI,
Remote Integral, Example
public class RemoteIntegralClient2 {
public static void main(String[] args) {
try {
System.setSecurityManager(new RMISecurityManager());
String host = (args.length > 0) ? args[0] : "localhost";
RemoteIntegral remoteIntegral =
(RemoteIntegral)Naming.lookup("rmi://" + host +
"/RemoteIntegral");
for(int steps=10; steps<=10000; steps*=10) {
System.out.println
("Approximated with " + steps + " steps:" +
"n Integral from 0 to pi of sin(x)=" +
remoteIntegral.integrate(0.0, Math.PI,
steps, new Sin()));
}
...
} catch(RemoteException re) {
System.out.println("RemoteException: " + re);
}
...
}
Remote Method Invocation27 www.corewebprogramming.com
Enterprise Example: Compiling
and Running the System
1. Compile the Client and the Server
Prompt> javac RemoteIntegralClient2.java
Prompt> javac RemeteIntegralServer.java
2. Generate the Client Stub and Server Skeleton
Prompt> rmic –v1.2 RemoteIntegralImpl
3. Place the files on the correct machines
Remote Method Invocation28 www.corewebprogramming.com
Enterprise Example: Compiling
and Running the System, cont.
4. Start the HTTP Server
• Place RemoteIntegral_Stub.class,
RemoteIntegeral.class, and
Evaluatable.class on an HTTP server
• Verify that you can access the files through a browser
5. Start the RMI Registry
Server> /somedirectory/rmiregistry
• Make sure that none of the class files are in the directory in
which you started the registry or available through the
classpath
6. Start the Server
Server> java -Djava.rmi.server.codebase=http://webhost/rmi/
RemoteIntegralServer
– Server must be started on same host as rmiregistry
Remote Method Invocation29 www.corewebprogramming.com
Enterprise Example: Compiling
and Running the System, cont.
7. Start the Client
Client> java -Djava.security.policy=rmiclient.policy
RemoteIntegralClient2 rmihost
Approximated with 10 steps:
Integral from 0 to pi of sin(x)=2.0082484079079745
Approximated with 100 steps:
Integral from 0 to pi of sin(x)=2.0000822490709877
...
– The rmihost is where server in which the rmiregistry
was started
Remote Method Invocation30 www.corewebprogramming.com
An RMI Applet
• Applet does not require a RMI Security
Manager
• Applet can only access server in which
class files were loaded
– RMI Registry and remote object server must be the same
HTTP host in which the applet was loaded
• RMI 1.1 stub protocol not properly
supported in IE
• RMI 1.2 stub protocol require Java Plug-In
or Netscape 6
Remote Method Invocation31 www.corewebprogramming.com
RMI Applet, Example
...
import javax.swing.*;
public class RemoteIntegralApplet extends JApplet
implements ActionListener {
private Evaluatable[] shapes;
private RemoteIntegral remoteIntegral;
private JLabel result;
private JTextField startInput, stopInput, stepInput;
private JComboBox combo;
public void init() {
String host = getCodeBase().getHost();
try {
remoteIntegral =
(RemoteIntegral)Naming.lookup("rmi://" + host +
"/RemoteIntegral");
} catch(RemoteException re) {
reportError("RemoteException: " + re);
}
...
Remote Method Invocation32 www.corewebprogramming.com
RMI Applet, Example
...
public void actionPerformed(ActionEvent event) {
try {
int steps = Integer.parseInt(stepInput.getText());
double start = Double.parseDouble(startInput.getText());
double stop = Double.parseDouble(stopInput.getText());
showStatus("Calculating ...");
Evaluatable shape = (Evaluatable)combo.getSelectedItem();
double area = remoteIntegral.integrate(start, stop,
steps, shape);
result.setText(Double.toString(area));
showStatus("");
} catch(NumberFormatException nfe) {
reportError("Bad input: " + nfe);
} catch(RemoteException re) {
reportError("RemoteException: " + re);
}
}
}
Remote Method Invocation33 www.corewebprogramming.com
RMI Applet, Result
Applet that communicates to a
remote object through RMI in Netscape 6
Remote Method Invocation34 www.corewebprogramming.com
Summary
• RMI is a pure Java-based protocol for
communicating with remote objects
• Register (bind) and look-up remote objects in a
registry
• Java 2 no longer requires the skeleton class
needed with the RMI 1.1 protocol
• Enterprise RMI configuration requires a RMI
Security Manager and client policy file for
permissions
35 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Questions?

More Related Content

What's hot (20)

Java RMI(Remote Method Invocation)
Java RMI(Remote Method Invocation)Java RMI(Remote Method Invocation)
Java RMI(Remote Method Invocation)
 
Java RMI Presentation
Java RMI PresentationJava RMI Presentation
Java RMI Presentation
 
Distributed Programming using RMI
Distributed Programming using RMIDistributed Programming using RMI
Distributed Programming using RMI
 
RMI (Remote Method Invocation)
RMI (Remote Method Invocation)RMI (Remote Method Invocation)
RMI (Remote Method Invocation)
 
A First Date With Scala
A First Date With ScalaA First Date With Scala
A First Date With Scala
 
Remote Method Innovation (RMI) In JAVA
Remote Method Innovation (RMI) In JAVARemote Method Innovation (RMI) In JAVA
Remote Method Innovation (RMI) In JAVA
 
High Quality Symfony Bundles tutorial - Dutch PHP Conference 2014
High Quality Symfony Bundles tutorial - Dutch PHP Conference 2014High Quality Symfony Bundles tutorial - Dutch PHP Conference 2014
High Quality Symfony Bundles tutorial - Dutch PHP Conference 2014
 
Rmi presentation
Rmi presentationRmi presentation
Rmi presentation
 
Symfony Components 2.0 on PHP 5.3
Symfony Components 2.0 on PHP 5.3Symfony Components 2.0 on PHP 5.3
Symfony Components 2.0 on PHP 5.3
 
Rmi ppt
Rmi pptRmi ppt
Rmi ppt
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Java servlets
Java servletsJava servlets
Java servlets
 
Servlets
ServletsServlets
Servlets
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
Ember - introduction
Ember - introductionEmber - introduction
Ember - introduction
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
Red5 - PHUG Workshops
Red5 - PHUG WorkshopsRed5 - PHUG Workshops
Red5 - PHUG Workshops
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 

Viewers also liked

Common Denominator of Success
Common Denominator of SuccessCommon Denominator of Success
Common Denominator of SuccessKedar Ponkshe
 
Festa de santa rita de cássia 2013
Festa de santa rita de cássia 2013Festa de santa rita de cássia 2013
Festa de santa rita de cássia 2013Roberto Rabat Chame
 
OBA - Social Media, Friend or Foe
OBA - Social Media, Friend or FoeOBA - Social Media, Friend or Foe
OBA - Social Media, Friend or FoeOmar Ha-Redeye
 
February 2009 Newsletter
February 2009 NewsletterFebruary 2009 Newsletter
February 2009 NewslettermrBanerjee
 
Atualmente existem 30 partidos políticos oficializados no brasil
Atualmente existem 30 partidos políticos oficializados no brasilAtualmente existem 30 partidos políticos oficializados no brasil
Atualmente existem 30 partidos políticos oficializados no brasilRoberto Rabat Chame
 
Leah Eustace AFP Toronto Congress 2008 Compressed
Leah Eustace AFP Toronto Congress 2008 CompressedLeah Eustace AFP Toronto Congress 2008 Compressed
Leah Eustace AFP Toronto Congress 2008 CompressedGood Works
 
Hill Claims Services Presentation Linkedin Ppt
Hill Claims Services Presentation Linkedin PptHill Claims Services Presentation Linkedin Ppt
Hill Claims Services Presentation Linkedin Pptkenbaker
 
Largestship
LargestshipLargestship
LargestshipMihaela
 
Discurso governador na assembleia
Discurso governador na assembleiaDiscurso governador na assembleia
Discurso governador na assembleiaRoberto Rabat Chame
 
Mit tennél a zenével?
Mit tennél a zenével?Mit tennél a zenével?
Mit tennél a zenével?Gabor Szabo
 
Ha A FéRfiak NevelnéK Smudla
Ha A FéRfiak NevelnéK SmudlaHa A FéRfiak NevelnéK Smudla
Ha A FéRfiak NevelnéK SmudlaGabor Szabo
 
Mandating Open Access - Wellcome Trust
Mandating Open Access - Wellcome TrustMandating Open Access - Wellcome Trust
Mandating Open Access - Wellcome TrustWellcome Library
 

Viewers also liked (20)

Common Denominator of Success
Common Denominator of SuccessCommon Denominator of Success
Common Denominator of Success
 
Festa de santa rita de cássia 2013
Festa de santa rita de cássia 2013Festa de santa rita de cássia 2013
Festa de santa rita de cássia 2013
 
Flowers
FlowersFlowers
Flowers
 
OBA - Social Media, Friend or Foe
OBA - Social Media, Friend or FoeOBA - Social Media, Friend or Foe
OBA - Social Media, Friend or Foe
 
February 2009 Newsletter
February 2009 NewsletterFebruary 2009 Newsletter
February 2009 Newsletter
 
Digwc
DigwcDigwc
Digwc
 
408 an 05_dezembro_2012.ok
408 an 05_dezembro_2012.ok408 an 05_dezembro_2012.ok
408 an 05_dezembro_2012.ok
 
Atualmente existem 30 partidos políticos oficializados no brasil
Atualmente existem 30 partidos políticos oficializados no brasilAtualmente existem 30 partidos políticos oficializados no brasil
Atualmente existem 30 partidos políticos oficializados no brasil
 
Leah Eustace AFP Toronto Congress 2008 Compressed
Leah Eustace AFP Toronto Congress 2008 CompressedLeah Eustace AFP Toronto Congress 2008 Compressed
Leah Eustace AFP Toronto Congress 2008 Compressed
 
Hill Claims Services Presentation Linkedin Ppt
Hill Claims Services Presentation Linkedin PptHill Claims Services Presentation Linkedin Ppt
Hill Claims Services Presentation Linkedin Ppt
 
Unit 1 4
Unit 1 4Unit 1 4
Unit 1 4
 
Unit 4
Unit 4Unit 4
Unit 4
 
Largestship
LargestshipLargestship
Largestship
 
Resultado ilhéus
Resultado ilhéusResultado ilhéus
Resultado ilhéus
 
Discurso governador na assembleia
Discurso governador na assembleiaDiscurso governador na assembleia
Discurso governador na assembleia
 
Mit tennél a zenével?
Mit tennél a zenével?Mit tennél a zenével?
Mit tennél a zenével?
 
Trabajo de tecnología
Trabajo de tecnologíaTrabajo de tecnología
Trabajo de tecnología
 
Ha A FéRfiak NevelnéK Smudla
Ha A FéRfiak NevelnéK SmudlaHa A FéRfiak NevelnéK Smudla
Ha A FéRfiak NevelnéK Smudla
 
Mandating Open Access - Wellcome Trust
Mandating Open Access - Wellcome TrustMandating Open Access - Wellcome Trust
Mandating Open Access - Wellcome Trust
 
Chapter2
Chapter2Chapter2
Chapter2
 

Similar to RMI Guide: Remote Method Invocation Explained

Similar to RMI Guide: Remote Method Invocation Explained (20)

Rmi
RmiRmi
Rmi
 
Rmi3
Rmi3Rmi3
Rmi3
 
Remote Method Invocation in JAVA
Remote Method Invocation in JAVARemote Method Invocation in JAVA
Remote Method Invocation in JAVA
 
Rmi
RmiRmi
Rmi
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method Invocation
 
Rmi
RmiRmi
Rmi
 
Java RMI
Java RMIJava RMI
Java RMI
 
Remote Method Invocation, Advanced programming
Remote Method Invocation, Advanced programmingRemote Method Invocation, Advanced programming
Remote Method Invocation, Advanced programming
 
Remote method invocatiom
Remote method invocatiomRemote method invocatiom
Remote method invocatiom
 
Remote Method Invocation (Java RMI)
Remote Method Invocation (Java RMI)Remote Method Invocation (Java RMI)
Remote Method Invocation (Java RMI)
 
ADB Lab Manual.docx
ADB Lab Manual.docxADB Lab Manual.docx
ADB Lab Manual.docx
 
Rmi
RmiRmi
Rmi
 
DS
DSDS
DS
 
Introduction To Rmi
Introduction To RmiIntroduction To Rmi
Introduction To Rmi
 
Remote Method Invocation
Remote Method InvocationRemote Method Invocation
Remote Method Invocation
 
Distributed Objects and JAVA
Distributed Objects and JAVADistributed Objects and JAVA
Distributed Objects and JAVA
 
Rmi
RmiRmi
Rmi
 
remote method invocation
remote method invocationremote method invocation
remote method invocation
 
A Short Java RMI Tutorial
A Short Java RMI TutorialA Short Java RMI Tutorial
A Short Java RMI Tutorial
 
Remote method invocation
Remote method invocationRemote method invocation
Remote method invocation
 

More from Adil Jafri

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5Adil Jafri
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net BibleAdil Jafri
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming ClientsAdil Jafri
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran TochAdil Jafri
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10Adil Jafri
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx TutorialsAdil Jafri
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbAdil Jafri
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12Adil Jafri
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash TutorialAdil Jafri
 

More from Adil Jafri (20)

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5
 
Php How To
Php How ToPhp How To
Php How To
 
Php How To
Php How ToPhp How To
Php How To
 
Owl Clock
Owl ClockOwl Clock
Owl Clock
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net Bible
 
Tcpip Intro
Tcpip IntroTcpip Intro
Tcpip Intro
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
 
Jsp Tutorial
Jsp TutorialJsp Tutorial
Jsp Tutorial
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10
 
Javascript
JavascriptJavascript
Javascript
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx Tutorials
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand Ejb
 
Html Css
Html CssHtml Css
Html Css
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12
 
Html Frames
Html FramesHtml Frames
Html Frames
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash Tutorial
 
C Programming
C ProgrammingC Programming
C Programming
 

Recently uploaded

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 

Recently uploaded (20)

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 

RMI Guide: Remote Method Invocation Explained

  • 1. 1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Remote Method Invocation
  • 2. Remote Method Invocation2 www.corewebprogramming.com Agenda • Steps to build and RMI application • Running and compiling an RMI program • Eample: Retrieving a String remotely • Example: Performing numerical integration remotely • Enterprise RMI configuration • RMI Applets
  • 3. Remote Method Invocation3 www.corewebprogramming.com RMI: Remote Method Invocation • Idea – Distribute objects across different machines to take advantage of hardware and dedicated software – Developer builds network service and installs it on specified machine – User requests an instance of a class using URL syntax – User uses object as though it were a regular, local object • Network connections happen automatically behind the scenes • Java “serialization” lets you pass complex data structures over the network without writing code to parse and reconstruct them
  • 4. Remote Method Invocation4 www.corewebprogramming.com RMI Operations • Stub Operation – Package identifier of remote object – Package method identifier – Marshall parameters – Send package to server skeleton • Skeleton Operation – Unmarshall Parameters – Calls return value or exception – Marshall method return – Send package to client stub
  • 5. Remote Method Invocation5 www.corewebprogramming.com RMI Details 1. Starting: Build Four Required Classes a. An interface for the remote object • Used by both the client and the server b. The RMI client • This will look up the object on the remote server, cast it to the type of the interface from Step 1, then use it like a local object. • Note that as long as there is a “live” reference to the remote object, an open network connection is maintained. The connection will be automatically closed when the remote object is garbage collected on the client. c. The object implementation • This object needs to implement the interface of Step a, and will be used by the server d. The RMI server • This will create an instance of the object from Step c and register it with a particular URL
  • 6. Remote Method Invocation6 www.corewebprogramming.com RMI Details, cont. 2. Compile and Run the System a. Compile client and server. • Compiles the remote object interface and implementation automatically b. Generate the client stub and the server skeleton • Use the rmic compiler on the remote object implementation for this. – The client system will need the client class, the interface class, and the client stub class – If the client is an applet, these three classes must be available from the applet’s home machine – The server system will need the server class, the remote object interface and implementation, and the server skeleton class
  • 7. Remote Method Invocation7 www.corewebprogramming.com RMI Details, cont. 2. Compile and Run the System, cont. c. Start the RMI registry • This only needs to be done once, not for each remote object • The current version of RMI requires this registry to be running on the same system as server d. Start the server • This step must be on the same machine as the registry of step c e. Start the client • This step can be done on an arbitrary machine
  • 8. Remote Method Invocation8 www.corewebprogramming.com A Very Simple RMI Example: The Four Required Classes 1. The Interface for the Remote Object – The interface should extend java.rmi.Remote, and all its methods should throw java.rmi.RemoteException import java.rmi.*; /** The RMI client will use this interface directly. * The RMI server will make a real remote object that * implements this, then register an instance of it * with some URL. */ public interface Rem extends Remote { public String getMessage() throws RemoteException; }
  • 9. Remote Method Invocation9 www.corewebprogramming.com Simple Example, Required Classes, cont. 2. The RMI Client – Look up the object from the host using Naming.lookup, cast it to the appropriate type, then use it like a local object import java.rmi.*; // For Naming, RemoteException, etc. import java.net.*; // For MalformedURLException import java.io.*; // For Serializable interface public class RemClient { public static void main(String[] args) { try { String host = (args.length > 0) ? args[0] : "localhost"; Rem remObject = (Rem)Naming.lookup("rmi://" + host + "/Rem"); System.out.println(remObject.getMessage()); } catch(RemoteException re) { System.out.println("RemoteException: " + re); } catch(NotBoundException nbe) { System.out.println("NotBoundException: " + nbe); } catch(MalformedURLException mfe) { System.out.println("MalformedURLException: " + mfe); } } }
  • 10. Remote Method Invocation10 www.corewebprogramming.com Simple Example, Required Classes, cont. 3. The Remote Object Implementation – This class must extend UnicastRemoteObject and implement the remote object interface defined earlier – The constructor should throw RemoteException import java.rmi.*; import java.rmi.server.UnicastRemoteObject; public class RemImpl extends UnicastRemoteObject implements Rem { public RemImpl() throws RemoteException {} public String getMessage() throws RemoteException { return("Here is a remote message."); } }
  • 11. Remote Method Invocation11 www.corewebprogramming.com Simple Example, Required Classes, cont. 4. The RMI Server – The server builds an object and register it with a particular URL – Use Naming.rebind (replace any previous bindings) or Naming.bind (throw AlreadyBoundException if a previous binding exists) import java.rmi.*; import java.net.*; public class RemServer { public static void main(String[] args) { try { RemImpl localObject = new RemImpl(); Naming.rebind("rmi:///Rem", localObject); } catch(RemoteException re) { System.out.println("RemoteException: " + re); } catch(MalformedURLException mfe) { System.out.println("MalformedURLException: " + mfe); } } }
  • 12. Remote Method Invocation12 www.corewebprogramming.com Simple Example: Compiling and Running the System 1. Compile the Client and the Server Prompt> javac RemClient.java – This compiles the Rem interface automatically Prompt> javac RemServer.java – This compiles the RemImpl object implementation automatically 2. Generate the Client Stub and Server Skeleton Prompt> rmic RemImpl – This builds RemImpl_Stub.class and RemImpl_Skeleton.class – The client machine needs Rem.class, RemClient.class, and RemImpl_Stub.class – The server machine needs Rem.class, RemImpl.class, RemServer.class, and RemImpl_Skeleton.class
  • 13. Remote Method Invocation13 www.corewebprogramming.com Simple Example: Compiling and Running the System, cont. 3. Start the RMI Registry Server> rmiregistry – On Unix systems you would probably add “&” to put the registry process in the background – You can also specify a port number; if omitted, port 1099 is used 4. Start the Server Server> java RemServer – Again, on Unix systems you would probably add “&” to put the process in the background 5. Start the Client Client> java RemClient hostname Here is a remote message.
  • 14. Remote Method Invocation14 www.corewebprogramming.com A Better RMI Example, Numerical Integration 1. Simple Iterative Program to Calculate Sums: 2. Use to Approximate Numeric Integrals of the Form: 3. MidPoint Rule: 4. Motivation for RMI – Since smaller rectangles typically give better results, this can often be very cpu-intensive – RMI can make it available on a fast floating-point box
  • 15. Remote Method Invocation15 www.corewebprogramming.com Numerical Integration, Example, cont. public class Integral { /** Returns the sum of f(x) from x=start to x=stop, where the function f * is defined by the evaluate method of the Evaluatable object. */ public static double sum(double start, double stop, double stepSize, Evaluatable evalObj) { double sum = 0.0, current = start; while (current <= stop) { sum += evalObj.evaluate(current); current += stepSize; } return(sum); } public static double integrate(double start, double stop, int numSteps, Evaluatable evalObj) { double stepSize = (stop - start) / (double)numSteps; start = start + stepSize / 2.0; return(stepSize * sum(start, stop, stepSize, evalObj)); } }
  • 16. Remote Method Invocation16 www.corewebprogramming.com Numerical Integration, Example, cont. /** An interface for evaluating functions y = f(x) at a specific * value. Both x and y are double-precision floating-point * numbers. */ public interface Evaluatable { public double evaluate(double value); }
  • 17. Remote Method Invocation17 www.corewebprogramming.com Integration Example: Four Required Classes 1. The RemoteIntegral Interface • The interface shared by the client and server import java.rmi.*; public interface RemoteIntegral extends Remote { public double sum(double start, double stop, double stepSize, Evaluatable evalObj) throws RemoteException; public double integrate(double start, double stop, int numSteps, Evaluatable evalObj) throws RemoteException;
  • 18. Remote Method Invocation18 www.corewebprogramming.com Integration Example: Four Required Classes, cont. 2. The Remote Integral Client • Sends the RemoteIntegral an Evaluatable to integrate public class RemoteIntegralClient { public static void main(String[] args) { try { String host = (args.length > 0) ? args[0] : "localhost"; RemoteIntegral remoteIntegral = (RemoteIntegral)Naming.lookup("rmi://" + host + "/RemoteIntegral"); for(int steps=10; steps<=10000; steps*=10) { System.out.println("Approximated with " + steps + " steps:" + "n Integral from 0 to pi of sin(x)=" + remoteIntegral.integrate(0.0, Math.PI, steps, new Sin())); } System.out.println("'Correct' answer using Math library:" + "n Integral from 0 to pi of sin(x)=" + (-Math.cos(Math.PI) - -Math.cos(0.0))); } catch(RemoteException re) { System.out.println("RemoteException: " + re); } catch(NotBoundException nbe) { System.out.println("NotBoundException: " + nbe); } catch(MalformedURLException mfe) { System.out.println("MalformedURLException: " + mfe); } } }
  • 19. Remote Method Invocation19 www.corewebprogramming.com Integration Example: Four Required Classes, cont. 2. The Remote Integral Client, cont. • Evaluatable Sin function import java.io.Serializable; class Sin implements Evaluatable, Serializable { public double evaluate(double val) { return(Math.sin(val)); } public String toString() { return("Sin"); } }
  • 20. Remote Method Invocation20 www.corewebprogramming.com Integration Example: Four Required Classes, cont. 3. The Remote Integral Implementation • Remote object that calculates the integral value import java.rmi.*; import java.rmi.server.UnicastRemoteObject; public class RemoteIntegralImpl extends UnicastRemoteObject implements RemoteIntegral { public RemoteIntegralImpl() throws RemoteException {} public double sum(double start, double stop, double stepSize, Evaluatable evalObj) { return(Integral.sum(start, stop, stepSize, evalObj)); } public double integrate(double start, double stop, int numSteps, Evaluatable evalObj) { return(Integral.integrate(start, stop, numSteps, evalObj)); } }
  • 21. Remote Method Invocation21 www.corewebprogramming.com Integration Example: Four Required Classes, cont. 4. The Remote Integral Server • Creates the RemoteIntegral and registers it with the rmi registry import java.rmi.*; import java.net.*; public class RemoteIntegralServer { public static void main(String[] args) { try { RemoteIntegralImpl integral = new RemoteIntegralImpl(); Naming.rebind("rmi:///RemoteIntegral", integral); } catch(RemoteException re) { System.out.println("RemoteException: " + re); } catch(MalformedURLException mfe) { System.out.println("MalformedURLException: " + mfe); } } }
  • 22. Remote Method Invocation22 www.corewebprogramming.com Integration Example: Compiling and Running the System 1. Compile the Client and the Server Prompt> javac RemoteIntegralClient.java Prompt> javac RemoteIntegralServer.java 2. Generate the Client Stub and Server Skeleton Prompt> rmic –v1.2 RemoteIntegralImpl – Client requires: RemoteIntegral.class, RemoteIntegralClient.class and RemoteIntegralImpl_Stub.class – Server requires: RemoteIntegral.class, RemoteIntegralImpl.class, and RemoteIntegralServer.class – If the server and client are both running JDK 1.1, use the -v1.1 switch to produce the RMI 1.1 skeleton stub, RemoteIntegralImpl_Skeleton, required by the server
  • 23. Remote Method Invocation23 www.corewebprogramming.com Integral Example: Compiling and Running the System, cont. 3. Start the RMI Registry Prompt> rmiregistry 4. Start the Server Prompt> java RemoteIntegralServer 5. Start the Client Prompt> java RemoteIntegralClient Approximated with 10 steps: Integral from 0 to pi of sin(x)=2.0082484079079745 Approximated with 100 steps: Integral from 0 to pi of sin(x)=2.0000822490709877 Approximated with 1000 steps: Integral from 0 to pi of sin(x)=2.0000008224672983 Approximated with 10000 steps: Integral from 0 to pi of sin(x)=2.00000000822436 ...
  • 24. Remote Method Invocation24 www.corewebprogramming.com Enterprise RMI Configuration • Stub files need to be placed on a HTTP server for downloading – In Java 2, the RMI 1.2 protocol does not require the skeleton • Client must install an RMISecurityManager to load the RMI classes remotely System.setSecurityManager(new RMISecurityManager()); • Client requires a policy file to connect to registry and HTTP server
  • 25. Remote Method Invocation25 www.corewebprogramming.com Policy File for Client grant { // rmihost - RMI registry and the server // webhost - HTTP server for stub classes permission java.net.SocketPermission "rmihost:1024-65535", "connect"; permission java.net.SocketPermission "webhost:80", "connect"; }; – Need to grant permission to ports 1024-65535 on the server • The server communicates with the rmiregistry (and client) on a randomly selected source port – Alternatively, can set policies in java.policy located in JAVA_HOME/lib/security/
  • 26. Remote Method Invocation26 www.corewebprogramming.com Enterprise RMI, Remote Integral, Example public class RemoteIntegralClient2 { public static void main(String[] args) { try { System.setSecurityManager(new RMISecurityManager()); String host = (args.length > 0) ? args[0] : "localhost"; RemoteIntegral remoteIntegral = (RemoteIntegral)Naming.lookup("rmi://" + host + "/RemoteIntegral"); for(int steps=10; steps<=10000; steps*=10) { System.out.println ("Approximated with " + steps + " steps:" + "n Integral from 0 to pi of sin(x)=" + remoteIntegral.integrate(0.0, Math.PI, steps, new Sin())); } ... } catch(RemoteException re) { System.out.println("RemoteException: " + re); } ... }
  • 27. Remote Method Invocation27 www.corewebprogramming.com Enterprise Example: Compiling and Running the System 1. Compile the Client and the Server Prompt> javac RemoteIntegralClient2.java Prompt> javac RemeteIntegralServer.java 2. Generate the Client Stub and Server Skeleton Prompt> rmic –v1.2 RemoteIntegralImpl 3. Place the files on the correct machines
  • 28. Remote Method Invocation28 www.corewebprogramming.com Enterprise Example: Compiling and Running the System, cont. 4. Start the HTTP Server • Place RemoteIntegral_Stub.class, RemoteIntegeral.class, and Evaluatable.class on an HTTP server • Verify that you can access the files through a browser 5. Start the RMI Registry Server> /somedirectory/rmiregistry • Make sure that none of the class files are in the directory in which you started the registry or available through the classpath 6. Start the Server Server> java -Djava.rmi.server.codebase=http://webhost/rmi/ RemoteIntegralServer – Server must be started on same host as rmiregistry
  • 29. Remote Method Invocation29 www.corewebprogramming.com Enterprise Example: Compiling and Running the System, cont. 7. Start the Client Client> java -Djava.security.policy=rmiclient.policy RemoteIntegralClient2 rmihost Approximated with 10 steps: Integral from 0 to pi of sin(x)=2.0082484079079745 Approximated with 100 steps: Integral from 0 to pi of sin(x)=2.0000822490709877 ... – The rmihost is where server in which the rmiregistry was started
  • 30. Remote Method Invocation30 www.corewebprogramming.com An RMI Applet • Applet does not require a RMI Security Manager • Applet can only access server in which class files were loaded – RMI Registry and remote object server must be the same HTTP host in which the applet was loaded • RMI 1.1 stub protocol not properly supported in IE • RMI 1.2 stub protocol require Java Plug-In or Netscape 6
  • 31. Remote Method Invocation31 www.corewebprogramming.com RMI Applet, Example ... import javax.swing.*; public class RemoteIntegralApplet extends JApplet implements ActionListener { private Evaluatable[] shapes; private RemoteIntegral remoteIntegral; private JLabel result; private JTextField startInput, stopInput, stepInput; private JComboBox combo; public void init() { String host = getCodeBase().getHost(); try { remoteIntegral = (RemoteIntegral)Naming.lookup("rmi://" + host + "/RemoteIntegral"); } catch(RemoteException re) { reportError("RemoteException: " + re); } ...
  • 32. Remote Method Invocation32 www.corewebprogramming.com RMI Applet, Example ... public void actionPerformed(ActionEvent event) { try { int steps = Integer.parseInt(stepInput.getText()); double start = Double.parseDouble(startInput.getText()); double stop = Double.parseDouble(stopInput.getText()); showStatus("Calculating ..."); Evaluatable shape = (Evaluatable)combo.getSelectedItem(); double area = remoteIntegral.integrate(start, stop, steps, shape); result.setText(Double.toString(area)); showStatus(""); } catch(NumberFormatException nfe) { reportError("Bad input: " + nfe); } catch(RemoteException re) { reportError("RemoteException: " + re); } } }
  • 33. Remote Method Invocation33 www.corewebprogramming.com RMI Applet, Result Applet that communicates to a remote object through RMI in Netscape 6
  • 34. Remote Method Invocation34 www.corewebprogramming.com Summary • RMI is a pure Java-based protocol for communicating with remote objects • Register (bind) and look-up remote objects in a registry • Java 2 no longer requires the skeleton class needed with the RMI 1.1 protocol • Enterprise RMI configuration requires a RMI Security Manager and client policy file for permissions
  • 35. 35 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Questions?