Title: Remote Method Invocation RMI
1Remote Method Invocation(RMI)
2Overview
- What is RMI
- RMI Process -- client and server
- A number of examples
3Remote Method Invocation (RMI)
- Can invoke methods on a remote object
- Integrates a distributed object model
- ORB compliant
- Extends security allowing dynamic downloading of
stub classes - Passes local objects by value (serialization)
- Passes remote objects by reference
4RMI Process (ten steps to success)
- Define an interface -- extends java.rmi.Remote,
all methods throw java.rim.Remote.Exception - Implement the interface -- server class that
extends java.rmi.UnicastRemoteObject - Compile the server class
- Run the stub compiler -- rmic -v1.2 classname
- Generates stub for client (skeleton for server in
older releases of Java)
5RMI Process (ten steps to success)
- Start the RMI registry (non-persistent naming
service) -- rmiregistry - Start the server objects -- load server classes
and create instances of remote objects - Register your remote objects with the registry --
use java.rmi.Naming class methods
6RMI Process (ten steps to success)
- Write your client code -- use java.rmi.Naming
class to locate remote object - Compile the client code
- Start the client
7RMI Interface
// CountRmi Interface public interface CountRMI
extends java.rmi.Remote int sum() throws
java.rmi.RemoteException void sum(int _val)
throws java.rmi.RemoteException public int
increment() throws java.rmi.RemoteException
8RMI Interface Implementation
// CountRMIImpl.java, CountRMI implementation impo
rt java.rmi. import java.rmi.server.UnicastRemot
eObject public class CountRMIImpl extends
UnicastRemoteObject implements CountRMI
private int sum
9RMI Interface Implementation
public CountRMIImpl(String name) throws
RemoteException super() try
Naming.rebind(name, this) sum 0 catch
(Exception e) System.out.println("Exception
" e.getMessage()) e.printStackTrace()
10RMI Interface Implementation
public int sum() throws RemoteException
return sum public void sum(int val)
throws RemoteException sum val
public int increment() throws RemoteException
sum return sum
11RMI Server
// CountRMIServer.java import java.rmi. import
java.rmi.server. public class CountRMIServer
public static void main(String args)
System.setSecurityManager(new RMISecurityManager()
) try CountRMIImpl myCount new
CountRMIImpl("my CountRMI")
System.out.println("CountRMI Server ready.")
catch (Exception e) System.out.println("Exc
eption " e.getMessage())
e.printStackTrace()
12RMI Client
// CountRMIClient.java RMI Count client import
java.rmi. import java.rmi.registry. import
java.rmi.server. public class CountRMIClient
public static void main(String args) //
Create and install the security manager
System.setSecurityManager(new RMISecurityManager()
)
13RMI Client
try CountRMI myCount (CountRMI)Naming.lookup("
rmi//" args0 "/"
"my CountRMI") System.out.println("Setting Sum
to 0") myCount.sum(0) long startTime
System.currentTimeMillis() System.out.println("
Incrementing") int count new
Integer(args1).intValue() for (int i 0 i
lt count i ) myCount.increment()
14RMI Client
long stopTime System.currentTimeMillis()
System.out.println("Avg Ping "
((stopTime - startTime)/(float)count
) " msecs")
System.out.println("Sum " myCount.sum())
catch(Exception e) System.err.println("Sys
tem Exception" e) System.exit(0)
15RMI Load Server and Client
16RMI Example Output
On the Server Count RMI Server ready. On the
Client Setting sum to 0 Incrementing Avg Ping
14.83 msecs Sum 500
17RMI Related classes and interfaces
- RemoteException -- superclass for all RMI
exceptions. All remote methods must throw a
RemoteException - Remote -- interface that flags remote objects
(contains no methods) - RemoteObject -- remote version of the Java root
Object class - RemoteServer -- class to define methods to create
server objects and export them
18RMI Related classes and interfaces
- UnicastRemoteObject -- class implements a remote
server object - object only exists as long as the process that
created it - requires a TCP connection based transport
- client and server use a stream protocol to
communicate - RemoteStub -- class is superclass for all client
stubs
19RMI Related classes and interfaces
- Registry interface -- methods let you update
entries in a registry - LocateRegistry class -- overloaded getRegistry()
static methods to find a registry - Naming class -- retrieve and define remote
objects using URL syntax - rmi//hostport/name (port usually 1099)
- Client uses lookup() method, host uses rebind()
method
20RMI Related classes and interfaces
- RMISecurityManager class -- simple security
manager for RMI objects (Applets have their own
security classes) - RMIClassLoader class -- load stubs (and
skeletons) via a URL
21RMI and CORBA (Common Object Request Broker
Architecture)
- Moving toward one way in cooperation with OMG
(Object Management Group consortium) - RMI over IIOP (Internet InterORB Protocol) -- now
offered by JavaSoft - RMI/IDL (Interface Definition Language) -- use
Java syntax to specify CORBA interfaces
22Another RMI Example
// Fig. 20.1 TemperatureServer.java //
TemperatureServer interface definition import
java.rmi. public interface TemperatureServer
extends Remote public WeatherInfo
getWeatherInfo() throws RemoteException
23Another RMI Example
// Fig. 20.2 TemperatureServerImpl.java //
TemperatureServerImpl definition import
java.rmi. import java.rmi.server. import
java.util. import java.io. import
java.net. public class TemperatureServerImpl
extends UnicastRemoteObject
implements TemperatureServer
private WeatherInfo weatherInformation
public TemperatureServerImpl() throws
RemoteException super()
updateWeatherConditions()
24Another RMI Example
// get weather information from NWS private void
updateWeatherConditions() throws
RemoteException try
System.err.println( "Updating weather
information..." ) // Traveler's Forecast
Web Page URL url new URL(
"http//iwin.nws.noaa.gov/iwin/us/traveler.html"
) BufferedReader in new
BufferedReader( new
InputStreamReader( url.openStream() ) )
String separator "ltTTgtltPREgt"
25Another RMI Example
// locate first horizontal line on Web page while
( !in.readLine().startsWith( separator ) )
// do nothing // s1 is the day format and s2 is
the night format String s1 "CITY
WEA HI/LO WEA HI/LO" String s2
"CITY WEA LO/HI WEA
LO/HI" String inputLine "" // locate header
that begins weather information do inputLine
in.readLine() while ( !inputLine.equals( s1
) !inputLine.equals( s2 ) )
26Another RMI Example
Vector cityVector new Vector() inputLine
in.readLine() // get first city's info while (
inputLine.length() gt 29 ) // create
WeatherInfo object for city WeatherInfo w
new WeatherInfo( inputLine.substring( 0, 16
), inputLine.substring( 16, 22 ),
inputLine.substring( 23, 29 ) )
cityVector.addElement( w ) // add to Vector
inputLine in.readLine() // get next city's
info // create array to return to
client weatherInformation new WeatherInfo
cityVector.size() for ( int i 0 i lt
weatherInformation.length i )
weatherInformation i ( WeatherInfo )
cityVector.elementAt( i )
27Another RMI Example
System.err.println( "Finished Processing Data."
) in.close() // close connection to NWS
server catch( java.net.ConnectException
ce ) System.err.println( "Connection
failed." ) System.exit( 1 )
catch( Exception e ) e.printStackTrace()
System.exit( 1 )
28Another RMI Example
// implementation for TemperatureServer
interface method public WeatherInfo
getWeatherInfo() return
weatherInformation public static void
main( String args ) throws Exception
System.err.println( "Initializing
server please wait." ) // create server
object TemperatureServerImpl temp
new TemperatureServerImpl() // bind
TemperatureServerImpl object to the rmiregistry
String serverObjectName "TempServer"
Naming.rebind( serverObjectName, temp )
System.err.println( "The Temperature
Server is up and running." )
29Another RMI Example
// Fig. 20.3 WeatherInfo.java // WeatherInfo
class definition import java.rmi. import
java.io.Serializable public class WeatherInfo
implements Serializable private String
cityName private String temperature
private String description public
WeatherInfo( String city, String desc, String
temp ) cityName city
temperature temp description desc
public String getCityName() return
cityName public String getTemperature()
return temperature public String
getDescription() return description
30Another RMI Example
// Fig. 20.4 TemperatureClient.java //
TemperatureClient definition import
java.awt. import java.awt.event. import
javax.swing. import java.rmi. public class
TemperatureClient extends JFrame public
TemperatureClient( String ip ) super(
"RMI TemperatureClient..." )
getRemoteTemp( ip ) setSize( 625, 567 )
setResizable( false ) show()
31Another RMI Example
// obtain weather information from
TemperatureServerImpl // remote object private
void getRemoteTemp( String ip ) try
// name of remote server object bound to rmi
registry String serverObjectName "//"
ip "/TempServer" // lookup
TemperatureServerImpl remote object // in
rmiregistry TemperatureServer mytemp (
TemperatureServer ) Naming.lookup(
serverObjectName ) // get weather
information from server WeatherInfo
weatherInfo mytemp.getWeatherInfo()
WeatherItem w new WeatherItem
weatherInfo.length ImageIcon headerImage
new ImageIcon( "images/header.jpg" )
JPanel p new JPanel()
32Another RMI Example
// determine number of rows for the
GridLayout // add 3 to accommodate the two
header JLabels // and balance the
columns p.setLayout( new GridLayout( (
w.length 3 ) / 2, 2 ) ) p.add( new JLabel(
headerImage ) ) // header 1 p.add( new JLabel(
headerImage ) ) // header 2 for ( int i 0 i
lt w.length i ) w i new WeatherItem(
weatherInfo i ) p.add( w i )
33Another RMI Example
getContentPane().add( new JScrollPane( p
), BorderLayout.CENTER
) catch ( java.rmi.ConnectException ce )
System.err.println( "Connection to server
failed. " "Server may be temporarily
unavailable." ) catch ( Exception e )
e.printStackTrace() System.exit( 1
)
34Another RMI Example
public static void main( String args )
TemperatureClient gt null // if no
sever IP address or host name specified, //
use "localhost" otherwise use specified host
if ( args.length 0 ) gt new
TemperatureClient( "localhost" ) else
gt new TemperatureClient( args 0 )
gt.addWindowListener( new
WindowAdapter() public void
windowClosing( WindowEvent e )
System.exit( 0 )
)
35Another RMI Example
// Fig. 20.5 WeatherItem.java // WeatherItem
definition import java.awt. import
javax.swing. public class WeatherItem extends
JLabel private static ImageIcon
weatherImages, backgroundImage private
final static String weatherConditions
"SUNNY", "PTCLDY", "CLOUDY", "MOCLDY", "TSTRMS",
"RAIN", "SNOW", "VRYHOT", "FAIR",
"RNSNOW", "SHWRS", "WINDY", "NOINFO",
"MISG" private final static String
weatherImageNames "sunny", "pcloudy",
"mcloudy", "mcloudy", "rain", "rain",
"snow", "vryhot", "fair", "rnsnow",
"showers", "windy", "noinfo", "noinfo"
36Another RMI Example
// static initializer block to load weather
images static backgroundImage new
ImageIcon( "images/back.jpg" ) weatherImages
new ImageIcon weatherImageNames.length
for ( int i 0 i lt weatherImageNames.leng
th i ) weatherImages i new
ImageIcon( "images/"
weatherImageNames i ".jpg" ) // instance
variables private ImageIcon weather private
WeatherInfo weatherInfo
37Another RMI Example
public WeatherItem( WeatherInfo w ) weather
null weatherInfo w // locate image
for city's weather condition for ( int i 0
i lt weatherConditions.length i ) if (
weatherConditions i .equals(
weatherInfo.getDescription().trim() ) )
weather weatherImages i break
// pick the "no info" image if either
there is no // weather info or no image for
the current // weather condition if (
weather null ) weather
weatherImages weatherImages.length - 1
System.err.println( "No info for "
weatherInfo.getDescription() )
38Another RMI Example
public void paintComponent( Graphics g )
super.paintComponent( g )
backgroundImage.paintIcon( this, g, 0, 0 )
Font f new Font( "SansSerif", Font.BOLD, 12 )
g.setFont( f ) g.setColor(
Color.white ) g.drawString(
weatherInfo.getCityName(), 10, 19 )
g.drawString( weatherInfo.getTemperature(), 130,
19 ) weather.paintIcon( this, g, 253, 1
) // make WeatherItem's preferred size
the width and height of // the background
image public Dimension getPreferredSize()
return new Dimension( backgroundImage.getI
conWidth(),
backgroundImage.getIconHeight() )
39Another RMI Example
Server
java -Djava.rmi.server.codebasehttp//komar.cs.st
thomas.edu/classes/ -Djava.rmi.hostnamek
omar.cs.stthomas.edu -Djava.security.polic
yjava.policy TemperatureServerImpl
Client
java -Djava.rmi.server.codebasehttp//komar.cs.st
thomas.edu/classes/ -Djava.security.polic
yjava.policy TemperatureClient
komar.cs.stthomas.edu
40Another RMI Example
41RMI Assignment
- Create the Java code needed to do the following
using RMI - Perform addition, subtraction, multiplication, or
division by executing a remote objects method - That remote method will accept three parameters
(character operator, double val1, double val2)
and return the resulting double
42Summary
- What is RMI
- RMI Process -- client and server
- A number of examples