Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 1. Definitions and Terminology 2. Communication between distributed objects 3. Remote procedure call 4. Java RMI 5. CORBA RMI 6. Invocations in JEE architecture.

Similar presentations


Presentation on theme: "1 1. Definitions and Terminology 2. Communication between distributed objects 3. Remote procedure call 4. Java RMI 5. CORBA RMI 6. Invocations in JEE architecture."— Presentation transcript:

1 1 1. Definitions and Terminology 2. Communication between distributed objects 3. Remote procedure call 4. Java RMI 5. CORBA RMI 6. Invocations in JEE architecture 7. Invocation of web services 8..NET remoting Chapter 2 Distributed Objects And Remote Invocation (Part I)

2 2 1.Definitions and Terminology 1.Distributed objects 2.Local and remote invocation 3.Remote object references 4.Interface definition language (IDL) 2. Communication between distributed objects 3. Remote procedure call 4. Java RMI Chapter 2 Distributed Objects And Remote Invocation

3 3 1.Definitions and terminology 1.Distributed objects Middleware remote invocation service Computer/network hardware Operating system Middleware Applications and services Transmission Protocols Remote Invocation (RMI/RPC) Request-Reply protocol Marshalling, data representation Messages between Distributed Objects MW services

4 4 1.Definitions and terminology 1.Distributed objects Object model OO systems : objects logical unit Distributed OO systems objects physically distributed remote object state only accessible through methods Architectural models simple client server replicated server objects client server client server service

5 5 1.Definitions and terminology 1.Distributed objects Distributed objects : issues - 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

6 6 1.Definitions and terminology 2.Local vs. remote Local and remote invocations A BC DE remote invocation local invocation Local invocationRemote invocation Use Object ReferenceUse Remote Object Reference Any public methodLimited access, remote interface

7 7 1.Definitions and terminology 2.Local vs. remote Remote interface data Method 1 Method 2 Method 3 A NO constructor (use factory method instead) CORBA : specified using specific Interface Definition Language (IDL) JAVA : standard Java interface (extending Remote ) local invocation local object remote invocation limited access only REMOTE interface

8 8 1.Definitions and terminology 3.Remote object references Remote object references Remote object purpose : unique ID for objects in distributed system uniqueness over time uniqueness over space usage : invoke methods on remote object (instead of local reference) Host : Internet Address Process : Port number + process creation time Object : object number Object type : remote interface IP-addressPort numberCreation timeObject numberInterface 32 ? e.g. Java RMI

9 9 1.Definitions and terminology 3.Remote object references Remote interface : Java RMI example import java.rmi.*; public interface UpperServerInterface extends Remote { String toUpper(String s) throws RemoteException; String getServerName() throws RemoteException; } UppserServerInterface.java

10 10 1.Definitions and terminology 4.IDL Interface definition language 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 usage interface -> specifies interface name attribute -> automatically make getters/setters in -> input parameter (read) out -> output parameter (out) inout -> input & output raises -> throwing exceptions Object -> supertype of all IDL types any -> anything can be passes (void*) readonly -> no setter, only getter for this attribute module -> groups interfaces and types in own name space (use with :: operator)

11 11 1.Definitions and terminology 4.IDL IDL type system built-in types shortunsigned short longunsigned long floatdouble char booleanoctet any use typedef -construct to extend IDL-types inheritance supported on interface level C++ syntax support for multiple inheritance

12 12 1.Definitions and terminology 4.IDL IDL example #ifndef __ECHO_IDL__ #define __ECHO_IDL__ interface echo { string echoString(in string mesg); long times_called(); }; echo.idl

13 13 More advanced IDL example 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 All; interface ShapeList { exception FullException{ }; Shape newShape(in GraphicalObject g) raises (FullException); All allShapes(); // returns sequence of remote object references long getVersion() ; }; 1.Definitions and terminology 4.IDL Whiteboard.idl

14 14 IDL module 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 All; interface ShapeList {...}; }; 1.Definitions and terminology 4.IDL

15 15 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 Chapter 2 Distributed Objects And Remote Invocation

16 16 2.Communicating objects 1.Invocation semantics Middleware remote invocation service Computer/network hardware Operating system Middleware Applications and services Transmission Protocols Remote Invocation (RMI/RPC) Request-Reply protocol Marshalling, data representation MW services distributed object logical interaction “real” info flow 1. what does remote invocation mean ? 2. RMI architecture and services ? 3. how to handle faults ? 4. how to convert objects to bitstreams ?

17 17 2.Communicating objects 1.Invocation semantics 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

18 18 2.Communicating objects 1.Invocation semantics Invocation: syntax 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

19 19 2.Communicating objects 2. Architecture RMI architecture Goal: realize transparency, offer interesting services Communication module Remote reference module RMI software Application objects runs reply-request protocol implements desired invocation semantics manages remote object references translates between local and remote references marshalling automatic proxying request dispatching to server object application logic (distributed objects) proxydispatcherskeleton

20 20 2.Communicating objects 2. Architecture RMI architecture Remote Ref. Mod. communication client server a b Remote Ref. Mod. proxy_b dispatcherskeleton proxy 1 proxy for each remote object local representative of remote object implements all methods of remote interface handles (un)marshalling 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 remote object reference table table of local proxies

21 21 2.Communicating objects 2. Architecture RMI services 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 Binding service Server registers remote objects [1] Client performs lookup [2] client server a b Binding service 1 2 3

22 22 2.Communicating objects 2. Architecture RMI services 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

23 23 2.Communicating objects 2. Architecture RMI services 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

24 24 2.Communicating objects 3. Request-reply protocol 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 Request – reply protocol Socket layer Byte-oriented communication RMI software Object-to-object communication Application objects proxyskeleton

25 25 2.Communicating objects 3. Request-reply protocol Possible implementation Request – reply protocol public byte[] doOperation( RemoteObjectRef o, int methodID, byte[] arguments) RMI software proxyskeleton public byte[] getRequest() public void sendReply( byte[] reply, InetAddress clientHost, int clientPort) doOperation : blocking (synchronous call) getRequest : blocks until request received

26 26 2.Communicating objects 3. Request-reply protocol Possible implementation [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 Message structure e.g. at-most-once invocation semantics messageType[int] requestID[int] objectReference[RemoteObjectRef] methodID[int or Method] arguments[byte[ ] ] [1] [2] [3] [4] [5]

27 27 2.Communicating objects 3. Request-reply protocol Possible implementation requestID ? -> unique ID for messages often used trick (to avoid interprocess synchronization) ID=IDSenderProcess (e.g. port+ IPaddress) + unique_messageID for this process

28 28 2.Communicating objects 3. Request-reply protocol Handling failures 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 Duplicate Re-executeRetransmitInvocation request filtering callreplySemantics NONANANAMaybe YESNOYES--At-least-once YESYES--YESAt-most-once

29 29 2.Communicating objects 3. Request-reply protocol Duplicate filtering algorithm 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

30 30 2.Communicating objects 4. Marshalling Marshalling = transform object in memory to bistream Byte-oriented communication RMI software Object-to-object communicaion proxyskeleton 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 Options

31 31 Java standard serialization class implements Serializable interface writing create ObjectOutputStream (out) call out.writeObject( ) 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 ! 2.Communicating objects 4. Marshalling

32 32 Standard serialization 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; } 2.Communicating objects 4. Marshalling

33 33 Standard serialization class WriteObject { public static void main(String[] args) { ArrayList o; try {writeObjects("obj.dat"); } catch(IOException e) {System.err.println("Output Error : "+e); } 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; } End of file reached. -> a=1 b=10.0 s=First. -> a=2 b=20.0 s=Second. NO CONSTRUCTOR CALLS TO RESTORE OBJECT ! 2.Communicating objects 4. Marshalling

34 34 Standard serialization : Statics 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 2.Communicating objects 4. Marshalling

35 35 Standard serialization : Statics 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()); 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 2.Communicating objects 4. Marshalling

36 36 Aggregating serializables 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; } 2.Communicating objects 4. Marshalling

37 37 Aggregating serializables // … 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. c=100 -> a=2 b=20.0 s=Second. c=200 Serialization mechanism follows the “web of objects” 1 object value = memory -> 1 object value in stream ! 2.Communicating objects 4. Marshalling

38 38 Transient fields 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 2.Communicating objects 4. Marshalling

39 39 Customized serialization 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 2.Communicating objects 4. Marshalling

40 40 Aggregation class A implements Serializable { // clone method added to A public Object clone() {return new A(a);} } 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); out.writeObject(o1); A o2=(A)o1.clone(); System.out.println(o2); out.writeObject(o2); out.close(); } A@192d342-> a=1 A@192d342-> a=10 A@87816d-> a=10 End of file reached. A@a83b8a-> a=1 A@dd20f6-> a=10 with // A@192d342-> a=1 A@192d342-> a=10 A@87816d-> a=10 End of file reached. A@a83b8a-> a=10 A@dd20f6-> a=10 without // Serialization (to same stream !) avoids unnecessary (and dangerous) duplicates OBJECT ONLY WRITTEN ONCE ! HANDLES (“stream references”) WRITTEN instead of full objects ! 2.Communicating objects 4. Marshalling

41 41 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 Chapter 2 Distributed Objects And Remote Invocation

42 42 3. Remote procedure call 1. Architecture RPC History = 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)

43 43 3. Remote procedure call 1. Architecture Architecture communication client server proc a proc b client stub dispatcherserver stub 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

44 44 3. Remote procedure call 2. SUN RPC details 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

45 45 3. Remote procedure call 3. Example Date example (credits: Unix Networking, Stevens) /* * 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 */ date.x 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.

46 46 3. Remote procedure call 3. Example Date example : server side /*dateproc.c remote procedures; called by server stub */ #include /* 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); } dateproc.c 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

47 47 /* rdate.c client program for remote date program */ #include /* 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); } /*... */ } 3. Remote procedure call 3. Example Date example : server side rdate.c

48 48 /*... */ /* 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); } 3. Remote procedure call 3. Example Date example : server side rdate.c client calls client stubs (_1) suffix close handle after use !

49 49 1.Definitions and Terminology 2. Communication between distributed objects 3. Remote procedure call 4. Java RMI 1. Philosophy and design choices 2. Example Chapter 2 Distributed Objects And Remote Invocation

50 50 Java RMI : 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 4. Java RMI 1. Philosophy

51 51 Java RMI : Code download Automatic code download ! client server a b:B 1 : b:B ? 2 3 Security risk Specialized security limitations for downloaded classes Implemented in RMISecurityManager() B_stub : Class b_stub : B_stub 4 Easy to keep clients and servers synchronized (same version) 4. Java RMI 1. Philosophy

52 52 Java RMI : Parameter passing 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 4. Java RMI 1. Philosophy

53 53 Java RMI : Remote interface 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; } 4. Java RMI 1. Philosophy

54 54 Java RMI : Remote objects 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 {/* … */} } 4. Java RMI 1. Philosophy

55 55 Java RMI : Registry 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) 4. Java RMI 1. Philosophy

56 56 Server Remote Interface import java.rmi.*; public interface UpperServerInterface extends Remote { String toUpper(String s) throws RemoteException; String getServerName() throws RemoteException; } 4. Java RMI 2. Example put String to upper case remotely

57 57 Example : Server Object 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; } 4. Java RMI 2. Example

58 58 Example : Server program 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 running..."); } catch(Exception e) { System.err.println("Failing starting server : "+s+e); } 4. Java RMI 2. Example

59 59 Example : Client program 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); } 4. Java RMI 2. Example

60 60 Java RMI : a Client recipe 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 4. Java RMI 2. Example

61 61 Java RMI : a Server recipe 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 4. Java RMI 2. Example

62 62 Activatable Server Objects : Remote Interface and Server Objects 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;} } 4. Java RMI 2. Example

63 63 Activatable Server Objects : Server Program (setup) 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 running... "); } System.exit(0); } 4. Java RMI 2. Example


Download ppt "1 1. Definitions and Terminology 2. Communication between distributed objects 3. Remote procedure call 4. Java RMI 5. CORBA RMI 6. Invocations in JEE architecture."

Similar presentations


Ads by Google