Sie sind auf Seite 1von 103

Distributed Objects

In the Good Old Days...

Only local objects existed

My Machine

My Object

Todays World...
Network and Distributed Objects

My Machine Local Objects

Remote Machine Remote Objects

Overview
What options do I have for distributed application development? Developers who program using the Java programming language can choose several solutions for creating distributed applications programs. 1) Java RMI technology 2) Java IDL technology (for CORBA programmers) 3) Enterprise JavaBeans technology In this section we shall be talking about Java RMI and IDL (Corba) technologies
4

JAVA RMI
Remote Method Invocation

Outline
1) 2) 3) 4) 5) RMI Concepts RMI architecture Implementing and running RMI system Implementing activatable RMI server Summary

Introduction
Remote Method Invocation (RMI) technology was first introduced in JDK1.1. RMI allows programmers to develop distributed Java programs with the same syntax and semantics used for non-distributed programs. RMI is based on a similar, earlier technology for procedural programming called remote procedure call (RPC)
7

Introduction
Disadvantages of RPC a) RPC supports a limited set of data types. Therefore it is not suitable for passing and returning Java Objects b) RPC requires the programmer to learn a special interface definition language (IDL) to describe the functions that can be invoked remotely
8

Introduction
The RMI architecture defines a) How objects behave. b) How and when exceptions can occur. c) How memory is managed. d) How parameters are passed to, and returned from, remote methods. The remote object model for Enterprise JavaBeans (EJB) is RMI- based.
9

Introduction
RMI is designed for Java-to-Java distributed applications. RMI is simpler and easier to maintain than using socket. Other options for creating Java-to-non-Java distributed applications are: a) Java Interface Definition Language (IDL) b) Remote Method Invocation (RMI) over Internet Inter-ORB Protocol (IIOP) -- RMIIIOP.
10

RMI architecture
RMI allows the code that defines the behavior and the code that implements the behavior to remain separate and to run on separate JVMs. At client side, RMI uses interfaces to define behavior. At server side, RMI uses classes to define implementation.

11

RMI Layer
Java Virtual Machine Client Object Java Virtual Machine Remote Object

Stub

Skeleton

Remote Reference Layer

Remote Reference Layer

Transport Layer

TCP

Transport Layer
12

Remote Objects
Remote Objects
Live on server Accessed as if they were local

13

Remote Objects

14

Stubs and Skeletons


Stub
lives on client marshals argument data (serialization) unmarshals results data (deserialization)

Skeleton
lives on server unmarshals argument data marshals results data receives requests from stub delivers response to stub

16

Remote Reference Layer


This layer provides a RemoteRef object that represents the link to the remote service implementation object. Encodes and decodes the on-wire protocol. Implements the remote object protocols (Unicast Remote Object/ activatable remote objects ).

17

Transport Layer
The Transport Layer makes the connection between JVMs. All connections are streambased network connections that use TCP/IP. Dispatching messages between stub and skeleton.

18

RMI Flow
1. Server Creates Remote Object Client Virtual Machine 2. Server Registers Remote Object Client Server Virtual Machine Remote Object
1

Stub

Skeleton Server
2

Fred Registry Virtual Machine


19

RMI Flow
Client Virtual Machine Client Server Virtual Machine Remote 3. Client requests object from Registry Object 4. Registry returns remote reference (and stub gets created) Stub
3 4

Skeleton Server

Fred Registry Virtual Machine


20

RMI Flow
Client Virtual Machine Client
5 6 7

Server Virtual Machine Remote Object

Stub

Skeleton Server

5. Client invokes stub method 6. Stub talks to skeleton 7. Skeleton invokes remote object Fred method Registry Virtual Machine
21

The steps...
Create the Interface to the server Create the Server Create the Client Compile the Interface (javac) Compile the Server (javac) Compile the Client (javac) Generate Stubs and Skeletons (rmic)

22

Part II: RMI Usage

23

Creating Remote Objects


Define a Remote Interface
extends java.rmi.Remote

Define a class that implements the Remote Interface


extends java.rmi.RemoteObject or java.rmi.UnicastRemoteObject

24

Remote Interface Example


import java.rmi.*; public interface Adder extends Remote { public int add(int x, int y) throws RemoteException; }

25

Remote Interface Example


Remark: All the interface has to extend the java.rmi.Remote interface and all the methods has to declare that it may throw a RemoteException object.

26

Remote Class Example


The implementation class may extend from the java.rmi.server.UnicastRemoteObject to link into the RMI system. It must also provide an explicit default constructor throwing RemoteException. When this constructor calls super(), it activates code in UnicastRemoteObject that performs the RMI linking and remote object initialization.

27

Remote Class Example


import java.rmi.*; import java.rmi.server.*; public class AdderImpl extends UnicastRemoteObject implements Adder Extend UnicastRemoteObject and implemet Adder Interfact { public AdderImpl() throws RemoteException { super(); } public int add(int x, int y) Implement all methods from interface Hello.java throws RemoteException { return x + y; } }

28

Compiling Remote Classes


Compile the Java class
javac
reads .java file produces .class file

Compile the Stub and Skeleton


rmic
reads .class file produces _Skel.class and _Stub.class

29

Compiling Remote Classes (Diagram)


Adder.java (interface)

javac

Adder.class (interface classfile)

AdderImpl_Skel.class (skeleton classfile)

AdderImpl.java (remote class)

javac

AdderImpl.class (classfile)

rmic

AdderImpl_Stub.class (stub classfile)

rmic v1.1 classpath ..\RMI d .\RMI AdderImpl


30

Registering Remote Classes


start the registry
running process

Windows:
start rmiregistry
(uses port 1099 by default)

You can also bind rmiregistry to a different port by indicating the new port number as :

start rmiregistry <new port>


31

Create the server


Creates a new instance of the remote object Registers it in the registry with a unique name

32

import java.rmi.AlreadyBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.Naming; import java.net.MalformedURLException;

RMI Server Example

public class RMIServer { public static void main(String []args) throws RemoteException, MalformedURLException, AlreadyBoundException { try{ // LocateRegistry.createRegistry(1099); Registering Remote Classes AdderImpl adder = new AdderImpl(); System.out.println("Server has started"); Instantiate a new object and register Naming.bind (rmi://localhost/adder", adder); (bind it) in the rmiregistry System.out.println("Adder bound"); }catch (Exception e) { Start rmicregistry.exe System.out.println ("Trouble: " + e); } } 33 }

RMI URLs
rmi://host[:port]/name

default port is 1099 Specifies hostname of registry can also use relative URLs
name only assumes registry is on local host

34

Creating an RMI Client


1) In the clients code, all you need to do is to lookup the object and use, its methods as local methods. 2) The clients code may look like the following:

35

RMI Client Example


import java.rmi.Naming; import java.rmi.NotBoundException; import java.util.Scanner; import java.io.*; public class RMIClient {

public static void main(String[] args) throws NotBoundException, IOException {


Adder a = (Adder) Naming.lookup("rmi://localhost/adder");

int sum = a.add(2,2); System.out.println("2+2=" + sum); }


}

lookup the RMIServer and call Method adder() on Stub

36

RMI URLs
rmi://host[:port]/name

default port is 1099 Specifies hostname of registry can also use relative URLs
name only assumes registry is on local host
Remember that the stub and skeleton classes get generated by the rmic compiler
37

Steps for Developing an RMI System


1. Define the remote interface 2. Develop the remote object by implementing the remote interface. 3. Develop the client program. 4. Compile the Java source files. 5. Generate the client stubs and server skeletons. 6. Start the RMI registry. 7. Start the remote server objects. 8. Run the client

38

Lab Work: RMI System


1) Please follow what we have discussed to develop a RMI server which hosts a service for calculating the square root of a number. 2) Compile your RMI server and generate the corresponding stub class. 3) Create a client to test the RMI service.

39

Passing Parameters
All parameters passed from an RMI client to an RMI server must either be serializable or be a remote object. For serializable: a) Data is extracted from the local object and sent across the network to the remote server. b) Object is then reconstructed in the remote server. c) Any changes to the object in the RMIServer will not be reflected in the object held in the RMI client and vice versa. 40

Passing Parameters
For a remote object: a) Stub information, not a copy of data, is actually sent over RMI. b) Any call made to the parameter object become a remote calls back to the actual object. c) Changes made in one JVM are reflected in the original JVM.

41

Conditions for serializability


If an object is to be serialized: a) The class must be declared as public b) The class must implement java.io.Serializable interface are marked as serializable c) The class must have a default (no-argument) constructor d) All fields of the class must be serializable: either primitive types or serializable objects.

42

Remote interfaces and class

43

Security
Your program should guarantee that the classes that get loaded do not perform operations that they are not allowed to perform. A more conservative security manager than the default should be installed. The following code should be added to the main method of the server and client program:

44

RMI Server Example

import java.rmi.RMISecurityManager;
public class RMIServer { public static void main(String []args) throws RemoteException, MalformedURLException, AlreadyBoundException {

// Create and install a security manager if (System.getSecurityManager() == null) { System.setSecurityManager(new RMISecurityManager()); }


} }
45

RMISecurityManager
Easiest way to do this is to use java.rmi.RMISecurityManager as:
System.setSecurityManager(new RMISecurityManager());

This by default restricts all code from making socket connections. Obviously this is too strict. Need a policy file to allow client to make network connection to rmi port. It would look something like:
grant{ permission java.net.SocketPermission *:1024-65535, connect}

java Client Djava.security.policy=file_policy


46

Activatable Server
Before Java 2, the UnicastRemoteObject could be accessed only from a server program that created instances of the object and ran all the time. With Java 2 we got the Activatable and the rmid daemon. An activatable class needs only to be registered with the rmid. This is an advantage for systems that have many remote object classes but only a few of them are active at any one time. They save memory (and so gain performance).
47

Activatable Server
Enable server programs to wake up and start to run when they are needed. Java RMI Activation System Deamon (RMID) is introduced to handle this task. When a client requests a reference to the server from the rmiregistry, the rmid program, which holds the servers details, will be requested to start up the server and return the reference to the client. After that, the rmiregistry will be able to provide the reference of the server directly.
48

MyRemoteInterface.java
import java.rmi.*; public interface MyRemoteInterface extends Remote { public Object callMeRemotely() throws RemoteException; }
49

Creating the implementation class


Step 1: Make the appropriate imports in the implementation class import java.rmi.*; import java.rmi.activation.*; Step 2: Extend your class from java.rmi.activation.Activatable public class ActivatableImplementation extends Activatable implements MyRemoteInterface {

50

Creating the implementation class


Step 3: Declare a two-argument constructor in the implementation class public ActivatableImplementation(ActivationID id, MarshalledObject data) throws RemoteException { // Register the object with the activation system // then export it on an anonymous port super(id, 0); }
The super(id, 0) method calls Activatable constructor to pass an activation ID and a port number. In this case, the port number is default 1099.
51

Creating the implementation class


Step 4: Implement the remote interface method(s) public Object callMeRemotely() throws RemoteException { return "Success"; }

52

ActivatableImplementation.java

53

Activatable Server: Setup

Activatable Server: Setup

Activatable Server: Setup

Activatable Server: Setup

Compile and Run


1. Compile all the classes use javac. 2. Run rmic on the implementation class 3. Start rmi registry use rmiregistry.
Note that if you use jdk version below 1.5.0, you may need to regenerate stub class first by using command below before start the rmiregistry.

rmic -v1.2 <implement of Interface> rmic v1.2 ActivatableImplementation


58

Compile and Run

Compile and Run

Compile and Run

Compile and Run

Example

http://www.javacamp.org/morecl asses/rmi/rmi23.html

63

java.rmi.activation.Activatable 1.2
protected Activatable(ActivationID id, int port) Constructs the activatable object and establishes a listener on the given port. Use 0 for the port to have a port assigned automatically. static Remote exportObject(Remote obj, ActivationID id, int port) Makes a remote object activatable. Returns the activation receiver that should be made available to remote callers. Use 0 for the port to have a port assigned automatically. static Remote register(ActivationDescriptor desc) registers the descriptor for an activatable object and prepares it for receiving remote calls. Returns the activation receiver that should be made available to remote callers.
65

java.rmi.MarshalledObject 1.2
MarshalledObject(Object obj) constructs an object containing the serialized data of a given object. Object get() deserializes the stored object data and returns the object.

66

java.rmi.activation.ActivationGroupDesc 1.2
ActivationGroupDesc(Properties props, ActivationGroupDesc.CommandEnvironment env)

constructs an activation group descriptor that specifies virtual machine properties for a virtual machine that hosts activated objects. The env parameter contains the path to the virtual machine executable and command-line options, or it is null if no special settings are required.

67

java.rmi.activation.ActivationGroup 1.2
static ActivationSystem getSystem() returns a reference to the activation system.

68

java.rmi.activation.ActivationSystem 1.2
ActivationGroupID registerGroup ( ActivationGroupDesc group)

registers an activation group and returns the group ID.

69

java.rmi.activation.ActivationDesc 1.2
ActivationDesc(ActivationGroupID id, String className, String classFileURL, MarshalledObject data)

constructs an activation descriptor.

70

Converting UnicastRemoteObject to Activatable


If you already have a UnicastRemoteObject and want to make it Activatable you just have to make some small changes to the implementation class. 1. 2. 3. 4. Make the appropriate imports. Make the class extend Activatable. Remove the no-argument constructor. Declare a two argument constructor.

You then need to create a setup program just like before.

Using Remote Method Invocation to Implement Callbacks

Polling vs. Callback


In the absence of callback, a client will have to poll a passive server repeatedly if it needs to be notified that an event has occurred at the server end.
Polling
Server

Callback
Server

...
Client A client issues a request to the server repeatedly until the desired response is obtained. Client A client registers itself with the server, and wait until the server calls back.

a remote method call

73

RMI Callbacks
A callback client registers itself with an RMI server. The server makes a callback to each registered client upon the occurrence of a certain event. Server
Clients C1 The callback list C2 RMI calls callback C4

C3

C5

74

Callback Client-Server Interactions


Client host 1 2 Server host Client.class RMI registry

SomeInterface_stub.class 3,4
X

SomeInterface_skel.class SomeServer.class

CallbackInterface_skel.class 5

CallbackInterface_stub.class 1. Client looks up the interface object in the RMIregistry on the server host. 2. The RMIRegistry returns a remote reference to the interface object. 3. Via the server stub, the client process invokes a remote method to register itself for callback, passing a remote reference to itself to the server. The server saves the reference in its callback list. 4. Via the server stub, the client process interacts with the skeleton of the interface object to access the methods in the interface object. 5. When the anticipated event takes place, the server makes a callback to each registered client via the callback interface stub on the server side and the callback interface skeleton on the client side.

75

Callback application files


Object client host object client directory Client.class
ClientInterface.class ServerInterface.class

Object server host object server directory Server.class


ServerInterface.class ClientInterface.class

ClientImpl.class
ServerImpl_Stub.class ClientImpl_skel.class

ServerImpl.class
ClientImpl_Stub.class ServerImpl_skel.class
76

Implementation

Defining the Listener Interface


defines a remote object with methods method should be invoked by an event source whenever an event occurs, so as to act as notification that the event occurred.

Object-Oriented Callbacks

Callback notification of event, for every registered listener

Callback implemented by invoking a method on a listening object

RMI Callbacks
Listener interface and the event source must be implemented as an RMI service. For the listener
to register itself with the remote event source, it must invoke a remote method and pass an object reference to the remote listener interface it defines.

Defining the Listener Interface

Defining the Event Source Interface


event source must allow a listener to be registered and unregistered, and may optionally provide additional methods

Defining the Event Source Interface

Implementing Event Source Interface

implement TemperatureSensorServer class


RMI server.

server must
extend UnicastRemoteObject, to offer a implement Temperature Sensor interface

Implementing Event Source Interface

Implementing Event Source Interface

Implementing Event Source Interface

Implementing Event Source Interface

Implementing Event Source Interface

Implementing Event Source Interface

Implementing Event Source Interface

Implementing the Listener Interface

implement the TemperatureListener interface, register itself with the remote temperature sensor service, client will be notified of changes as they occur, using a remote callback

Implementing the Listener Interface

Implementing the Listener Interface

Implementing the Listener Interface

Implementing the Listener Interface

Running the Callback Example

RMI Components
java.rmi: client-side RMI classes, interfaces, and exceptions java.rmi.server: server-side RMI classes, interfaces, and exceptions java.rmi.registry: Classes for naming services java.rmi.dgc: distribute garbage collection

100

RMI Server Properties


java.rmi.activation: Implements activate on demand RMI services. Objects instantiated on-demand by client-requests. References persistent over server crashes. rmic: compiler to generate stubs and skeletons rmiregistry: Utility server that provides naming service for RMI. Associates names with objects rmid: utility server to RMI activation 101 framework

RMI Server Properties


java.rmi.server.codebase: a url indicating code base from which classes should be loaded to network clients java.rmi.server.disableHttp: if true, RMI will not use Http to try to tunnel through firewalls. Default is false, meaning that Http wraps RMI calls

102

RMI Server Properties


java.rmi.server.hostname: sets servers fully qualified host name, if name unavailable via DNS java.rmi.server.logCalls: if true, RMI will log information about calls. Default is false. java.rmi.dgc.leaseValue: The time in milliseconds until server notices client is no longer connected. Default is 10 minutes.
103

RMI Naming Methods


Remote lookup(String name): Look up remote object by URL and return it bind(String name, Remote obj): bind an object to a specific URL unbind(String name): unbind an object at a URL rebind(String name, Remote obj): Replace the object currently bound with a new one String[] list(String name): list of URLs from specified Registry

104

Das könnte Ihnen auch gefallen