Sunteți pe pagina 1din 65

Remote Method Invocation (RMI)

Object to Object Communication between different Java


Virtual Machines (JVM)

One JVM can invoke methods of an object in another JVM.

“In the Java distributed object model, a remote object is the one whose
method can be invoked from another java virtual machine, potentially a
different host.

An Object of type is described by one or more remote Interfaces,


which are Java interfaces that declare the methods of the remote object.
Remote method Invocation is the action of invoking a method of a
remote interface on a remote object..”
-- RMI Specification
Need For RMI

An Application comprised of smaller applications spread across


different locations in a network.

For Using the processing power of multiple computers.

Sharing resources and processing load across systems.


RMI's Purpose

To make objects in separate JVMs look and act like local objects

One of the most important aspect of RMI design is its transparency,


where Applications do not know whether an object is remote or local.

A Remote object is always accessed via its remote Interface. In other


words the client invokes methods on the object only after casting the
reference to the remote interface.
Stubs

Stub is the client side object that represents or acts as a proxy


for the remote object. The stub has the list of methods, as the
remote object.

Sequence of tasks performed by a stub:

1. Initiates a connection with the remote VM containing the


actual remote object.
2. Marshals the parameters to the remove VM
3. Waits for the result of method invocation
4. Unmarshals the return value or exception returned
5. Returns the value to the caller.
Skeletons

On the server side, the skeleton object takes care of all of the
details of “Remoteness” so that the remote object doesn't need ot
worry about them. In other words, You can pretty much code a
remote object the same way as if it were local.

Sequence of tasks performed by a skeleton

1.Unmarshals the parameters for the remote method.


2.Invokes the method on the actual remote object
implementation
3.Marshals the result or exception to the caller.
Protocols Involved

1.JRMP – Java Remote Method Protocol.(Sun Microsystems)

2.IIOP – Internet Inter-ORB Protocol.(Object Management


Group)

3.NinjaRMI – (BEA Weblogic)

These Protocols uses Stream based network connections over


TCP/IP between the JVMs.
Remote Interface

java.rmi.Remote – A marker – used to mark object as


being remote.

1.Remote Interface must be declared public.

2.It must extend the java.rmi.Remote Interface.

3.Each method in the Interface has to throw


java.rmi.RemoteException
Parameters Passed to Remote Methods

Primitives
are passed by Value

Objects
Think.!!!!
Little More.!!!
In RMI , Objects are passed by value

In RMI Objects are passed by value, not by reference .


A reference to an object doesn't make sense across multiple
JVMs , since a reference, points to a value in the heap. Different
JVMs do not share heap memory.

So RMI sends the object itself, not its reference, between JVMs.
Enterprise Java Beans (EJB)
EJBs are Server Side Components that encapsulates
a bigger chunk of functionality (Business Logic).

The primary reason that you would write an Enterprise Java


Bean Component is to take the advantage of services provided
by the container.

EJB Specification clearly defines the contracts for Component


development. (Client, Bean provider, Container, Server,
Deployer etc.)
Contracts & Container

Contracts

A Statement of responsibilites between different layers of the


software.

Container

A Container is an execution environment for a component.

The Component lives in the container.

The Container provides services for the component.

A component interacts only with its container and the resources the
container provides.
An Application Server

A Container lives in a server which provies an execution


environment for it.

A Server may have one or more containers.


Container Services

1.Transaction
2.Security
3.Concurrency
4.Networking
5.Resource Management
6.presistence
7.Messaging
8.Deploy-time customization

Doing programmatically – writing the code by yourself.


Doing declaratively – Telling the container.
Being a Bean Provider
An EJB is a single unit bundled with collections of
java classes and an XML file.

1. Home Interface

2.Remote Interface

3.Bean Class

4.Deployment Descriptor
Writing Classes for a Component

1.Write Home (extends javax.ejb.EJBHome) Interface

The Home interface is for life cycle operations : Creating,


Finding and removing EJBs. The home interface isn't associated
with a particular Bean.

2.Write Remote (extends javax.ejb.EJBObject) Interface.

The Remote Interface is for business methods, Logically, It


represents a particular bean on the server.
Writing Classes for a Component

3.Implement Interface’s (Either SessionBean or Entity Bean)


container callback methods in your bean class.

4.Write business methods in the Bean Class.

5.Write deployment descriptor file (ejb-jar.xml)


This file tells the container about how to deploy your
bean.
What is the need to Implement these Interfaces.?

?????????????
The Client will never access the bean directly, the container
intercepts the call to provide its services. How will it
Intercepts???

You are making a call to the EJBObject stub. Your Remote


Interface which extend EJBObject is implemented by the
Container. The Container implementation of Remote Interface
has your business methods in which the Bean Business method
is called.
Java Naming and Directory Interface
Usage Of JNDI

• Simple usage: binding and looking up objects by name


• Putting Objects into JNDI (binding objects into the name
space)
• Get an initial context - the first handle into the name
space
• Bind object to context
• Getting Objects out of JNDI (resolving objects out of the
name space)
Bean Class

• Implements the bean’s business methods


• Does NOT implement home or remote interface
• However, it must have methods that match the signatures of
the remote interface.
Deploying EJBs

After the Home interface, Remote interface, Bean Class


implementation and Deployment Descriptor are Written
The class files and descriptor are bundled together as a jar,
using some tools given by App Server vendors an ejb jar is
created
The EJBs must be added to the EJB container.
This process is called deployment.
Deployment Descriptors file tells the EJB server
which are all the classes
….
<ejb-name>StatelessSessionBeanExample</ejb-name>
<home>examples.ejb.basic.statelessSession.TraderHome</home>
<remote>examples.ejb.basic.statelessSession.Trader</remote>
<ejb-class>examples.ejb.basic.statelessSession.TraderBean</ejb-
class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
.........
<jndi-name>statelessSession.TraderHome</jndi-name>
Types of EJBs

 Session Beans

Stateful session Beans


Stateless session Beans

 Entity Beans

Container Managed Persistence (CMP)


Bean Managed Persistence (BMP)
What Is a Session Bean?

A session bean represents a single client inside the J2EE


server acts as a logical interface of the client
Non-persistence object that implements business logic
The business logic is implemented in methods defined in
remote interface.
Stateless Session Beans
Stateless Session Beans

 Does not maintain any conversational state.

 Stateless session beans are pooled by their container to


handle multiple requests from multiple clients.
Life Cycle of Stateless Session Beans
Home Interface

import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
public interface TraderHome extends EJBHome
{
Trader create() throws CreateException, RemoteException;
}
Remote Interface

import java.rmi.RemoteException;
import javax.ejb.EJBObject;
public interface Trader extends EJBObject
{
public TradeResult buy (String stockSymbol, int shares)
throws RemoteException;
public TradeResult sell (String stockSymbol, int shares)
throws RemoteException;
}
Bean Class
import javax.ejb.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class TraderBean implements SessionBean {
private SessionContext ctx;
private int tradeLimit;
public void ejbActivate() { }
public void ejbRemove() { }
public void ejbPassivate() { }
public void setSessionContext(SessionContext ctx) { this.ctx = ctx; }
public void ejbCreate () throws CreateException {}
public TradeResult buy(String stockSymbol, int shares) {
if (shares > tradeLimit) {
shares = tradeLimit; }
return new TradeResult(shares, stockSymbol);
}
public TradeResult sell(String stockSymbol, int shares) {
if (shares > tradeLimit) {
shares = tradeLimit; }
return new TradeResult(shares, stockSymbol);
}}
Client Class
// Lookup the beans home using JNDI
Object home = ctx.lookup(JNDI_NAME);
return (TraderHome) PortableRemoteObject.narrow(home, TraderHome.class);

// create a Trader
Trader trader = (Trader) narrow(home.create(), Trader.class);
String [] stocks = {"BEAS", "MSFT", "AMZN", "HWP" };

// execute some buys


for (int i=0; i<stocks.length; i++) {
int shares = (i+1) * 100;
trader.buy(stocks[i], shares); }

// execute some sells


for (int i=0; i<stocks.length; i++) {
int shares = (i+1) * 100;
trader.sell(stocks[i], shares); }

// remove the Trader


log("Removing the trader");
trader.remove();
ejb-jar.xml
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>statelessSession</ejb-name>
<home>examples.ejb.basic.statelessSession.TraderHome</home>
<remote>examples.ejb.basic.statelessSession.Trader</remote>
<ejb-class>examples.ejb.basic.statelessSession.TraderBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<env-entry>
<env-entry-name>tradeLimit</env-entry-name>
<env-entry-type>java.lang.Integer </env-entry-type>
<env-entry-value>500</env-entry-value>
</env-entry> </session></enterprise-beans>

<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>statelessSession</ejb-name>
<method-intf>Remote</method-intf>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor> </ejb-jar>
weblogic-ejb-jar.xml
Stateless Session Bean – weblogic-ejb-jar.xml
<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>statelessSession</ejb-name>
<caching-descriptor>
<max-beans-in-free-pool>100</max-beans-in-free-pool>
</caching-descriptor>
<jndi-name>statelessSession.TraderHome</jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>

Stateful Session Bean – weblogic-ejb-jar.xml

<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>statefulSession</ejb-name>
<caching-descriptor>
<max-beans-in-cache>100</max-beans-in-cache>
</caching-descriptor>
<jndi-name>statefulSession.TraderHome</jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>
Stateful Session Beans
Stateful Session Beans

 Maintains client-specific session information (called


conversational state) across multiple method calls.
 Each stateful session bean has a timeout value.
 The bean instance is destroyed and theremote reference
is invalidated after the timeout period is elapsed.
Life Cycle of Stateful Session Beans
Activation and Passivation

 During passivation, the state of the EJB instance is stored


automatically by the container.
 During activation, the state of the EJB instance is loaded
automatically by the container.
 An EJB instance may be passivated if none of its methods
are invoked during a specified amount of time (customisable)
 An EJB instance is activated by any method call (if not
active).
Entity Beans
Entity Beans

 An entity bean represents a business object in a persistent


storage
 mechanism like customers, orders, and products.
 Each instance of the bean corresponds to a row in that table.
 Entity lifetime is not dependent on the client connection.
 Shared data between clients.
 May be accessed by multiple clients concurrently.
 Concurrent access is managed by the container or by the
 underlying database
Object / Relational Mapping


Associate a database table with a class each instance
of the class (each object) is stored in a row

Associate a database column with an attribute of the
class
What Makes Entity Beans Different from Session Beans?

• Persistence

Shared Access

Primary Key

Relationships

When to Use Entity Beans ?


The bean represents a business entity, not a procedure.


The bean's state must be persistent.
Life Cycle of Entity Beans
Database Calls

Method SQL Statement

ejbCreate INSERT
ejbFindByPrimaryKey SELECT
ejbFindByLastName SELECT
ejbLoad SELECT
ejbRemove DELETE
ejbStore UPDATE
Container-Managed Persistence

Bean developer doesn't need to write any data access logic.

EJB server will take care of all the persistence needs.

Home Interface

To create a new instance of a CMP entity bean, and therefore insert data into the

database, thecreate() method on the bean's home interface must be invoked

•A bean's home interface may declare zero or more create() methods, each of
which must have corresponding ejbCreate() and ejbPostCreate() methods in the
bean class.

•Finder Methods are used to query the EJB server for specific entity beans, based
on the name of the method and arguments passed.

•The deployer will use vendor specific tools to tell the container how a particular
find method should behave.
Home Interface
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
import javax.ejb.FinderException;
import java.rmi.RemoteException;
import java.util.Enumeration;
public interface AccountHome extends EJBHome {

public Account create(String accountId, double initialBalance, String type) throws


CreateException, RemoteException;

public Account findByPrimaryKey(String primaryKey) throws FinderException,


RemoteException;

public Account findAccount(double balanceEqual) throws FinderException,


RemoteException;

public Enumeration findBigAccounts(double balanceGreaterThan) throws


FinderException, RemoteException;

public Enumeration findNullAccounts() throws FinderException, RemoteException;}


Remote Interface

The remote interface defines the business methods of the entity bean.

The business methods in the remote interface are delegated to the matching business
methods in the bean instance.

import java.rmi.RemoteException;
import javax.ejb.*;
public interface Account extends EJBObject
{
public double deposit(double amount) throws RemoteException;
public double withdraw(double amount) throws ProcessingException,
RemoteException;
public double balance() throws RemoteException;
public String accountType() throws RemoteException;
}
Bean Class

 No database access logic in the bean.

 EJB vendor provides tools for mapping the fields in the Bean
Class to the database.

 Could be mapped to any database providing it contains data that


is similar to the fields in the bean
Bean Class

//Nessary imports

public class AccountBean implements EntityBean


{

private EntityContext ctx;


public String accountId;
public double balance;
public String accountType;

// Implement the callback methods


}
Callback Methods

 setEntityContext()
 unsetEntityContext()
 ejbLoad()
 ejbStore()
 ejbPassivate()
 ejbActivate()
ejb-jar.xml
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>containerManaged</ejb-name>
<home>examples.ejb.basic.containerManaged.AccountHome</home>
<remote>examples.ejb.basic.containerManaged.Account</remote>
<ejb-class>examples.ejb.basic.containerManaged.AccountBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
<cmp-field>
<field-name>accountId</field-name>
</cmp-field>
<cmp-field>
<field-name>balance</field-name>
</cmp-field>
<cmp-field>
<field-name>accountType</field-name>
</cmp-field>
<primkey-field>accountId</primkey-field>
</entity>
weblogic-ejb-jar.xml
<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>containerManaged</ejb-name>
<caching-descriptor>
<max-beans-in-cache>1000</max-beans-in-cache>
</caching-descriptor>
<persistence-descriptor>
<is-modified-method-name>isModified</is-modified-method-name>
<persistence-type>
<type-identifier>WebLogic_CMP_RDBMS</type-identifier>
<type-version>5.1.0</type-version>
<type-storage>META-INF/weblogic-cmp-rdbms-jar.xml</type-storage>
</persistence-type>
<persistence-use>
<type-identifier>WebLogic_CMP_RDBMS</type-identifier>
<type-version>5.1.0</type-version>
</persistence-use>
</persistence-descriptor>
<jndi-name>containerManaged.AccountHome</jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>
Weblogic-cmp-rdbms-jar.xml
<weblogic-rdbms-bean>
<pool-name>demoPool</pool-name>
<table-name>ejbAccounts</table-name>
<attribute-map>
<object-link>
<bean-field>accountId</bean-field>
<dbms-column>id</dbms-column>
</object-link>
<object-link>
<bean-field>balance</bean-field>
<dbms-column>bal</dbms-column>
</object-link></attribute-map>
<finder-list>
<finder>
<method-name>findAccount</method-name>
<method-params>
<method-param>double</method-param>
</method-params>
<finder-query><![CDATA[(= balance $0)]]></finder-query>
</finder> </finder-list>
</weblogic-rdbms-bean>
EJB 2.0
New Features of EJB 2.0

Local Interfaces

Reengineered Container Managed Persistence (CMP)

EJB - Query Language (EJB - QL)

Message Driven Beans

Container Managed Relationship (CMR)

Home Business Methods


Thank You

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