Unit-IV; Professional Sales Representative (PSR).pptx
ADV JAVA UNIT 2 M.SC CS (1).pdf
1. SRI VASAVI COLLEGE,ERODE
(Self -Finance Wing)
Department of Computer Science
I-M.Sc (CS)
Advanced Java Programming
Unit-2
Presented by
P.KALAISELVI
Assistant Professor
Department of Computer Science
2. 5/24/2022
Remote Method Invocation
Remote Method Invocation (RMI) is a Java mechanism
similar to RPCs.
RMI allows a Java program on one machine to invoke a
method on a remote object.
4. 5/24/2022
Remote Method Invocation
RMI and RPC differs in two ways:
1. RPCs support procedural programming whereby only
remote procedures or functions may be called. RMI is
object based: It supports invocation of methods on
remote objects.
2. The parameters to remote procedures are ordinary
data structures in RPC; with RMI it is possible to pass
objects as parameters to remote methods.
If the marshaled parameters are local (non remote)
objects, they are passed by copy using a technique
known as object serialization.
◦ Object serialization allowed the state of an
object to be written toa byte stream.
5. 5/24/2022
Introduction to RMI
Remote Method Invocation (RMI)
◦ Allows remote method calls
Objects in different programs can communicate
Method calls appear same as those in same program
◦ Based on Remote Procedure Calls (RPC)
Developed in 1980's
Allows procedural program (like C) to call function on
another computer
Performs networking and marshalling of data (packaging
arguments and return values)
Not compatible with objects
Interface Definition Language required - describe
functions
◦ RMI is Java's implementation of RPC
6. 5/24/2022
Introduction to RMI
RMI
◦ Register method as remotely accessible
Client can look up method and receive a reference
Use reference to call method
Syntax same as a normal method call
◦ Marshalling of data
Can transfer objects as well
Class ObjectOutputStream converts
Serializable object into stream of bytes
Transmit across network
Class ObjectInputStream reconstructs object
◦ No Interface Definition Language needed
Use Java's own interface
7. 5/24/2022
Case Study: Creating a
Distributed System with RMI
RMI example
◦ Downloads weather information from National
Weather Service website
http://iwin.nws.noaa.gov/iwin/us/traveler.html
Note: Format of website changed several times, if
example does not work do the appropriate
modifications.
◦ Store information on a server
Request information through remote method calls
9. 5/24/2022
Case Study: Creating a
Distributed System with RMI
Four major steps
◦ Define remote interface
Describes client/server communication
◦ Define server application to implement
remote interface
Same name as remote interface, ends with Impl
◦ Define client application that uses remote
interface reference
Interacts with server implementation
◦ Compile and execute server and client
10. 5/24/2022
Defining the Remote Interface
First step
◦ Define remote interface that describes remote
methods
Client calls remote methods, server implements them
To create a remote interface
◦ Define interface that extends interface Remote
(java.rmi)
Tagging interface - no methods to define
An object of a class that implements interface Remote
directly or indirectly is a remote object and can be accesses
from any JVM.
◦ Each method in Remote interface must throw
RemoteException
Potential network errors
12. 5/24/2022
1. import
1.1 extends Remote
2. getWeatherInfo
2.1 throws RemoteException
1 // Fig. 20.1: TemperatureServer.java
2 // TemperatureServer interface definition
3 import java.rmi.*;
4
5 public interface TemperatureServer extends Remote {
6 public WeatherInfo[] getWeatherInfo()
7 throws RemoteException;
8 }
Interface Remote in java.rmi
Methods in Remote interface (is a relationship)
must be able to throw a RemoteException.
13. 5/24/2022
Implementing the Remote
Interface
Define TemperatureServerImpl
◦ Implements Remote interface
TemperatureServer
◦ Client interacts with
TemperatureServerImpl object
◦ Uses array of WeatherInfo objects to store
data
Copy sent to client when calls getWeatherInfo
14. 5/24/2022
Implementing the Remote Interface
◦ UnicastRemoteObject
Provides functionality for remote objects
Constructor exports object so it can receive remote calls
Wait for client on anonymous port number
Subclass constructors must throw RemoteExceptions
◦ URL object
Contains URL for Traveler's Forecast web page
Throws MalformedURLException
18 public class TemperatureServerImpl extends UnicastRemoteObject
19 implements TemperatureServer {
22 public TemperatureServerImpl() throws RemoteException
37 URL url = new URL(
38 "http://iwin.nws.noaa.gov/iwin/us/traveler.html" );
15. 5/24/2022
Implementing the Remote Interface
◦ Open connection to file specified by URL
◦ Method openStream (class URL)
Opens network connection using Http protocol
If successful, InputStream object returned (else
IOException)
◦ InputStreamReader
Translates bytes to Unicode characters
◦ BufferedReader
Buffers characters
Method readLine
Returns one line as a String
40 BufferedReader in =
41 new BufferedReader(
42 new InputStreamReader( url.openStream() ) );
16. 5/24/2022
Implementing the Remote
Interface
◦ Sentinel String to find relevant part of
HTML code
readLine until sentinel found
◦ A string used as column head
Second "WEA HI/LO" is for next day, we do not
use
◦ Locate column head and get first city's info
44 String separator = "</PRE><HR> <BR><PRE>";
47 while ( !in.readLine().startsWith( separator ) )
48 ; // do nothing
51 String s1 =
52 "CITY WEA HI/LO WEA HI/LO";
66 inputLine = in.readLine(); // get first city's info
17. 5/24/2022
Implementing the Remote Interface
◦ WeatherInfo objects
City name, temperature, description of weather
Method substring to extract data from line
Store all WeatherInfo objects in a Vector
◦ Store data in WeatherInfo array
elementAt returns Object (must be cast)
◦ Close connection
70 WeatherInfo w = new WeatherInfo(
71 inputLine.substring( 0, 16 ),
72 inputLine.substring( 16, 22 ),
73 inputLine.substring( 23, 29 ) );
75 cityVector.addElement( w ); // add to Vector
84 weatherInformation[ i ] =
85 ( WeatherInfo ) cityVector.elementAt( i );
88 in.close(); // close connection to NWS server
18. 5/24/2022
Implementing the Remote Interface
◦ Name of server object
Used by clients to connect
//host:port/remoteObjectName
host - computer running registry for remote objects
Where remote object executes
port - port number of registry on host (1099 default)
remoteObjectName - client uses to locate object
◦ Registry managed by rmiregistry (located
at host and port)
Remote objects register with it, clients use it to locate
service
localhost (same computer)
Same as IP 127.0.0.1
116 String serverObjectName = "//localhost/TempServer";
19. 5/24/2022
Implementing the Remote Interface
◦ static method rebind (class Naming)
Binds object to rmiregistry
Named //localhost/TempServer
Name used by client
rebind replaces any previous objects with same
name
Method bind does not
117 Naming.rebind( serverObjectName, temp );
112 TemperatureServerImpl temp =
113 new TemperatureServerImpl();
116 String serverObjectName = "//localhost/TempServer";
20. 5/24/2022
1.Interface
------------------
1.extends UnicastRemote Object,implements TemperatureServer
1.1 Constructor
1 // Fig. 20.1: TemperatureServer.java
2 // TemperatureServer interface definition
3 import java.rmi.*;
4
5 public interface TemperatureServer extends Remote {
6 public WeatherInfo[] getWeatherInfo()
7 throws RemoteException;
8 }
9 TemperatureServer interface.
10 // Fig. 20.2: TemperatureServerImpl.java
11 // TemperatureServerImpl definition
12 import java.rmi.*;
13 import java.rmi.server.*;
14 import java.util.*;
15 import java.io.*;
16 import java.net.*;
17
18 public class TemperatureServerImpl extends UnicastRemoteObject
19 implements TemperatureServer {
20 private WeatherInfo weatherInformation[];
21
22 public TemperatureServerImpl() throws RemoteException
23 {
24 super();
25 updateWeatherConditions();
26 }
27
Allows objects to be exported.
Superclass constructor exports objects, and
this constructor must be able to throw
RemoteException.
21. 5/24/2022
2. updateWeather Conditions
2.1 URL
2.2 BufferedReader
2.3 readLine
34 "Updating weather information..." );
35
36 // Traveler's Forecast Web Page
37 URL url = new URL(
38 "http://iwin.nws.noaa.gov/iwin/us/traveler.html" );
39
40 BufferedReader in =
41 new BufferedReader(
42 new InputStreamReader( url.openStream() ) );
43
44 String separator = "</PRE><HR> <BR><PRE>";
45
46 // locate first horizontal line on Web page
47 while ( !in.readLine().startsWith( separator ) )
48 ; // do nothing
49
50 // s1 is the day format and s2 is the night format
51 String s1 =
52 "CITY WEA HI/LO WEA HI/LO";
53 String s2 =
54 "CITY WEA LO/HI WEA LO/HI";
55 String inputLine = "";
56
28 // get weather information from NWS
29 private void updateWeatherConditions()
30 throws RemoteException
31 {
32 try {
33 System.err.println(
URL of web site (URL object).
Open connection to file.
InputStreamReader formats it to Unicode
characters, and BufferedReader buffers the
characters.
readLine until separator found.
22. 5/24/2022
2.4 Locate header
2.5 Loop
2.5.1 WeatherInfo
2.5.2 readLine
2.6 WeatherInfo array
67
68 while ( !inputLine.equals( "" ) ) {
69 // create WeatherInfo object for city
70 WeatherInfo w = new WeatherInfo(
71 inputLine.substring( 0, 16 ),
72 inputLine.substring( 16, 22 ),
73 inputLine.substring( 23, 29 ) );
74
75 cityVector.addElement( w ); // add to Vector
76 inputLine = in.readLine(); // get next city's info
77 }
78
79 // create array to return to client
80 weatherInformation =
81 new WeatherInfo[ cityVector.size() ];
82
83 for ( int i = 0; i < weatherInformation.length; i++ )
84 weatherInformation[ i ] =
85 ( WeatherInfo ) cityVector.elementAt( i );
86
62
63
64 Vector cityVector = new Vector();
65
66 inputLine = in.readLine(); // get first city's info
57 // locate header that begins weather information
58 do {
59 inputLine = in.readLine();
60 } while ( !inputLine.equals( s1 ) &&
61 !inputLine.equals( s2 ) ); Create WeatherInfo object, add data
(substring), add to Vector. Loop until
blank line reached.
Create WeatherInfo array, cast
Vector elements.
23. 5/24/2022
2.7 close
3. getWeatherInfo
4. main
4.1 temp
100 // implementation for TemperatureServer interface method
101 public WeatherInfo[] getWeatherInfo()
102 {
103 return weatherInformation;
104 }
105
106 public static void main( String args[] ) throws Exception
107 {
108 System.err.println(
109 "Initializing server: please wait." );
110
111 // create server object
112 TemperatureServerImpl temp =
113 new TemperatureServerImpl();
114
87 System.err.println( "Finished Processing Data." );
88 in.close(); // close connection to NWS server
89 }
90 catch( java.net.ConnectException ce ) {
91 System.err.println( "Connection failed." );
92 System.exit( 1 );
93 }
94 catch( Exception e ) {
95 e.printStackTrace();
96 System.exit( 1 );
97 }
98 }
99
Return the WeatherInfo array.
24. 5/24/2022
4.2 serverObjectName
4.3 rebind
115 // bind TemperatureServerImpl object to the rmiregistry
116 String serverObjectName = "//localhost/TempServer";
117 Naming.rebind( serverObjectName, temp );
118 System.err.println(
119 "The Temperature Server is up and running." );
120 }
121}
Name of server object.
rebind binds object to
rmiregistry.
25. 5/24/2022
1. Class WeatherInfo implements Serializable
1. Instance variables
1.1 Constructor
2. Get methods
1 / Fig. 20.3: WeatherInfo.java
2 // WeatherInfo class definition
3 import java.rmi.*;
4 import java.io.Serializable;
5
6 public class WeatherInfo implements Serializable {
7 private String cityName;
8 private String temperature;
9 private String description;
10
11 public WeatherInfo( String city, String desc, String temp )
12 {
13 cityName = city;
14 temperature = temp;
15 description = desc;
16 }
17
18 public String getCityName() { return cityName; }
19
20 public String getTemperature() { return temperature; }
21
22 public String getDescription() { return description; }
23 }
This allows objects to be passed as a
stream of bytes.
26. 5/24/2022
Define the client
Next step
◦ Client code to get weather info from
TemperatureServerImpl
◦ Calls getWeatherInfo through RMI
◦ Graphically display weather info
Class WeatherItem (extends JLabel) stores
info about each city
Display name, High/low, and image (depending on
conditions)
27. 5/24/2022
Define the client
◦ Can specify IP address at command line (more
later)
◦ static method lookup (class Naming)
◦ Returns reference to Remote object
Cast to TemperatureServer
◦ Reference may be used as normal
Only difference that copy of array returned
22 private void getRemoteTemp( String ip )
26 String serverObjectName = "//" + ip + "/TempServer";
30 TemperatureServer mytemp = ( TemperatureServer )
31 Naming.lookup( serverObjectName );
34 WeatherInfo weatherInfo[] = mytemp.getWeatherInfo();
28. 5/24/2022
Define the client
◦ Add WeatherItems
Initialize with WeatherInfo
◦ main
Passes command line argument (ip) to constructor
localhost default
40 JPanel p = new JPanel();
50 for ( int i = 0; i < w.length; i++ ) {
51 w[ i ] = new WeatherItem( weatherInfo[ i ]
);
52 p.add( w[ i ] );
53 }
68 public static void main( String args[] )
69 {
70 TemperatureClient gt = null;
74 if ( args.length == 0 )
75 gt = new TemperatureClient( "localhost" );
76 else
77 gt = new TemperatureClient( args[ 0 ] );
29. 5/24/2022
Define the client
Class WeatherItem
◦ extends JLabel
◦ static initializer block
For complex initialization of static variables
backgroundImage - ImageIcon, has
background
weatherImages - ImageIcon array, holds
weather images
18 static {
19 backgroundImage = new ImageIcon( "images/back.jpg" );
20 weatherImages =
21 new ImageIcon[ weatherImageNames.length ];
22
23 for ( int i = 0; i < weatherImageNames.length; ++i )
24 weatherImages[ i ] = new ImageIcon(
25 "images/" + weatherImageNames[ i ] + ".jpg" );
26 }
30. 5/24/2022
Define the client
◦ Array of descriptions and matching array of
images
weatherConditions and weatherImages
◦ Tests WeatherInfo object, loads proper
image
35 weatherInfo = w;
38 for ( int i = 0; i < weatherConditions.length;
++i )
39 if ( weatherConditions[ i ].equals(
40 weatherInfo.getDescription().trim() ) )
{
41 weather = weatherImages[ i ];
32 public WeatherItem( WeatherInfo w )
31. 5/24/2022
1. import
1.1 Constructor
2. getRemoteTemp
2.1 serverObjectName
2.2 Naming.lookup
1 // Fig. 20.4: TemperatureClient.java
2 // TemperatureClient definition
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6 import java.rmi.*;
7
8 public class TemperatureClient extends JFrame
9 {
10 public TemperatureClient( String ip )
11 {
12 super( "RMI TemperatureClient..." );
13 getRemoteTemp( ip );
14
15 setSize( 625, 567 );
16 setResizable( false );
17 show();
18 }
19
20 // obtain weather information from TemperatureServerImpl
21 // remote object
22 private void getRemoteTemp( String ip )
23 {
24 try {
25 // name of remote server object bound to rmi registry
26 String serverObjectName = "//" + ip + "/TempServer";
27
28 // lookup TemperatureServerImpl remote object
29 // in rmiregistry
30 TemperatureServer mytemp = ( TemperatureServer )
31 Naming.lookup( serverObjectName );
Use ip specified at command line.
Lookup remote object in
registry. Returns Remote
reference, cast to proper
type.
32. 5/24/2022
2.3 getWeatherInfo
2.4 GUI
2.4.1 WeatherItem
34 WeatherInfo weatherInfo[] = mytemp.getWeatherInfo();
35 WeatherItem w[] =
36 new WeatherItem[ weatherInfo.length ];
37 ImageIcon headerImage =
38 new ImageIcon( "images/header.jpg" );
39
40 JPanel p = new JPanel();
41
42 // determine number of rows for the GridLayout;
43 // add 3 to accommodate the two header JLabels
44 // and balance the columns
45 p.setLayout(
46 new GridLayout( ( w.length + 3 ) / 2, 2 ) );
47 p.add( new JLabel( headerImage ) ); // header 1
48 p.add( new JLabel( headerImage ) ); // header 2
49
50 for ( int i = 0; i < w.length; i++ ) {
51 w[ i ] = new WeatherItem( weatherInfo[ i ] );
52 p.add( w[ i ] );
53 }
54
55 getContentPane().add( new JScrollPane( p ),
56 BorderLayout.CENTER );
57 }
58 catch ( java.rmi.ConnectException ce ) {
59 System.err.println( "Connection to server failed. " +
60 "Server may be temporarily unavailable." );
61 }
32
33 // get weather information from server
Call like regular method.
33. 5/24/2022
3. main
3.1 args[ 0 ]
67
68 public static void main( String args[] )
69 {
70 TemperatureClient gt = null;
71
72 // if no sever IP address or host name specified,
73 // use "localhost"; otherwise use specified host
74 if ( args.length == 0 )
75 gt = new TemperatureClient( "localhost" );
76 else
77 gt = new TemperatureClient( args[ 0 ] );
78
79 gt.addWindowListener(
80 new WindowAdapter() {
81 public void windowClosing( WindowEvent e )
82 {
83 System.exit( 0 );
84 }
85 }
86 );
87 }
88 }
62 catch ( Exception e ) {
63 e.printStackTrace();
64 System.exit( 1 );
65 }
66 }
args[ 0 ] is the first
argument, which should be
the IP address.
34. 5/24/2022
1. Class WeatherItem
1.1 static variables
1.2 Initializer block
1.3 Load ImageIcons
1 // Fig. 20.5: WeatherItem.java
2 // WeatherItem definition
3 import java.awt.*;
4 import javax.swing.*;
5
6 public class WeatherItem extends JLabel {
7 private static ImageIcon weatherImages[], backgroundImage;
8 private final static String weatherConditions[] =
9 { "SUNNY", "PTCLDY", "CLOUDY", "MOCLDY", "TSTRMS",
10 "RAIN", "SNOW", "VRYHOT", "FAIR", "RNSNOW",
11 "SHWRS", "WINDY", "NOINFO", "MISG" };
12 private final static String weatherImageNames[] =
13 { "sunny", "pcloudy", "mcloudy", "mcloudy", "rain",
14 "rain", "snow", "vryhot", "fair", "rnsnow",
15 "showers", "windy", "noinfo", "noinfo" };
16
17 // static initializer block to load weather images
18 static {
19 backgroundImage = new ImageIcon( "images/back.jpg" );
20 weatherImages =
21 new ImageIcon[ weatherImageNames.length ];
22
23 for ( int i = 0; i < weatherImageNames.length; ++i )
24 weatherImages[ i ] = new ImageIcon(
25 "images/" + weatherImageNames[ i ] + ".jpg" );
26 }
27
28 // instance variables
29 private ImageIcon weather;
30 private WeatherInfo weatherInfo;
Use names in weatherImageNames
array to load ImageIcons.
35. 5/24/2022
2. Constructor
2.1 Compare conditions
3. paintComponent
3.1 paintIcon
34 weather = null;
35 weatherInfo = w;
36
37 // locate image for city's weather condition
38 for ( int i = 0; i < weatherConditions.length; ++i )
39 if ( weatherConditions[ i ].equals(
40 weatherInfo.getDescription().trim() ) ) {
41 weather = weatherImages[ i ];
42 break;
43 }
44
45 // pick the "no info" image if either there is no
46 // weather info or no image for the current
47 // weather condition
48 if ( weather == null ) {
49 weather = weatherImages[ weatherImages.length - 1 ];
50 System.err.println( "No info for: " +
51 weatherInfo.getDescription() );
52 }
53 }
54
55 public void paintComponent( Graphics g )
56 {
57 super.paintComponent( g );
58 backgroundImage.paintIcon( this, g, 0, 0 );
59
31
32 public WeatherItem( WeatherInfo w )
33 {
Loop though weatherConditions and
compare to getDescription.
Attach background to WeatherItem.
36. 5/24/2022
3.2 drawString
3.3 paintIcon
67 }
68
69 // make WeatherItem's preferred size the width and height of
70 // the background image
71 public Dimension getPreferredSize()
72 {
73 return new Dimension( backgroundImage.getIconWidth(),
74 backgroundImage.getIconHeight() );
75 }
76 }
60 Font f = new Font( "SansSerif", Font.BOLD, 12 );
61 g.setFont( f );
62 g.setColor( Color.white );
63 g.drawString( weatherInfo.getCityName(), 10, 19 );
64 g.drawString( weatherInfo.getTemperature(), 130, 19 );
65
66 weather.paintIcon( this, g, 253, 1 );
Draw city name, high/low, and attach
weather image to WeatherItem.
37. 5/24/2022
Compile and Execute the
Server and the Client
Build and execute application
◦ All pieces in place
◦ Compile classes with javac
◦ Remote server class
(TemperatureServerImpl) compiled
with rmic compiler
Makes a stub class - allows client to access remote
methods and server to provide its services
Gets remote method calls, passes to RMI system,
which performs networking
rmic TemperatureServerImpl
38. 5/24/2022
Compile and Execute the
Server and the Client
Start rmiregistry
◦ Type rmiregistry at command window
No text in response
39. 5/24/2022
Compile and Execute the
Server and the Client
Must bind remote server object
◦ RunTemperatureServerImpl application
java TemperatureServerImpl
◦ Superclass UnicastRemoteObject
Constructor exports remote object
main binds object to rmiregistry
rmiregistry provides host and port number to
clients
40. 5/24/2022
Compile and Execute the
Server and the Client
ExecuteTemperatureClient
◦ javaTemperatureClient
◦ If server on different machine, specify IP on
command line
java TemperatureClient
192.168.150.4
◦ Result on next slide
42. Defining Remote Objects
Now that you have a basic idea of how Java RMI
works, we can explore the details of creating and
using distributed objects with RMI in more detail. As
mentioned earlier, defining a remote RMI object
involves specifying a remote interface for the object,
then providing a class that implements this interface.
The remote interface and implementation class are
then used by RMI to generate a client stub and
server skeleton for your remote object. The
communication between local objects and remote
objects is handled using these client stubs and server
skeletons. The relationships among stubs, skeletons,
and the objects that use them are shown in Figure 3
5/24/2022
43. When a client gets a reference to a remote object (details on how this
reference is obtained come later) and then calls methods on this object
reference, there needs to be a way for the method request to get transmitted
back to the actual object on the remote server and for the results of the
method call to get transmitted back to the client. This is what the generated
stub and skeleton classes are for. They act as the communication link between
the client and your exported remote object,making it seem to the client that
the object actually exists within its JavaVM.
5/24/2022
44. The RMI compiler ( rmic) automatically generates these
stub and skeleton classes for you. Based on the remote
interface and implementation class you provide,rmic
generates stub and skeleton classes that implement the
remote interface and act as go-betweens for the client
application and the actual server object. For the client stub
class, the compiler generates an implementation of each
remote method that simply packages up (marshals) the method
arguments and transmits them to the server. For the server
skeleton class, the RMI compiler generates another set of
implementations of the remote methods, but these are
designed to receive the method arguments from the remote
method call, unpackage them, and make the corresponding
method call on die object implementation. Whatever the
method call generates (return data or an exception), the
results are packaged and transmitted back to the remote client.
The client stub method (which is still executing at this point)
unpackages the results and delivers them to the client as the
result of its remote method call.
5/24/2022
45. Key RMI Classes for Remote Object
Implementations:
◦ There are four key classes related to writing server
object implementations:
RemoteObject
◦ RemoteObject implements both the Remote and
Serializable interfaces.
◦ Although the RemoteObject class is in the ja v a .rmi
.server package, it is used by both the client and erver
portions of a remote object reference. Both client
stubs and server implementations are subclassed
(directly or indirectly) from RemoteObject. A
RemoteObject contains the remote reference for a
particular remote object.
5/24/2022
46. ◦ RemoteObject is an abstract class that reimplements the equal
s ( ), hashCodei), and to S t r in g i) methods inherited from
Object in a way that makes sense and is practical for remote
objects. The equal s() method, for example, is implemented to
return true if the internal remote references of the two
RemoteObject objects are equal, (i.e., if they both point to the
same server object).
RemoteServer
◦ RemoteServer is an abstract class that extends RemoteObject.
It defines a set of static methods that are useful for
implementing server objects in RMI, and it acts as a base class
for classes that define various semantics for remote objects. In
principle, a remote object can behave according to a simple
pointto- point reference scheme; it can have replicated copies
of itself scattered across the network that need to be kept
synclironized, or any number of other scenarios. JDK 1.1
supported only point-to-point, onpersistent remote references
with the UnicastRemoteObject class. The, Java 2 SDK 1.2
introduced the RMI activation system, so current versions of
the core Java API include another subclass of RemoteServer:
Activatable.
5/24/2022
47. UnicastRemoteObject
◦ This is a concrete subclass of RemoteServer that
implements point-to-point remote references over
TCP/IP networks. These references are nonpersistent:
remote references to a server object are only valid
during the lifetime of the server object. Before the
server object is created (inside a virtual machine
running on the host) or after the object has been
destroyed, a client can’t obtain remote references to
the object. In addition, if the virtual machine containing
the object exits (intentionally or otherwise), any
existing remote references on clients become invalid
and generate RemoteException objects if used.
5/24/2022
48. Activatable
◦ This concrete subclass of RemoteServer is part of the
RMI object activation facility and can be found in the
java.rmi .activation package. It implements a server
object that supports persistent remote references. If a
remote method request is received on the server host
for an Activatable object and the target object is not
executing at the time, the object can be started
automatically by the RMI activation daemon.
Creating the Stubs and Skeletons
◦ After you define the remote Java interface and implementation
class, compile them into Java bytecodes using a standard Java
compiler. Then you use the RMI stub/ skeleton compiler, rmic,
to generate the stub and skeleton interfaces that are used at
either end of the RMI communication link,
5/24/2022
49. ◦ In its simplest form, you can run rmic with the fully qualified classname
of your implementation class as the only argument. For example, once
we’ve compiled the Account and Account Impl classes, we can generate the
stubs and skeletons for the remote Account object with the following
command (Unix version):
% rmic Accountlmpl
◦ If the RMI compiler is successful, this command generates the stub and
skeleton classes, AccountImpl_Stub and AccountImpl_SkeT, in the current
directory. The rmic compiler has additional arguments that let you
specify where the generated classes should be stored, whether to print
warnings,- etc
. For example, if you want the stub and skeleton classes to reside in the directory
/usr/locaVclasses, you can run the command using the -d option:
% rmic -d / u s r / lo c a l / c l asses Account lmpl
This command generates the stub and skeleton classes in the specified directory
5/24/2022
50. Remote Object Activation
Automatic activation of remote objects was added to RMI as of Java 1.2. The
activation subsystem in RMI provides you with two basic features: the ability to
have remote objects instantiated (activated) on-demand by client requests, and
the ability for remote object references to remain valid across server crashes,
making the references persistent. These features can be quite useful in certain
types of distributed applications.
If a remote object is made activatable, it can be registered with the RMI
registry without actually being instantiated. Normally, RMI remote objects
(based on the UnicastRemoteObject interface) provide only nonpersistent
references to themselves. Such a reference can be created for a client only if
the referenced object already exists in a remote Java VM. In addition, the
remote reference is valid only during the lifetime of the remote object. The
remote object activation service adds support for persistent remote
references that can be created even if the remote object is not running at the
time of the request. This can persist beyond the lifetime of an individual server
object.
5/24/2022
51. The key features provided by the RMI activation service include:
• The ability to automatically create remote objects, triggered by requests for
references to these objects.
• Support for activation groups, in which groups of activatable remote objects are
executed in the same Java VM, which is automatically started by the activation service
if needed.
• The ability to restart remote objects if they exit or are destroyed due to a system
failure of some kind. This can add a certain degree of fault tolerance to RMI
applications.
In the RMI activation system, activatable objects belong to activation groups, and each
activation group runs within its own Java VM. If you don’t group your activatable objects,
instead simply assigning a new activation group to each activatable object you create,
each object then runs inside a separate JavaVM.
You typically define an activatable remote object by:
• Subclassing your remote object implementation from the Activatable class provided in
the Java. rmi .activation package
• Providing activation constructors in the server implementation
• Registering the object and its activation method with the activation service
5/24/2022
52. JavaSpaces
JavaSpaces is a new distributed object system being proposed by Sun as
a package at a higher level than the existing RMI and object serialization
facilities built into Java. JavaSpaces provides a distributed, persistent
object system that is roughly modeled after earlier shared memory
systems, such as LINDA. While it has some analogies with parallel
shared memory systems such as the Posix shm_xxx library and shared
memory facilities in parallel languages like Python, it also has some
important differences.
This appendix provides an overview of the general JavaSpace
architecture as currently described in the draft JavaSpace specification.
It doesn't go into detail about how to use the JavaSpace API, since the
API isn't fully available yet. This appendix only includes the core
elements of the specification, without discussing any proposed features
that may or may not be in the final API. C.1.
Overview of JavaSpaces The distributed application paradigm supported
by JavaSpaces is one in which remote agents interact with each other
indirectly through shared data object spaces. Objects are stored in a
JavaSpace in the form of entries. Clients write entries into the space,
read entries from the space, or take entries from the space, as shown in
Figure below.
5/24/2022
53. basic operations: read Read an entry from the space that matches a template. write Add
an entry to the space. take Read and remove an entry from the space. notify Send a
notification through a given event handler if entries that match a template are added to
the space.
A notification request has a time-out period associated with it: if a matching entry isn't
added within the time-out period, the notify request fails and is dropped from the
JavaSpace. Multiple basic operations can be assembled into transactions that group basic
operations into a single, atomic aggregate operation. There can be many clients and many
JavaSpaces in a given distributed application.
One client, and even one transaction from one client, can access multiple JavaSpaces. So
instead of one agent sending a message to another, or invoking a remote method directly
on another object within an agent, agents interact by writing and reading objects in
JavaSpaces.
An important feature of the JavaSpaces specification is that all operations on a given
JavaSpace are considered unordered. If you have multiple threads or multiple remote
agents issuing operations on a JavaSpace, and for some reason you want to impose some
order on the operations, then it's up to you to synchronize your threads or agents as
needed.
5/24/2022
54. Each JavaSpace holds data in the form of entries, which can either be read,
written, or taken from a JavaSpace. Each entry has one or more fields that are
used to match incoming requests from clients. Each request to read, take, or be
notified about an entry includes a template for the entry to match. In order for
an entry in the JavaSpace to match, the entry must be of the same type as the
template object.
Each field in the template can either have a non-null value, which must match
the fields in a matching entry in the JavaSpace, or a null value, which matches
any value in that field.
All operations on JavaSpaces are "transactionally secure," which means that
each operation or transaction is either entirely committed or entirely
noncommitted to a JavaSpace. So if a write to a JavaSpace succeeds, then you
can be assured that the Entry was written and will appear in the next client
read or take operation on the space.
An operation on JavaSpaces can be either in the form of a simple operation, or
a group of operations within a single Transaction. The authors of the JavaSpace
specification make a point of distinguishing JavaSpaces from a distributed
database system.
A JavaSpace knows the type of its entries, and can compare field values, but it
doesn't understand anything about the structure of the data in its entries. It
also isn't meant to provide opaque read/write access to persistent data. An
entry in a JavaSpace is a serialized copy of the object written to the space, and
entries returned to clients as a result of read or take operations are separate
copies of the objects in the space.
5/24/2022
55. Serialization and Deserialization in Java
Serialization in Java is a mechanism of writing the
state of an object into a byte-stream. It is mainly used
in Hibernate, RMI, JPA, EJB and JMS technologies.
The reverse operation of serialization is called
deserialization where byte-stream is converted into
an object. The serialization and deserialization
process is platform-independent, it means you can
serialize an object on one platform and deserialize it
on a different platform.
For serializing the object, we call the writeObject()
method of ObjectOutputStream class, and for
deserialization we call the readObject() method of
ObjectInputStream class.
We must have to implement the Serializable interface
for serializing the object.
5/24/2022
56. Advantages of Java Serialization
◦ It is mainly used to travel object's state on the network (that is
known as marshalling)
java.io.Serializable interface
Serializable is a marker interface (has no data member and
method). It is used to "mark" Java classes so that the
objects of these classes may get a certain capability. The
Cloneable and Remote are also marker interfaces.
5/24/2022
57. The Serializable interface must be implemented by
the class whose object needs to be persisted.
The String class and all the wrapper classes
implement the java.io.Serializable interface by default.
Let's see the example given below:
Student.java
import java.io.Serializable;
public class Student implements Serializable{
int id;
String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
}
5/24/2022
58. In the above example, Student class implements
Serializable interface. Now its objects can be
converted into stream. The main class
implementation of is showed in the next code.
ObjectOutputStream class
The ObjectOutputStream class is used to write
primitive data types, and Java objects to an
OutputStream. Only objects that support the
java.io.Serializable interface can be written to
streams.
Constructor
1) public ObjectOutputStream(OutputStream out) throws
IOException {} --It creates an ObjectOutputStream that
writes to the specified OutputStream.
5/24/2022
59. Important Methods
5/24/2022
Method Description
1) public final void
writeObject(Object obj)
throws IOException {}
It writes the specified object
to the.
ObjectOutputStream.
2) public void flush() throws
IOException {}
It flushes the current output
stream.
3) public void close() throws
IOException {}
It closes the current output
stream.
ObjectInputStream class