Corso di Formazione Sodalia Enterprise Java Beans Distributed Objects Remote Method Invokation.

Slides:



Advertisements
Similar presentations
CS Network Programming CS 3331 Fall CS 3331 Outline Socket programming Remote method invocation (RMI)
Advertisements

Distributed Objects Remote Method Invokation: Conceptual model.
J0 1 Marco Ronchetti - Basi di Dati Web e Distribuite – Laurea Specialistica in Informatica – Università di Trento.
COS 461 Fall 1997 Network Objects u first good implementation: DEC SRC Network Objects for Modula-3 u recent implementation: Java RMI (Remote Method Invocation)
What is RMI? Remote Method Invocation –A true distributed computing application interface for Java, written to provide easy access to objects existing.
RMI Varun SainiYing Chen. What is RMI? RMI is the action of invoking a method of a remote interface on a remote object. It is used to develop applications.
1 Chapter 9 Network Programming. 2 Overview Java has rich class libraries to support network programming at various levels. There are standard classes.
Copyright © 2001 Qusay H. Mahmoud RMI – Remote Method Invocation Introduction What is RMI? RMI System Architecture How does RMI work? Distributed Garbage.
15-May-15 RMI Remote Method Invocation. 2 “The network is the computer” Consider the following program organization: If the network is the computer, we.
Java Remote Method Invocation (RMI) In Java we implement object systems: O1O2 O3 thread 1thread 2 execution scheme JVM 1JVM 2 distribution scheme.
Java Remote Object Invocation (RMI) Overview of RMI Java RMI allowed programmer to execute remote function class using the same semantics as local functions.
FONG CHAN SING (143334) WONG YEW JOON (143388). JAVA RMI is a distributive system programming interface introduced in JDK 1.1. A library that allows an.
Remote Method Invocation Chin-Chih Chang. Java Remote Object Invocation In Java, the object is serialized before being passed as a parameter to an RMI.
EEC-681/781 Distributed Computing Systems Lecture 5 Wenbing Zhao Department of Electrical and Computer Engineering Cleveland State University
Changing the the way of designing distributed applications Communication design orientation: The design of the protocol goes first and then the development.
Introduction to Remote Method Invocation (RMI)
Java Remote Object Invocation (RMI) Overview of RMI Java RMI allowed programmer to execute remote function class using the same semantics as local functions.
How Does Remote Method Invocation Work? –Systems that use RMI for communication typically are divided into two categories: clients and servers. A server.
JAVA - Network DUT Info - Option ISI (C) Philippe Roose , 2005.
Java RMI Essentials Based on Mastering RMI Rickard Oberg.
1 Java Programming II Java Network II (Distributed Objects in Java)
+ A Short Java RMI Tutorial Usman Saleem
Presentation: RMI Continued 2 Using The Registry & Callbacks.
1 Java RMI G53ACC Chris Greenhalgh. 2 Contents l Java RMI overview l A Java RMI example –Overview –Walk-through l Implementation notes –Argument passing.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 RMI.
Java Remote Method Invocation RMI. Idea If objects communicate with each other on one JVM why not do the same on several JVM’s? If objects communicate.
RMI remote method invocation. Traditional network programming The client program sends data to the server in some intermediary format and the server has.
RMI Remote Method Invocation Distributed Object-based System and RPC Together 2-Jun-16.
Presentation: RMI Continued 2 Using The Registry & Callbacks.
Java Remote Object Invocation (RMI) Overview of RMI Java RMI allowed programmer to execute remote function class using the same semantics as local functions.
Example: RMI Program How to write it.
 Remote Method Invocation  A true distributed computing application interface for Java, written to provide easy access to objects existing on remote.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 43 Remote Method Invocation.
Fall 2007cs4251 Distributed Computing Umar Kalim Dept. of Communication Systems Engineering 17/10/2007.
Java Remote Method Invocation (RMI) Overview of RMI Java RMI allowed programmer to execute remote function class using the same semantics as local functions.
Presentation: RMI Continued 2 Using The Registry & Callbacks.
 Java RMI Distributed Systems IT332. Outline  Introduction to RMI  RMI Architecture  RMI Programming and a Sample Example:  Server-Side RMI programming.
Remote Method Invocation A Client Server Approach.
UMBC Distributed Computing with Objects RMI/Corba CMSC 432 Shon Vick.
Remote Method Invocation RMI architecture stubs and skeletons for remote services RMI server and client in Java Creating an RMI Application step-by- step.
Java RMI. RMI Any object whose methods can be invoked from another Java VM is called a remote object.
1 RMI Russell Johnston Communications II. 2 What is RMI? Remote Method Invocation.
Khoa CNTT 1/37 PHẠM VĂN TÍNH   Java RMI (Remote Method Invocation)
Distributed programming in Java Faculty:Nguyen Ngoc Tu Session 5 - RMI.
CSC 480 Software Engineering Lab 6 – RMI Nov 8, 2002.
Netprog Java RMI1 Remote Method Invocation.
RMI1 Remote Method Invocation Adapted from “Core Java 2” by Cay Horstmann.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 29 Remote Method.
Java Distributed Computing
Java Remote Method Invocation (RMI)
RMI Packages Overview java.rmi java.rmi.server java.rmi.registry
Remote Method Invocation
What is RMI? Remote Method Invocation
Remote Method Invokation
Remote Method Invocation
Knowledge Byte In this section, you will learn about:
Network and Distributed Programming in Java
Creating a Distributed System with RMI
Chapter 40 Remote Method Invocation
Creating a Distributed System with RMI
Overview of RMI Architecture
Remote Method Invocation
Creating a Distributed System with RMI
Chapter 46 Remote Method Invocation
Chapter 46 Remote Method Invocation
Java Remote Method Invocation
Remote Method Invokation: Conceptual model
Creating a Distributed System with RMI
Overview of RMI Architecture
Java Chapter 5 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Corso di Formazione Sodalia Enterprise Java Beans Distributed Objects Remote Method Invokation

Corso di Formazione Sodalia Enterprise Java Beans Object 1Object 2 invoke method respond Object Oriented Paradigm

Corso di Formazione Sodalia Enterprise Java Beans Object 1Object 2 invoke method respond Client Host/Process Server Host/Process Distributed Object Oriented Paradigm

Corso di Formazione Sodalia Enterprise Java Beans Object 1Object 2 socket interaction Local – Client Host/Process Remote - Server Host/Process Post Office Distributed Object Oriented: implementation

Corso di Formazione Sodalia Enterprise Java Beans Object 1Object 2 magic Local – Client Host/Process Remote- Server Host/Process Stub of Object 2Skeleton of Object 2 Distributed Object Oriented: RMI paradigm

Corso di Formazione Sodalia Enterprise Java Beans Distributed Objects Una implementazione fai da te

Corso di Formazione Sodalia Enterprise Java Beans Un oggetto distribuito fai da te package distributedobjectdemo; public interface Person { public int getAge() throws Throwable; public String getName() throws Throwable; } 1. Person: linterfaccia

Corso di Formazione Sodalia Enterprise Java Beans Un oggetto distribuito fai da te package distributedobjectdemo; public class PersonServer implements Person{ int age; String name; public PersonServer(String name,int age){ this.age=age; this.name=name; } public int getAge(){ return age; } public String getName(){ return name; } 2. Person: la classe

Corso di Formazione Sodalia Enterprise Java Beans Un oggetto distribuito fai da te package distributedobjectdemo; import java.net.Socket; import java.net.ServerSocket; import java.io.*; public class Person_Skeleton extends Thread { PersonServer myServer; int port=9000; public Person_Skeleton(PersonServer server) { this.myServer=server; } public static void main(String a[]) { PersonServer person = new PersonServer("Marko",45); Person_Skeleton skel=new Person_Skeleton(person); skel.start(); } // la classe continua… 3. Person: lo skeleton

Corso di Formazione Sodalia Enterprise Java Beans Un oggetto distribuito fai da te public void run(){ Socket socket = null; ServerSocket serverSocket=null; try { serverSocket=new ServerSocket(port); } catch (IOException ex) { System.err.println("error while creating serverSocket"); ex.printStackTrace(System.err); System.exit(1); } while (true) { try { socket=serverSocket.accept(); System.out.println("Client opened connection"); } catch (IOException ex) { System.err.println("error accepting on serverSocket"); ex.printStackTrace(System.err); System.exit(1); } // il metodo continua… 3. Person: lo skeleton

Corso di Formazione Sodalia Enterprise Java Beans Un oggetto distribuito fai da te try { while (socket!=null){ ObjectInputStream instream= new ObjectInputStream(socket.getInputStream()); String method=(String)instream.readObject(); if (method.equals("age")) { int age=myServer.getAge(); ObjectOutputStream outstream= new ObjectOutputStream(socket.getOutputStream()); outstream.writeInt(age); outstream.flush(); } else if (method.equals("name")) { String name=myServer.getName(); ObjectOutputStream outstream= new ObjectOutputStream(socket.getOutputStream()); outstream.writeObject(name); outstream.flush(); } //prosegue con il catch… 3. Person: lo skeleton

Corso di Formazione Sodalia Enterprise Java Beans Un oggetto distribuito fai da te } catch (IOException ex) { if (ex.getMessage().equals("Connection reset")) { System.out.println("Client closed connection"); } else { System.err.println("error on the network"); ex.printStackTrace(System.err); System.exit(2); } } catch (ClassNotFoundException ex) { System.err.println("error while reading object from the net"); ex.printStackTrace(System.err); System.exit(3); } }//fine del ciclo while(true) } //fine del metodo run } //fine della classe 3. Person: lo skeleton

Corso di Formazione Sodalia Enterprise Java Beans Un oggetto distribuito fai da te package distributedobjectdemo; import java.net.Socket; import java.io.*; public class Person_Stub implements Person { Socket socket; String machine="localhost"; int port=9000; public Person_Stub() throws Throwable { socket=new Socket(machine,port); } protected void finalize(){ System.err.println("closing"); try { socket.close(); } catch (IOException ex) {ex.printStackTrace(System.err); } } // la classe continua… 4. Person: lo stub

Corso di Formazione Sodalia Enterprise Java Beans Un oggetto distribuito fai da te public int getAge() throws Throwable { ObjectOutputStream outstream= new ObjectOutputStream(socket.getOutputStream()); outstream.writeObject("age"); outstream.flush(); ObjectInputStream instream= new ObjectInputStream(socket.getInputStream()); return instream.readInt(); } public String getName() throws Throwable { ObjectOutputStream outstream=new ObjectOutputStream(socket.getOutputStream()); outstream.writeObject("name"); outstream.flush(); ObjectInputStream instream= new ObjectInputStream(socket.getInputStream()); return (String)instream.readObject(); } } // fine della classe 4. Person: lo stub

Corso di Formazione Sodalia Enterprise Java Beans Un oggetto distribuito fai da te package distributedobjectdemo; public class Client { public Client() { try { Person person=new Person_Stub(); int age=person.getAge(); String name=person.getName(); System.out.println(name+" ha "+age+" anni"); } catch (Throwable ex) { ex.printStackTrace(System.err); } public static void main(String[] args) { Client client1 = new Client(); } 5. Person: il client

Corso di Formazione Sodalia Enterprise Java Beans Questioni aperte -Istanze multiple -Generazione automatica di stub e skeleton -Identificazione del server on demand -Attivazione della classe remota on demand ClientBrokerServer Registro

Corso di Formazione Sodalia Enterprise Java Beans Distributed Objects Una implementazione RMI - basi

Corso di Formazione Sodalia Enterprise Java Beans CLIENT & SERVER: iCalendar (interface) import java.rmi.*; public interface iCalendar extends Remote { java.util.Date getDate () throws RemoteException; } 1. Define the common interface

Corso di Formazione Sodalia Enterprise Java Beans SERVER: CalendarImpl import java.util.Date; import java.rmi.*; import java.rmi.registry.*; import java.rmi.server.*; public class CalendarImpl extends UnicastRemoteObject implements iCalendar { public CalendarImpl() throws RemoteException {} public Date getDate () throws RemoteException { return new Date(); } public static void main(String args[]) { CalendarImpl cal; try { LocateRegistry.createRegistry(1099); cal = new CalendarImpl(); Naming.bind("rmi:///CalendarImpl", cal); System.out.println("Ready for RMI's"); } catch (Exception e) {e.printStackTrace()} } 2. Implement the service

Corso di Formazione Sodalia Enterprise Java Beans SERVER: CalendarImpl import java.util.Date; import java.rmi.*; import java.rmi.registry.*; import java.rmi.server.*; public class CalendarImpl extends UnicastRemoteObject implements iCalendar { public CalendarImpl() throws RemoteException {} public Date getDate () throws RemoteException { return new Date(); } public static void main(String args[]) { CalendarImpl cal; try { LocateRegistry.createRegistry(1099); cal = new CalendarImpl(); Naming.bind("rmi:///CalendarImpl", cal); System.out.println("Ready for RMI's"); } catch (Exception e) {e.printStackTrace()} } 3. Create Registry

Corso di Formazione Sodalia Enterprise Java Beans SERVER: CalendarImpl import java.util.Date; import java.rmi.*; import java.rmi.registry.*; import java.rmi.server.*; public class CalendarImpl extends UnicastRemoteObject implements iCalendar { public CalendarImpl() throws RemoteException {} public Date getDate () throws RemoteException { return new Date(); } public static void main(String args[]) { CalendarImpl cal; try { LocateRegistry.createRegistry(1099); cal = new CalendarImpl(); Naming.bind("rmi:///CalendarImpl", cal); System.out.println("Ready for RMI's"); } catch (Exception e) {e.printStackTrace()} } 4. Register yourself

Corso di Formazione Sodalia Enterprise Java Beans Server It is not necessary to have a thread wait to keep the server alive. As long as there is a reference to the CalendarImpl object in another virtual machine, the CalendarImpl object will not be shut down or garbage collected. Because the program binds a reference to the CalendarImpl in the registry, it is reachable from a remote client, the registry itself! The CalendarImpl is available to accept calls and won't be reclaimed until its binding is removed from the registry, and no remote clients hold a remote reference to the CalendarImpl object.

Corso di Formazione Sodalia Enterprise Java Beans CLIENT: CalendarUser import java.util.Date; import java.rmi.*; public class CalendarUser { public static void main(String args[]) { long t1=0,t2=0; Date date; iCalendar remoteCal; try { remoteCal = (iCalendar) Naming.lookup("rmi://HOST/CalendarImpl"); t1 = remoteCal.getDate().getTime(); t2 = remoteCal.getDate().getTime(); } catch (Exception e) {e.printStackTrace();} System.out.println("This RMI call took " + (t2-t1) + milliseconds ); } 6. Use Service

Corso di Formazione Sodalia Enterprise Java Beans Preparing and executing SERVER C:dir CalendarImpl.java iCalendar.java C:javac CalendarImpl.java C:rmic CalendarImpl C:dir CalendarImpl.java iCalendar.java CalendarImpl.class iCalendar.class CalendarImpl_Stub.class CalendarImpl_Skel.class C:java CalendarImpl CLIENT C:dir CalendarUser.java iCalendar.java C:javac CalendarUser.java C:dir CalendarUser.java iCalendar.java CalendarImpl_Stub.class C:java CalendarUser copy

Corso di Formazione Sodalia Enterprise Java Beans Distributed Objects Una implementazione RMI - addendum

Corso di Formazione Sodalia Enterprise Java Beans Preparing and executing - security The JDK 1.2 security model is more sophisticated than the model used for JDK 1.1. JDK 1.2 contains enhancements for finer- grained security and requires code to be granted specific permissions to be allowed to perform certain operations. Since JDK 1.2, you need to specify a policy file when you run your server and client. grant { permission java.net.SocketPermission "*: ", "connect,accept"; permission java.io.FilePermission "c:\\…path…\\", "read"; }; java -Djava.security.policy=java.policy executableClass

Corso di Formazione Sodalia Enterprise Java Beans Accesso alle proprietà di sistema Nota: invece che specificare a runtime con lo switch –D del comando java una proprietà, è possibile scriverla nel codice: -Djava.security.policy=java.policy System.getProperties().put( "java.security.policy", "java.policy");

Corso di Formazione Sodalia Enterprise Java Beans Preparing and executing NOTE: in Java 2 the skeleton may not exist (its functionality is absorbed by the class file). In order to use the Java 2 solution, one must specify the switch –v1.2 C:rmic –v1.2 CalendarImpl

Corso di Formazione Sodalia Enterprise Java Beans IMPORTANT: Parameter passing Java Standard: void f(int x) : Parameter x is passed by copy void g(Object k) : Parameter k and return value are passed by reference Java RMI: void h(Object k) : Parameter k is passed by copy! UNLESS k is a REMOTE OBJECT (in which case it is passed as a REMOTE REFERENCE, i.e. its stub is copied if needed)

Corso di Formazione Sodalia Enterprise Java Beans IMPORTANT: Parameter passing Passing By-Value When invoking a method using RMI,all parameters to the remote method are passed by-value.This means that when a client calls a server,all parameters are copied from one machine to the other. Passing by remote-reference If you want to pass an object over the network by-reference,it must be a remote object, and it must implement java.rmi.Remote.A stub for the remote object is serialized and passed to the remote host. The remote host can then use that stub to invoke callbacks on your remote object. There is only one copy of the object at any time,which means that all hosts are calling the same object.

Corso di Formazione Sodalia Enterprise Java Beans Serialization Any basic primitive type (int,char,and so on) is automatically serialized with the object and is available when deserialized. Java objects can be included with the serialized or not: Objects marked with the transient keyword are not serialized with the object and are not available when deserialized. Any object that is not marked with the transient keyword must implement java.lang.Serializable.These objects are converted to bit-blob format along with the original object. If your Java objects are neither transient nor implement java.lang.Serializable,a NotSerializable Exception is thrown when writeObject()is called.

Corso di Formazione Sodalia Enterprise Java Beans When not to Serialize The object is large.Large objects may not be suitable for serialization because operations you do with the serialized blob may be very intensive. (one could save the blob to disk or transporting the blob across the network) The object represents a resource that cannot be reconstructed on the target machine.Some examples of such resources are database connections and sockets. The object represents sensitive information that you do not want to pass in a serialized stream..

Corso di Formazione Sodalia Enterprise Java Beans Alternativa – accensione del registro Invece di scrivere nel codice del server LocateRegistry.createRegistry(1099); è possibile far partire a mano il registro da shell: C: rmiregistry 1099 (port number is optional) Nota: in Java 2 occorre un parametro addizionale: C: rmiregistry –J-Djava.security.policy=registerit.policy dove registerit.policy è un file contenente: grant {permission java.security.AllPermission} o una restrizione dei permessi. Il file è in genere in %USER_HOME%/.java.policy

Corso di Formazione Sodalia Enterprise Java Beans RMI-IIOP RMI-IIOP is a special version of RMI that is compliant with CORBA and uses both java.rmi and javax.rmi. RMI has some interesting features not available in RMI- IIOP,such as distributed garbage collection, object activation,and downloadable class files. But EJB and J2EE mandate that you use RMI-IIOP, not RMI.

Corso di Formazione Sodalia Enterprise Java Beans Distributed Objects Una implementazione RMI – caricamento dinamico dello stub

Corso di Formazione Sodalia Enterprise Java Beans Alternativa 2 – caricamento dinamico dello stub Invece di dover copiare a mano lo stub dal Server al client, si puo caricare lo stub automaticamente a runtime? RMI can download the bytecodes of an object's class if the class is not defined in the receiver's virtual machine. The types and the behavior of an object, previously available only in a single virtual machine, can be transmitted to another, possibly remote, virtual machine. RMI passes objects by their true type, so the behavior of those objects is not changed when they are sent to another virtual machine. This allows new types to be introduced into a remote virtual machine, thus extending the behavior of an application dynamically.

Corso di Formazione Sodalia Enterprise Java Beans Alternativa 2 – caricamento dinamico dello stub SERVER rmiregistry CLIENT http Server STUB VM -rmi class VM –client code

Corso di Formazione Sodalia Enterprise Java Beans This client expects a URL in the marshalling stream for the remote object. It will load the stub class for the remote object from the URL in the marshalling stream. Before you can load classes from a non-local source, you need to set a security manager. Note, as an alternative to using the RMISecurityManager, you can create your ownsecurity manager. import java.util.Date; import java.rmi.*; public class CalendarUser { public static void main(String args[]) { long t1=0,t2=0; Date date; iCalendar remoteCal; System.setSecurityManager(new RMISecurityManager()); try { remoteCal = (iCalendar) Naming.lookup("rmi://HOST/CalendarImpl"); t1 = remoteCal.getDate().getTime(); t2 = remoteCal.getDate().getTime(); } catch (Exception e) {e.printStackTrace();} System.out.println("This RMI call took " + (t2-t1) + milliseconds ); } CLIENT: CalendarUser- Caric.dinamico

Corso di Formazione Sodalia Enterprise Java Beans SERVER: CalendarImpl – Caricamento dinamico import java.util.Date; import java.rmi.*; import java.rmi.registry.*; import java.rmi.server.*; public class CalendarImpl extends UnicastRemoteObject implements iCalendar { public CalendarImpl() throws RemoteException {} public Date getDate () throws RemoteException { return new Date(); } public static void main(String args[]) { CalendarImpl cal; System.setSecurityManager(new RMISecurityManager()); System.getProperties().put( "java.rmi.server.codebase", " try { LocateRegistry.createRegistry(1099); cal = new CalendarImpl(); Naming.bind("rmi:///CalendarImpl", cal); System.out.println("Ready for RMI's"); } catch (Exception e) {e.printStackTrace()} } La prima parte resta invariata

Corso di Formazione Sodalia Enterprise Java Beans Caricamento dinamico di una classe remota Object 1 Class 2 1. Get class Client Host Server Host Class 2 Object 2 2. Create instance 3. Invoke method Diverso paradigma: 1.caricare a runtime una classe residente su una macchina remota, 2.crearne una istanza locale 3.ed eseguirla.

Corso di Formazione Sodalia Enterprise Java Beans La classe remota caricabile dinamicamente import java.awt.*; public class NetworkApp implements Executable { Frame f; public NetworkApp(Frame f) { this.f = f; }; public void exec() { Label l = new Label("Latest version of your application.", Label.CENTER); f.add("Center",l); f.pack(); f.repaint(); } public interface Executable { public void exec(); }

Corso di Formazione Sodalia Enterprise Java Beans import java.awt.*; import java.awt.event.*; import java.net.URL; import java.rmi.RMISecurityManager; import java.rmi.server.RMIClassLoader; import java.lang.reflect.*; public class ExecutableLoader { public static void main(String args[]) { System.setSecurityManager(new RMISecurityManager() { public void checkPermission(Permission p){} });; Frame cf = new Frame("NetworkApp"); cf.show(); try { URL url = new URL(" Class cl = RMIClassLoader.loadClass(url,"NetworkApp"); Class argTypes[] = {Class.forName("java.awt.Frame")}; Object argArray[] = {cf}; Constructor cntr = cl.getConstructor(argTypes); Executable client = (Executable)cntr.newInstance(argArray); client.exec(); } catch (Exception e) {e.printStackTrace();} } Caricatore dinamico