Sunteți pe pagina 1din 46

Advanced Programming (CMIT

6113)
Chapter 5
Distributed Programming
Using RMI and CORBA
• RMI
• RMI architecture
• Serialization
• Steps to develop RMI application
• CORBA
• CORBA architecture
• CORBA IDL
• Naming services
RMI - Remote Method Invocation
 Java RMI is a mechanism to allow the invocation of
methods that reside on different Java Virtual Machines
(JVMs).
 The JVMs may be on different machines or they could be
on the same machine.
 In either case, the method runs in a different address space than
the calling process.
 Java RMI is an object-oriented remote procedure call
mechanism.
 RMI is a distributed object system that enables you to
easily develop distributed Java applications.
 Developing distributed applications in RMI is simpler than
developing with sockets since there is no need to design a
protocol, which is an error-prone task
 Java RMI allowed programmer to execute remote function
class using the same semantics as local function calls.
2
……RMI

Local Machine (Client) Remote Machine (Server)

SampleServer remoteObject;
int s;
… 10,20
s =
remoteObject.sum(10,20);
public int sum(int a,int b)
{
return a + b;
30 }

System.out.println(s);

3
Entities involved in RMI
1. AApplication
remote object is an object on another computer
2. The server object is the object receiving the
request
3. Client: program written to access remote
methods
4. Server: program written to implement the
remote methods
 Clients connect to the server and request that a

method be executed.
5. Object registry: is a program
 runs on a known port (1099 by default)

 A server, upon starting, registers its objects with

a textual name in the object registry.


4  A client, before invoking a remote method, must
General RMI Architecture
Remote Machine
 The server must first
bind its name to the RMI Server
bind

registry
 The client lookup the Registry

server name in the skeleton

registry to establish
remote references. lookup
return call
 The Stub serializing the
parameters to skeleton,
the skeleton invoking the stub
remote method and
serializing the result
back to the stub. RMI Client

Local Machine

5
The Stub and Skeleton
call

skeleton
Stub
RMI Client RMI Server
return
 A client invokes a remote method, the call is first forwarded to stub.
 The stub is responsible for sending the remote call over to the
server-side skeleton
 The stub opening a socket to the remote server, marshaling the
object parameters and forwarding the data stream to the skeleton.
 A skeleton contains a method that receives the remote calls,
unmarshals the parameters, and invokes the actual remote object
implementation.
 RMI uses only TCP, UDP is not supported by RMI.
 Marshalling and UnMarshalling: refers to the process of
converting the data or object being transfered into a byte stream
and unmarshalling is the reverse- converting the stream into an
object or data; conversion is achieved via object serialization.
6
Serialization
 Serialization is the process of writing the state of an
object to a byte stream.
 This is useful when we want to save the state of
our object to a persistent storage such as a file.
 At a later time, we may restore these objects by
using the process of de-serialization.
 The class whose object we want to write to a file,
must implement the Serializable interface.
 Serializable interface is a marker interface means it
does not have any method, it only informs the tools
that are involved in serialization that the class is
ready for serialization.
 For eg.
class Test implements Serializable{

7
RMI – Merits and Demerits
 Merits
 Ease of programming

 No complicated Interface Definition Language

(IDL) to learn
 Demerits
 Uses Proprietary Protocol

 Java Remote Method Protocol (JRMP)

 No cross-language support

8
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

9
Step 1: Defining the Remote
 ToInterface
create an RMI application, the first step is the
defining of a remote interface between the client
and server objects.
 The interface definition:

 must be public
 must extend the interface java.rmi.Remote
 every method in the interface must declare
that it throws java.rmi.RemoteException
 but other exceptions may be thrown as well
/* SampleServer.java */
import java.rmi.*;

public interface SampleServer extends Remote


{
public int sum(int a,int b) throws RemoteException;
}
10
Step 2: Develop the remote object and
its interface
 The server must implement the Remote interface
 It should extend
java.rmi.server.UnicastRemoteObject class
 This will allow the methods to be invoked remotely
 Each method must throw RemoteException
 Because remote procedure calls might fail
 The server uses the RMISecurityManager to
protect its resources while engaging in remote
communication.

11
Step 2: Develop the remote object and
its interface
/* SampleServerImpl.java */
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;

public class SampleServerImpl extends UnicastRemoteObject


implements SampleServer
{
SampleServerImpl() throws RemoteException
{
super();
}
// Implement the remote methods
public int sum(int a,int b) throws RemoteException
{
return a + b;
}
}

12
Develop the remote object…..
 The server must bind its name to the registry, the client will
look up the server name.
 Use java.rmi.Naming class to bind the server name to registry.
In this example, lets use the name “SAMPLE-SERVER”.
 In the main method of your server object, the RMI security
manager is created and installed.
/* SampleServerImpl.java */
public static void main(String args[])
{ try
{
//set the security manager
System.setSecurityManager(new RMISecurityManager());
//create a local instance of the object
SampleServerImpl Server = new SampleServerImpl();
//put the local instance in the registry
Naming.rebind("SAMPLE-SERVER" , Server);
System.out.println("Server waiting.....");
}
catch (RemoteException re)
{ System.out.println("Remote exception: " + re.toString()); }
}
13 }
Step 3: Develop the client program

 In order for the client object to invoke methods on


the server, it must first look up the name of server
in the registry. Use the java.rmi.Naming class to
lookup the server name.
 The server name is specified as URL in the form
(rmi://host:port/name )
 Default RMI port is 1099.
 The name specified in the URL must exactly match
the name that the server has bound to the registry.
 In this example, the name is “SAMPLE-SERVER”
 The remote method invocation is programmed
using the remote interface name (remoteObject)
as prefix and the remote method name (sum) as
suffix.
14
Step 3: Develop the client program
import java.rmi.*;
import java.rmi.server.*;
public class SampleClient
{ public static void main(String[] args)
{ // set the security manager for the client
System.setSecurityManager(new RMISecurityManager());
try
{ //get the remote object from the registry
String url = “rmi://localhost/SAMPLE-SERVER";
SampleServer remoteObject = (SampleServer)Naming.lookup(url);
System.out.println("Got remote object");
System.out.println(" 1 + 2 = " + remoteObject.sum(10,20) );
}
catch (RemoteException exc) {
System.out.println("Error in lookup: " + exc.toString());
}
catch (java.net.MalformedURLException exc) {
System.out.println("Malformed URL: " + exc.toString());
}
catch (java.rmi.NotBoundException exc) {
System.out.println("NotBound: " + exc.toString());
}
15 }
}
Step 4 & 5: Compile the Java source
files & Generate the client stubs
and server skeletons
 Compile the java source files in command prompt
> javac SampleServer.java
> javac SampleServerImpl.java
> javac SampleClient.java
 Generate stubs and skeleton code. The RMI system
provides an RMI compiler (rmic) that takes the
implemented interface class and produces stub
code on itself.
> rmic SampleServerImpl

16
Step 6: Start the RMI registry
 The rmiregistry uses port 1099 by default. You
can also bind rmiregistry to a different port by
indicating the new port number as : rmiregistry
<new port>

 Type the following


> start in the command line:
rmiregistry

17
Steps 7 & 8: Start remote server
objects & Run client
 Once the Registry is started, the server can be
started and will be able to store itself in the
Registry.
 In the command line, to start the remote server:
> java SampleServerImpl

 NOTE: The registry and server processes are


running in the background. Be sure to kill the
registry and server processes when you’re done.
 Finally,
> javatoSampleClient
run the client:
10 20

 The Final Output becomes:


Got remote object
10 + 20 = 30
18
Java Policy File
 Because of the grained security model in Java 2.0, you must
setup a security policy for RMI by updating the java.policy
file.
 In Java 2, the java application must first obtain information
regarding its privileges.
 It can obtain the security policy through a policy file.
 In above example, we allow Java code to have all
permissions, the contents of the java.policy file are:

grant {
permission java.security.AllPermission;
};

19
Distributing the Application
 The easiest way to try a distributed architecture is
to copy all required files manually to correct
machines/directories:
 Copy SampleClient.class (client),
SampleServerImpl_Stub.class (stub),
SampleServer.class (interface) to a directory on
the client machine .
 Copy SampleServer.class (interface),
SampleServerImpl.class (its implementation),
and SampleServerImpl_Stub.class (stub) to a
directory on the server machine.
 *** If your implementation has a database
connection, you can consider putting the database
in a third machine=> 3 Tier
20
What is CORBA?
 Stands for Common Object Request Broker
Architecture(CORBA)
 Is a communication infrastructure for distributed
objects
 Allows a heterogeneous, distributed collection of
objects to collaborate transparently
 A specification for creating distributed objects
 CORBA is NOT a programming language
 Its architecture is based on the object model
 Promotes design of applications as a set of
cooperating objects
 OMG Object Model: object is defined as what the
client could see.
21 OMG- Is an industry Consortium with over 855
What is CORBA good for?
Developing distributed applications
Locating remote objects on a network
Sending messages to those objects
Common interface for transactions, security,
etc.

22
Basic CORBA Architecture

Client Server

request response

ORB ORB

“Object Bus”

23
Object Request Broker (ORB)
Gives the communication infrastructure that is
capable of relaying object requests across
distributed platforms.
Client calls the Object implementation through
interfaces provided by ORB.
Advantages:
Separates Client and Server implementation
Separates both client and Server from underlying
communication infrastructure and protocol stack and
so replaceable while migration from one
implementation to other
IIOP
Internet Inter-Orb Protocol
Network or “wire” protocol
Works across TCP/IP (the Internet protocol)
24
Creating CORBA IDL Files
(Contents)
The CORBA Interface Definition Language (IDL)
Declaring data members, methods, and
parameters
The interface compiler
Separating client and server on different
machines

25
CORBA IDL
IDL is used to describe the interfaces that client
objects call and that object implementations
provide.
It is a specification that enables interoperability
by separating interface from implementation.
It is not a programming language – has no
constructs
It maps to many programming languages like C,
C++, Java, and COBOL via OMG standards

26
The Interface Definition
 The interface is the syntax part of the contract that the server
object offers to the clients that invoke it
 Clients access objects only through their advertised interface,
invoking only those operations that the object exposes
through its IDL interface, with only those parameters (input
and output) that are included in the invocation
 The IDL interface definition is independent of programming
language.
 It is mapped to programming languages using the interface
compiler.
Example:
module Calc
{ interface Calculator
{
float calculate(in float val1, in float val2, in
char operator);
27
};
Mapping IDL to Java, C++

28
Declaring Data Members
Data members are declared using the
attribute keyword.
The declaration must include a name and a
type.
Attributes are readable and writable by default.
To make a readonly attribute, use the
readonly keyword.
IDL compiler generates public read and write
methods for the data member as required.
For example,
attribute long assignable ;
generates,
29
int assignable();
......Declaring Data Members
CORBA const values declared in an IDL map to
public static final fields in the corresponding
Java interface.
Constants not declared inside the interface are
mapped to public interface with the same
name containing a field value.
const float sample = 2.3;
It is also possible to define your own types
using the typedef keyword.
typedef string name;

30
Declaring Methods
Methods are declared by specifying name,
return type, and parameters.
float calculate(in float val1, in float
val2, in char operator);
Methods can optionally throw exceptions.
User-defined exceptions must be declared in
the IDL.

31
Methods Types
 Methods are synchronous by default.

 The client program will wait for the remote

method to execute and return.


 Asynchronous methods are defined using the

oneway keyword.
 oneway methods have no return value, can

have input parameters only and cannot throw


exceptions.
 The client makes the call to the oneway
32
method and continues processing while the
Declaring Methods
module Calc{
interface Calculator{
//User-defined exception
exception MyException{};
//synchronous method
float calculate(in float val1, in float val2, in
char operator) raises (MyException);
//asynchronous method
oneway void setvalue(in long val);
};
};

33
Exceptions
There are two types of CORBA exceptions:

System Exceptions are thrown when something

goes wrong with the system


User Exceptions are generated if something goes

wrong inside the execution of the remote method

They are declared inside the IDL definition for

the object, and are automatically generated by


the IDL compiler
Implementation of these exceptions depends
34
on the language mapping
Declaring Parameters
 Parameters can be of following types:

 Basic (char, long, short, float, bool, etc.),

 Constructed (struct, array, sequence),

 Typed objects, or any.

Parameters can be declared as in, out, or

inout.
in parameters are copied from client to server

out parameters are copied from server to client

inout parameters are used both for incoming


35
and outgoing information and are copied both
Interface Compilers
IDL Compilers implement language mappings
in software.
They compile the interface definition (defined
using IDL) to produce output that can be
compiled and linked with an object
implementation and its clients.
Every ORB comes with one or more IDL
compilers, one for each language that it
supports.
Many vendors supply their IDL compilers.
Because the compilers implement mapping
standards, every vendor's IDL compiler
produces language code with the same
36
mappings, making the code vendor
Need for Interface Compiler
 The interface compiler converts the language independent IDL
to language specific code that C++, Java or other language
clients and servers can understand.
For example, the idlj compiler compiles the IDL to Java
code.
 IDL allows an object implementer to choose the appropriate
programming language for the object.
 Client and Server can be developed in parallel.
 Clients depend only on the interface and not the
implementation of the server code.
 By using IDL and interface compiler, the following can be
defined independent of the programming language
 Modularized object interfaces
 Operations and attributes that an object supports
 Exceptions raised by an operation
 Data types of an operation return value, its parameters, and
37
an object's attributes
The idlj compiler
To compile the IDL to java using idlj,
idlj -fall <idl_file_name>
The –fall option creates both server and
client files
-fclient generates client files only (default)
–fserver generates server files only

38
Files created by idlj
The following classes are created when Calc.idl is
compiled using idlj
 Calc.Calculator - The IDL interface represented as a
Java interface
 Calc.CalculatorHelper - Implements the type
operations for the interface
 Calc.CalculatorHolder - Used for out and inout
parameters
 Calc.CalculatorOperations – The interface that
defines the exposed remote methods
 Calc.CalculatorStub - The client stub. Implements a
local object representing the remote CORBA object
 This object forwards all requests to the remote object.
The client does not use this class directly
 Calc.CalculatorImplBase - An abstract class that
implements the Calculator interface.
39
 It is the server skeleton
Separating Client and Server

Client Server
• _CalculatorStub • _CalculatorImplBa
• Calculator se
• CalculatorHelper • Calculator
• CalculatorHolder

• CalculatorOperatio
CalculatorOperations
ns

40
What next?
Implement the client
Compile the client
Implement the server
Compile the server
Start ORB
Start server
Start client

41
Naming & Directory Services
A naming service maintains a set of bindings
that relate names to objects
All objects in a naming system are named in
the same way (that is, they subscribe to the
same naming convention)
Clients use the naming service to locate
objects by name
Making a request to a service or accessing an
object by means of inter-process
communication requires that one must first
locate the service or object.
Service are abstractions of objects.
42 They are usually represented by processes
…….Naming & Directory Services
 Services and Objects are normally identified by
textual names.
 Alternatively, if names are unknown, service or
object entities can be described by using
attributes associated with them.
 Although services and objects have distinct
meanings, their naming issues are similar
 Name and Directory services, in a narrow sense
are look-up operations.
 The terms name service and directory service are
often used interchangeably.

43
Why do we need Naming & Directory
Services
Object-oriented middleware uses object
references to address server objects
We need to find a way to get hold of these
object references without assuming physical
locations
A name is a sequence of character strings that
can be bound to an object reference
A name binding can be resolved to obtain the
object reference
There may be many server objects in a
distributed object system
Server objects may have several names
44
Naming Service
Naming Service

2. resolve

1. Create binding

Client Server

3. Use target object

45
COS (Common Object Services)
Naming 
The naming service for CORBA applications;
allows applications to store and access
references to CORBA objects.
The CORBA naming service is used by
Clients to locate CORBA objects
Servers to advertise specific CORBA objects
Server creates associations between names
and object references for the CORBA objects
(object binding)
Client retrieve the object references by
querying the naming service and using the
name as the key.
46

S-ar putea să vă placă și