Chapter2_PartI

advertisement
Chapter 2
Distributed Objects
And Remote Invocation
(Part I)
1.
2.
3.
4.
5.
6.
7.
8.
Definitions and Terminology
Communication between distributed objects
Remote procedure call
Java RMI
CORBA RMI
Invocations in JEE architecture
Invocation of web services
.NET remoting
1
Chapter 2
Distributed Objects
And Remote Invocation
1. Definitions and Terminology
1.
2.
3.
4.
Distributed objects
Local and remote invocation
Remote object references
Interface definition language (IDL)
2. Communication between distributed objects
3. Remote procedure call
4. Java RMI
2
Middleware remote invocation service
1.
Definitions and terminology
1. Distributed objects
Applications and services
Middleware
Remote Invocation
MW services
(RMI/RPC)
Messages between
Distributed Objects
Request-Reply protocol
Marshalling, data representation
Transmission Protocols
Operating system
Computer/network hardware
3
1.
Object model
Definitions and terminology
1. Distributed objects
OO systems : objects logical unit
Distributed OO systems
• objects physically distributed
• remote object state only accessible through methods
Architectural models
• simple client server
client
server
• replicated server objects
client
server
server
service
4
Distributed objects : issues
1.
Definitions and terminology
1. Distributed objects
- how to distinguish between local/remote invocations
-> same invocation semantics ?
-> same access rights ?
- how to refer to distributed objects ?
-> Remote object references
- how to send arguments, receive results ?
-> Marshalling/unmarshalling
5
1.
Local and remote invocations
A
B
C
Definitions and terminology
2. Local vs. remote
D
E
remote invocation
local invocation
Local invocation
Remote invocation
Use Object Reference
Any public method
Use Remote Object Reference
Limited access, remote interface
6
1.
Remote interface
remote
invocation
A
limited access
only REMOTE interface
data
Method 1
Method 2
Method 3
Definitions and terminology
2. Local vs. remote
local
invocation
local
object
• NO constructor (use factory method instead)
• CORBA : specified using specific Interface Definition Language (IDL)
• JAVA : standard Java interface (extending Remote)
7
1.
Remote object references
Definitions and terminology
3. Remote object references
• purpose : unique ID for objects in distributed system
• uniqueness over time
• uniqueness over space
• usage : invoke methods on remote object (instead of local reference)
Remote
object
e.g. Java RMI
Host : Internet Address
Process : Port number + process creation time
Object : object number
Object type : remote interface
IP-address
Port number
Creation time
Object number
Interface
32
32
32
32
?
8
Remote interface : Java RMI example
1.
Definitions and terminology
3. Remote object references
import java.rmi.*;
public interface UpperServerInterface extends Remote {
String toUpper(String s) throws RemoteException;
String getServerName() throws RemoteException;
}
UppserServerInterface.java
9
Interface definition language
1.
Definitions and terminology
4. IDL
Some facts ...
• purpose : specify remote interfaces in a language neutral way
• standardized in 1990
• uses C++-like syntax (C++ has no interface construct ...)
• heavily used in CORBA (Common Object Request Broker Architecture)
Syntax
keyword
interface
attribute
in
out
inout
raises
Object
any
readonly
module
usage
-> specifies interface name
-> automatically make getters/setters
-> input parameter (read)
-> output parameter (out)
-> input & output
-> throwing exceptions
-> supertype of all IDL types
-> anything can be passes (void*)
-> no setter, only getter for this attribute
-> groups interfaces and types in own name space
(use with :: operator)
10
1.
IDL type system
built-in types
short
long
float
char
boolean
any
Definitions and terminology
4. IDL
unsigned short
unsigned long
double
octet
• use typedef-construct to extend IDL-types
• inheritance supported on interface level
• C++ syntax
• support for multiple inheritance
11
IDL example
1.
Definitions and terminology
4. IDL
#ifndef __ECHO_IDL__
#define __ECHO_IDL__
interface echo {
string echoString(in string mesg);
long
times_called();
};
echo.idl
12
More advanced IDL example
1.
Definitions and terminology
4. IDL
Whiteboard.idl
struct Rectangle{
long width;
long height;
long x;
long y;
} ;
struct GraphicalObject {
string type;
Rectangle enclosing;
boolean isFilled;
};
interface Shape {
long getVersion() ;
GraphicalObject getAllState() ; // returns state of the GraphicalObject
};
typedef sequence <Shape, 100> All;
interface ShapeList {
exception FullException{ };
Shape newShape(in GraphicalObject g) raises (FullException);
All allShapes(); // returns sequence of remote object references
long getVersion() ;
};
13
IDL module
1.
Definitions and terminology
4. IDL
• Modules allow interfaces and associated definitions to be grouped.
• A module defines a naming scope.
module Whiteboard {
struct Rectangle{
...} ;
struct GraphicalObject {
...};
interface Shape {
...};
typedef sequence <Shape, 100> All;
interface ShapeList {
...};
};
14
Chapter 2
Distributed Objects
And Remote Invocation
1. Definitions and Terminology
2. Communication between distributed objects
1. Invocation semantics
2. RMI-architecture
3. Request-Reply protocol
4. Marshalling
3. Remote procedure call
4. Java RMI
15
Middleware remote invocation service
Applications and services
distributed
object
Middleware
Remote Invocation
MW services
(RMI/RPC)
Request-Reply protocol
Marshalling, data representation
2.
Communicating objects
1. Invocation semantics
1. what does remote
invocation mean ?
logical
interaction
2. RMI architecture and
services ?
3. how to handle faults ?
4. how to convert objects
to bitstreams ?
Transmission Protocols
Operating system
Computer/network hardware
“real” info
flow
16
Invocation: semantics
2.
Communicating objects
1. Invocation semantics
Local invocation : Exactly 1
Remote invocation : ??? Due to channel/process omission failures
In practice:
• Java RMI : at-most-once
• CORBA : at-most-once (optionally maybe for void methods)
• Sun RPC : at-least-once
17
Invocation: syntax
2.
Communicating objects
1. Invocation semantics
The transparency argument
Make invocation syntax similar to local invocation, hiding:
•
•
•
•
locate/contact remote object
marshalling
fault tolerance measures
communication details (sockets)
But ...
Not everything should be hidden ...
programmer should know object is remote (network latency !) !
Typical approach
• same invocation syntax (but catch exceptions ...)
• object interface reflects remoteness
18
2.
RMI architecture
Communicating objects
2. Architecture
Goal: realize transparency, offer interesting services
application logic
(distributed objects)
Application objects
• marshalling
• automatic proxying
• request dispatching to server object
RMI software
proxy
dispatcher
Remote reference module
skeleton
Communication module
• manages remote object references
• translates between local and
remote references
• runs reply-request protocol
• implements desired invocation
semantics
19
2.
RMI architecture
a
proxy_b
Remote Ref. Mod.
communication
client
• remote object reference table
• table of local proxies
• proxy
• 1 proxy for each remote object
• local representative of remote object
• implements all methods of remote interface
• handles (un)marshalling
dispatcher
Communicating objects
2. Architecture
skeleton
b
Remote Ref. Mod.
communication
server
• dispatcher
• typically 1 for each class
• identify message to invoke in skeleton
• skeleton
• typically 1 for each class
• (un)marshalling
• invokes method on remote object
• sends reply
20
2.
RMI services
Communicating objects
2. Architecture
Binding service
disadvantages of remote object references
• no logical meaning
• direct reference to physical location
• server might crash -> automatic failover to other server ?
• object might migrate ?
• load balancing through replication not possible
binding service =
registry of remote objects reference
<-> textual name mappings
Server registers remote objects [1]
Client performs lookup [2]
Binding
service
1
2
client
a
3
b
server
21
RMI services
2.
Communicating objects
2. Architecture
Activation service
Activation
= on demand execution of services to reduces server processes/threads
activate objects when requests arrive
passivate objects if in consistent state
Activator
• keeps table of passive (activatable) objects
• start server processes on demand
• create active server objects from passive state
(e.g. serialized state)
• keeps table of activated objects and their location
In practice ...
CORBA : activator service
Java RMI : 1 activator on each server computer
22
RMI services
2.
Communicating objects
2. Architecture
Persistent object storage
• allows objects to live beyond process life time
• make persistent if in consistent state
• e.g. CORBA persistent object service,
Java Hibernate, Persistent Java
Object location service
-> identify likely locations where object might live
Transaction service
-> handle distributed transactions
e.g. CORBA transaction service
Event service
-> distributed event subscription/notification
e.g. CORBA event service
23
2.
Request-Reply protocol
Communicating objects
3. Request-reply protocol
Runs in the communication module
Purpose
• send message to server object
• send back return value or exception info to requestor
• enforce appropriate invocation semantics
Application objects
Object-to-object communication
RMI software
proxy
skeleton
Byte-oriented communication
Request – reply protocol
Byte-oriented communication
Socket layer
24
2.
Possible implementation
Communicating objects
3. Request-reply protocol
RMI software
proxy
public byte[] doOperation(
RemoteObjectRef o,
int methodID, byte[] arguments)
skeleton
public byte[] getRequest()
public void sendReply( byte[] reply,
InetAddress clientHost,
int clientPort)
Request – reply protocol
• doOperation : blocking (synchronous call)
• getRequest : blocks until request received
25
Possible implementation
2.
Communicating objects
3. Request-reply protocol
e.g. at-most-once invocation semantics
Message structure
[1]
[2]
[3]
[4]
[5]
messageType
requestID
objectReference
methodID
arguments
[int]
[int]
[RemoteObjectRef]
[int or Method]
[byte[ ] ]
[1] request = 0, reply = 1
[2] allows doOperation to identify matching request – reply pairs
[3] marshalled remote object reference
[4] method to invoke (e.g. numbering convention between
communication modules)
[5] marshalled method arguments
26
Possible implementation
2.
Communicating objects
3. Request-reply protocol
requestID ?
-> unique ID for messages
often used trick (to avoid interprocess synchronization)
ID=IDSenderProcess (e.g. port+ IPaddress)
+ unique_messageID for this process
27
2.
Handling failures
Communicating objects
3. Request-reply protocol
Failure model
1. server process omission (crash)
2. channel omission (request and/or reply lost)
Failure detection : timeout
Failure handling strategies
1. Throw exception
2. Retry request message until
- Reply from server
- Server assumed crashed
3. Duplicate request filtering
4. Result retransmissions
- Re-execute method call
- Retransmit reply (history based)
Retransmit
request
NO
YES
YES
Duplicate
filtering
NA
NO
YES
Re-execute
call
NA
YES
--
Retransmit
reply
NA
-YES
Invocation
Semantics
Maybe
At-least-once
At-most-once
28
Duplicate filtering algorithm
2.
Communicating objects
3. Request-reply protocol
if duplicate request arrives (check client + requestID)
• discard if request handling still in process
• if request already executed
• re-execute (idempotent operations)
• retransmit reply (keep history)
scaling of history table ?
- timeout (FIFO)
- interpret new request from same client as acknowledgement
29
2.
Marshalling
Communicating objects
4. Marshalling
= transform object in memory to bistream
Object-to-object communicaion
RMI software
proxy
skeleton
Byte-oriented communication
Options
• marshalling using external standard
= External Data Representation
e.g. CORBA’s common data representation (CDR)
Java serialization
• marshalling using sender standard AND
send this standard along
30
Java standard serialization
2.
Communicating objects
4. Marshalling
• class implements Serializable interface
• writing
create ObjectOutputStream (out)
call out.writeObject(<object>)
• reading
create ObjectInputStream (in)
call in.readObject()
cast to specific class (result is of type Object)
BUT : class file must be reachable by virtual machine !
31
Standard serialization
2.
Communicating objects
4. Marshalling
class A implements Serializable {
private int a=0;
private double b=12.0;
private String s="Some data";
public A() {System.out.println(" A() called.");}
public A(int ia,double ib,String is) {
a=ia;b=ib;s=is;
}
public void setA(int ia) {a=ia;}
public void setB(double ib) {b=ib;}
public void setS(String is) {s=is;}
public String toString() {
return "-> a="+a+" b="+b+" s="+s;
}
}
32
Standard serialization
2.
Communicating objects
4. Marshalling
class WriteObject {
public static void main(String[] args) {
End of file reached.
ArrayList o;
try {
writeObjects("obj.dat");
-> a=1 b=10.0 s=First.
} catch(IOException e) {System.err.println("Output Error : "+e);
-> a=2 b=20.0 s=Second.
}
try {
o=readObjects("obj.dat");
for(int i=0;i<o.size();i++) System.out.println(o.get(i));
// no casting needed for toString
} catch(IOException e) { System.err.println("Input Error : "+e);
} catch(ClassNotFoundException e) { System.err.println("Class Error : "+e);
}
}
public static void writeObjects(String n) throws IOException {
ObjectOutputStream out=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(n)));
A o1=new A(1,10.0,"First.");A o2=new A(2,20.0,"Second.");
out.writeObject(o1);out.writeObject(o2);out.close();
}
public static ArrayList readObjects(String n) throws IOException,ClassNotFoundException {
ObjectInputStream in=new ObjectInputStream(new BufferedInputStream(new FileInputStream(n)));
ArrayList l=new ArrayList();
try {
while(true) l.add(in.readObject());
} catch(EOFException e) {System.err.println("End of file reached.");}
in.close();
return l;
}
}
NO CONSTRUCTOR CALLS
TO RESTORE OBJECT !
33
Standard serialization : Statics
2.
Communicating objects
4. Marshalling
class A implements Serializable {
// .. Only changes shown …
private static char c;
public static void setC(char ic) {c=ic;}
public String toString() {
return "-> a="+a+" b="+b+" s="+s+" c = "+c;
}
public static void serializeStaticState(ObjectOutputStream o) throws IOException {
System.out.println("serializeStaticState().");
o.writeChar(c);
}
public static void deserializeStaticState(ObjectInputStream i) throws IOException {
System.out.println("deserializeStaticState().");
c=i.readChar();
}
}
Statics not serialized !
IF needed :
• add custom static methods to serialize/deserialize static state
• provide explicit calls for serializing/deserializing static state
34
Standard serialization : Statics
2.
Communicating objects
4. Marshalling
class WriteObject { // … only changes shown …
public static void writeObjects(String n) throws IOException {
ObjectOutputStream out=new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(n)));
A o1=new A(1,10.0,"First.");A o2=new A(2,20.0,"Second.");
A.setC('a');
out.writeObject(o1);
out.writeObject(o2);
A.serializeStaticState(out);
A.setC('b');
out.close();
}
public static ArrayList readObjects(String n) throws IOException,ClassNotFoundException {
ObjectInputStream in=new ObjectInputStream(new BufferedInputStream(new FileInputStream(n)));
ArrayList l=new ArrayList();
l.add(in.readObject());
l.add(in.readObject());
A.deserializeStaticState(in);
in.close();
return l;
}
serializeStaticState().
}
deserializaStaticState().
-> a=1 b=10.0 s=First. c = a
-> a=2 b=20.0 s=Second. c = a
35
Aggregating serializables
2.
Communicating objects
4. Marshalling
class A implements Serializable {
private int a=0;
private double b=12.0;
private String s="Some data";
private B myB;
public A() {System.out.println(" A() called.");}
public A(int ia,double ib,String is,B aB) {
a=ia;b=ib;s=is;myB=aB;
}
public void setA(int ia) {a=ia;}
public void setB(double ib) {b=ib;}
public void setS(String is) {s=is;}
public String toString() {
return "-> a="+a+" b="+b+" s="+s+myB;
}
}
class B implements Serializable { // MUST BE SERIALIZABLE !
private int c=0;
public B() {System.out.println(" B() called.");}
public B(int i) {c=i;};
public void setC(int ic) {c=ic;};
public String toString() {
return "\t c="+c;
}
}
36
Aggregating serializables
2.
Communicating objects
4. Marshalling
// … rest the same …
public static void writeObjects(String n) throws IOException {
ObjectOutputStream out=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(n)));
A o1=new A(1,10.0,"First.",new B(100));
A o2=new A(2,20.0,"Second.",new B(200));
out.writeObject(o1);
out.writeObject(o2);
out.close();
}
// …
End of file reached.
-> a=1 b=10.0 s=First.
-> a=2 b=20.0 s=Second.
c=100
c=200
Serialization mechanism follows the “web of objects”
1 object value = memory
-> 1 object value in stream !
37
Transient fields
2.
Communicating objects
4. Marshalling
Do not serialize some fields :
• some objects can not be serialized (e.g. Thread objects)
• not logical to store permanently (e.g. password field)
Mark fields as “transient”
class A implements Serializable {
private int a=0;
private transient double b=12.0;
private String s="Some data";
private transient B myB;
// B not necessarily Serializable !
public A() {System.out.println(" A() called.");}
public A(int ia,double ib,String is,B aB) {
a=ia;b=ib;s=is;myB=aB;
}
public void setA(int ia) {a=ia;}
public void setB(double ib) {b=ib;}
public void setS(String is) {s=is;}
public String toString() {
return "-> a="+a+" b="+b+" s="+s+myB;
}
}
End of file reached.
-> a=1 b=0.0 s=First.null
-> a=2 b=0.0 s=Second.null
38
Customized serialization
2.
Communicating objects
4. Marshalling
custom serialization : 2 options
1. Implement Externalizable interface
implement
public void writeExternal(ObjectOutput o) throws IOException
public void readExternal(ObjectInput i) throws IOException
2. Implement Serializable
ADD (NOT override !) following methods :
private void writeObject(ObjectOutputStream o) throws IOException
private void readObject(ObjectInputStream i) throws IOException
39
2.
Aggregation
class A
implements Serializable {
// clone method added to A
public Object clone() {return new
Communicating objects
4. Marshalling
• Serialization (to same stream !) avoids unnecessary
(and dangerous) duplicates
• OBJECT ONLY WRITTEN ONCE !
• HANDLES (“stream references”) WRITTEN instead
A(a);}
of full objects !
}
class Serial {
// main and readObjects unchanged
public static void writeObjects(String n) throws IOException {
ObjectOutputStream out=new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(n)));
A o1=new A(1);
System.out.println(o1);
out.writeObject(o1);
// out.close();
// out=new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(n)));
o1.setA(10);
System.out.println(o1);
with //
without //
out.writeObject(o1);
A o2=(A)o1.clone();
A@192d342-> a=1
A@192d342-> a=1
System.out.println(o2);
A@192d342-> a=10
A@192d342-> a=10
out.writeObject(o2);
A@87816d-> a=10
A@87816d-> a=10
out.close();
End of file reached. End of file reached.
}
A@a83b8a-> a=1
A@a83b8a-> a=10
}
A@a83b8a-> a=1
A@dd20f6-> a=10
A@dd20f6-> a=10
40
Chapter 2
Distributed Objects
And Remote Invocation
1. Definitions and Terminology
2. Communication between distributed objects
3. Remote procedure call
1. RPC architecture
2. SUN RPC details
3. Example : date service
4. Java RMI
41
RPC History
3. Remote procedure call
1. Architecture
= non OO version of RMI
“RMI for C programs”
•
•
•
•
•
“invented” in 1976 (!), IETF RFC 707
popular implementation “SUN RPC”
(official name : ONC RPC (Open Network Computing)
competing implementations not always compatible !
programming language : mostly C
used to implement Network File System (NFS)
42
3. Remote procedure call
1. Architecture
Architecture
proc
a
client
stub
communication
client
•
•
•
•
•
dispatcher
server
stub
proc
b
communication
server
no remote reference module (only 1 global “object”)
dispatcher selects function stub at server side
client procedure stub = RMI proxy
server procedure stub = RMI skeleton
stubs can be generated from service interface definition
43
Details
3. Remote procedure call
2. SUN RPC details
• marshalling : external data representation (XDR, RFC 1832)
• interface compiler : rpcgen
• binding service : portmapper
Steps for developing RPC-program
1. Interface definition (XDR)
procedures have only 1 argument
-> use C-structs
additional keywords:
program
logical grouping of procedures
version
version control
2. Compile XDR-file with rpcgen
-> client stub procedure
-> server main procedure, dispatcher, server proc stubs
-> XDR marshalling and unmarshalling procedures
3. Implement application logic (client and server proc’s)
4. perform RPC in client code
clnt_create(hostname,program,version) returns handle
clnt_destry(handle)
matching closing procedure
5. compile + run
44
Date example
(credits: Unix Networking, Stevens)
3. Remote procedure call
3. Example
date.x
/*
* date.x Specification of the remote date and time server
*/
/*
* Define two procedures
* bin_date_1() returns the binary date and time (no arguments)
* str_date_1() takes a binary time and returns a string
*
*/
program DATE_PROG {
version DATE_VERS {
long BIN_DATE(void) = 1; /* procedure number = 1 */
string STR_DATE(long) = 2; /* procedure number = 2 */
} = 1; /* version number = 1 */
} = 0x31234567; /* program number = 0x31234567 */
•Start numbering procedures at 1 (procedure 0 is always the ``null procedure''.)
•Program number is defined by the user. Use range 0x20000000 to 0x3fffffff.
•Provide a prototype for each function.
45
Date example : server side
3. Remote procedure call
3. Example
dateproc.c
/*dateproc.c
remote procedures; called by server stub */
#include <rpc/rpc.h>
/* standard RPC include file */
#include "date.h"
/* this file is generated by rpcgen */
/*Return the binary date and time*/
long *bin_date_1()
{
static long timeval;
/* must be static */
timeval = time((long *) 0);
return(&timeval);
}
/*Convert a binary time and return a human readable string*/
char **str_date_1(long *bintime)
{
static char *ptr;
/* must be static */
ptr = ctime(bintime);
/* convert to local time */
return(&ptr);
}
• No main() routine in server code.
• Extra level of indirection. bin_date() does not return a long, but *long.
• return variable needs to be declared static
46
Date example : server side
3. Remote procedure call
3. Example
rdate.c
/* rdate.c client program for remote date program */
#include <stdio.h>
#include <rpc/rpc.h>
/* standard RPC include file */
#include "date.h" /* this file is generated by rpcgen */
main(int argc, char *argv[]) {
CLIENT *cl; /* RPC handle */
char *server;
long *lresult; /* return value from bin_date_1() */
char **sresult; /* return value from str_date_1() */
if (argc != 2) {
fprintf(stderr, "usage: %s hostname\n", argv[0]); exit(1);
}
server = argv[1];
/* Create client handle */
if ((cl = clnt_create(server, DATE_PROG, DATE_VERS, "udp")) == NULL) {
/*can't establish connection with server */
clnt_pcreateerror(server);
exit(2);
}
/*... */
}
47
Date example : server side
3. Remote procedure call
3. Example
rdate.c
/* ... */
/* First call the remote procedure "bin_date". */
if ( (lresult = bin_date_1(NULL, cl)) == NULL) {
clnt_perror(cl, server); exit(3);
}
printf("time on host %s = %ld\n",server, *lresult);
/* Now call the remote procedure str_date */
if ( (sresult = str_date_1(lresult, cl)) == NULL) {
clnt_perror(cl, server);
exit(4);
}
printf("time on host %s = %s", server, *sresult);
clnt_destroy(cl); /* done with the handle */
exit(0);
}
• client calls client stubs (_1) suffix
• close handle after use !
48
Chapter 2
Distributed Objects
And Remote Invocation
1.
2.
3.
4.
Definitions and Terminology
Communication between distributed objects
Remote procedure call
Java RMI
1. Philosophy and design choices
2. Example
49
Java RMI : philosophy
4. Java RMI
1. Philosophy
• Java-only technology
alternatives : CORBA, SOAP
• Remote invocation semantics identical to local ones BUT :
• client knows invocation is remote
(MUST catch RemoteException)
• server object MUST implement Remote interface
• Terminology
• client-side RMI-component (proxy) : stub
• server-side RMI-component : skeleton
• no dispatcher per class (single generic dispatcher)
• binder : RMIregistry (1 instance on every server computer)
• stubs and skeletons automatically generated
by RMI-compiler rmic
50
4. Java RMI
1. Philosophy
Java RMI : Code download
Automatic code download !
1 : b:B ?
a
4
3
b:B
B_stub : Class
b_stub : B_stub
2
B_stub : Class
server
client
Easy to keep clients and servers synchronized (same version)
Security risk
Specialized security limitations for downloaded classes
Implemented in RMISecurityManager()
51
Java RMI : Parameter passing
4. Java RMI
1. Philosophy
• local invocation
pass by reference
• remote invocation
• remote objects : pass by reference
(remote object reference)
• non-remote objects : pass by value
• make object COPY (MUST be serializable)
• send copy to other side
• serialization
• Remote objects : serialize remote object reference
• Non-remote objects : add URL to locate class-file
52
Java RMI : Remote interface
4. Java RMI
1. Philosophy
• extends java.rmi.Remote
• all methods throw java.rmi.RemoteException
• has public visibility
import java.rmi.*;
public interface MyRemoteInterface extends Remote {
int getData() throws RemoteException;
MyRemoteInterface getNewObject() throws RemoteException;
String getMessage(int n) throws RemoteException;
}
53
Java RMI : Remote objects
4. Java RMI
1. Philosophy
extend
• java.rmi.server.UnicastRemoteObject
• or java.rmi.server.Activatable
implement desired remote interface
import java.rmi.*;
Import java.rmi.server.UnicastRemoteObject;
public class MyServer extends UnicastRemoteObject
implements MyRemoteInterface {
// …
public int getData() throws RemoteException {/* … */}
public MyRemoteInterface getNewObject() throws RemoteException {/* … */}
public String getMessage(int n) throws RemoteException {/* … */}
}
54
Java RMI : Registry
4. Java RMI
1. Philosophy
RMI registry must run on every server computer
maps String <-> remote object reference
String : //computerName:port/objectName
accessed through the class java.rmi.Naming
• server methods (registration of objects)
• public void bind(String name, Remote obj)
• public void unbind(String name, Remote obj)
• public void rebind(String name, Remote obj)
• client methods (lookup of server objects)
• public Remote lookup(String name)
• public String[ ] list()
(returns all names bound in registry)
55
Server Remote Interface
4. Java RMI
2. Example
put String to upper case remotely
import java.rmi.*;
public interface UpperServerInterface extends Remote {
String toUpper(String s) throws RemoteException;
String getServerName() throws RemoteException;
}
56
Example : Server Object
4. Java RMI
2. Example
import java.rmi.*;
import java.rmi.server.*;
public class UpperServer extends UnicastRemoteObject
implements UpperServerInterface {
private String name;
public UpperServer(String n) throws RemoteException {
name=n;
}
public String toUpper(String s) {
return "Server : "+name+" : "+s.toUpperCase();
}
public String getServerName() {
return name;
}
}
57
Example : Server program
4. Java RMI
2. Example
import java.rmi.*;
import java.rmi.server.*;
import java.net.*;
public class UpperServerProgram {
public static void main(String[] args) {
if(System.getSecurityManager()==null)
System.setSecurityManager(new RMISecurityManager());
for(int i=0;i<args.length;i++)
registerServer(args[i]);
}
public static void registerServer(String s) {
try {
UpperServer server=new UpperServer(s);
Naming.rebind(s,server);
System.out.println("Server <"+s+"> running ...");
} catch(Exception e) {
System.err.println("Failing starting server : "+s+e);
}
}
}
58
Example : Client program
4. Java RMI
2. Example
import java.rmi.*;
import java.rmi.server.*;
public class UpperClient {
public static void main(String[] args) {
System.setSecurityManager(new RMISecurityManager());
UpperServerInterface server=null;
try {
server = (UpperServerInterface)
Naming.lookup("rmi://localhost/"+args[1]);
System.out.println("Reply from server : "+
server.toUpper(args[0]));
} catch(RemoteException e) {System.err.println("Remote exception : "+e);
} catch(Exception ee) {System.err.println(ee);
}
}
}
59
Java RMI : a Client recipe
4. Java RMI
2. Example
1. Create and install RMISecurityManager
2. Lookup remote object
(specify host, port number, textual representation of server object)
3. Perform remote invocations, catching remote exceptions
60
Java RMI : a Server recipe
4. Java RMI
2. Example
Remote interface
1. Must be public
2. Must extend java.rmi.Remote
3. Each method must throw java.rmi.RemoteException
4. Remote objects type : use interface type
Remote Server object
1. Implement Remote interface
2. Extend java.rmi.server.UnicastRemoteObject
3. Constructor must throw RemoteException
Remote Server program
1. Create and install RMISecurityManager
2. Create server object
3. Register at least one server object
61
Activatable Server Objects :
Remote Interface and Server Objects
4. Java RMI
2. Example
import java.rmi.*;
import java.rmi.activation.*;
import java.io.*;
public class UpperServer extends Activatable implements UpperServerInterface {
private String name;
public UpperServer (ActivationID id, MarshalledObject data)
throws RemoteException {
super(id,0);
try {name=(String)(data.get());
} catch(IOException e) {
} catch(ClassNotFoundException ee) {}
}
public String toUpper(String s) {return "Server : "+name+" : "+s.toUpperCase();}
public String getServerName() {return name;}
}
62
Activatable Server Objects :
Server Program (setup)
4. Java RMI
2. Example
import java.rmi.*;
import java.rmi.activation.*;
import java.util.Properties;
public class UpperServerProgram {
public static void main(String[] args) throws Exception {
System.setSecurityManager(new RMISecurityManager());
Properties props = new Properties();
props.put("java.security.policy", "C:/security/java.policy");
ActivationGroupDesc.CommandEnvironment ace = null;
ActivationGroupDesc example = new ActivationGroupDesc(props, ace);
ActivationGroupID agi = ActivationGroup.getSystem().registerGroup(example);
String location = "file:/D:/onderwijs/activatable/";
// location of stub file
for(int i=0;i<args.length;i++) {
MarshalledObject data = new MarshalledObject(args[i]);
ActivationDesc desc = new ActivationDesc (agi,"UpperServer",location, data);
UpperServerInterface stub = (UpperServerInterface)Activatable.register(desc);
Naming.rebind(args[i],stub);
System.out.println("Server <"+args[i]+"> running ... ");
}
System.exit(0);
}
}
63
Download