Download as pdf or txt
Download as pdf or txt
You are on page 1of 69

Server Side Component Architectures

Enterprise java beans are a Server side component architecture that enables and simplifies the process
of building enterprise class distributed object applications in java. By using EJB, we can write scalable,
reliable and secure applications without writing our own complex distributed object framework. EJB is
about rapid application development fro the server side. We can quickly and easily construct server
side components in java by leveraging a prewritten distributed infrastructure provided by the industry.
EJB is designed to support application portability and reusability across any vendors enterprise middleware
services.
The Need for a Server-Side Component Architecture
To understand the value EJB brings, we first must examine the needs that developers commonly have
when authoring and deploying components in server side environment. Let us discuss a need for a
standardized architecture such as EJB.
Software Components
A software component is code that implements the set of well defined interfaces. It is a manageable
discrete chunk of logic. Components are not entire applications, they cannot run alone rather they can
be used as puzzle pieces to solve some larger problems. The ideal software component is very powerful.
A company can purchase a well-defined module that solves a problem and combine it with other
components to solve larger problems. For eg., consider a software component that computes the price
of goods we can have this pricing component information about a set of products and it figures out the
total price of the order.
Component Architectures
To facilitate the component development process their should be a standardized way to build, manage
and maintain components. This approach consists of the following:
● Tools for Developing components The process of building the components should be streamlined,
allowing the component developer to focus on writing the core logic behind the component. This
promotes rapid application development and is essential for any component standard to succeed.
● A container that manages your deployed components. This component container provides a
runtime environment for our component to play in. It also provides a set of common services that
most components will need. For example, the container should automatically instantiate new
components as necessary, thus removing that burden from component developer. To combine any
container with any component you must have a well-defined contract between containers and
components. This contract allows any container to manage any component.

1
● Tools for deploying and maintaining components. When the organisation purchases a
components from component vendors there must be set of tools to add in the deployment and
maintenance of those components.
Each of this feature is essential in a mainstream component marketplace and of course, as a component
developer you will like to focus on riding the components themselves rather than the ancillary products
that are common to all components. A well defined component architecture supply the standards
necessary for different vendors to write the components, component containers and tools. Thus, by
having a component architecture developers can employ a “divide-and-conquer” approach to
programming.
Component architectures in Java
Lets look at what component architecture exist in the Java world. The first one we may have heard is
of JavaBeans. Java Beans components are a small-grained application bits. We can use JavaBeans to
assemble larger grind components or to build entire applications. JavaBeans however are development
components and are not deployable components. We typically do not deploy JavaBeans because a
JavaBean is not a complete application; rather JavaBeans help you construct larger software that is
deployable.
The Enterprise Java Bean (EJB) standard defines a component architecture for deployable components
called Enterprise beans. Enterprise Beans are larger, coarser-grained application components that are
ready to be deployed. They can be deployed as is, or they can be assembled with other components
into larger application system.
Enterprise beans are very similar to two other Java components: applets and servlets. Applets can be
deployed in a Web page, where the browser’s appletviewer provides the runtime container for the
applets. Servlets can be deployed in a Web Server where the Web Server Servlet engine provides a
runtime container for the servlets. EJB are deployed in an application server where the application
server provides a runtime container for EJB. The following figure best describes this scenario.

2
Enterprise beans are not for the client side, but are server side components. They are mean to perform
server – side operations, such as executing complex algorithms or performing high – volume business
transactions. Server side components need to run in a highly available, fault tolerant, transactional and
multi-user secure environment. An application server provides this high end server side environment
for the enterprise beans, and it provides the runtime containment necessary to manage enterprise
beans.
The needs of the Server Side
Complete component architecture paves the way for the following.
● Developers to write reusable components
● Vendors to write component containers that provide a runtime environment and services to
components.
● Vendors to provide development, deployment and maintenance tools, which are necessary
complements to the component themselves.
The divide – and – conquer approach allows vendors to provide a set of common services that most
components will need, thus saving precious development and deployment time.
Multi- tier - Architectures
A server side deployment is software written to support concurrent users performing operations
simultaneously, securely, reliably and efficiently. The examples includes Banks, Retail outlets, insurance
agencies etc.
Any well written deployment has a logical software partitioning into layers. Each layer has a different
responsibility in the overall deployment, and within each layer there can be one or more components.
These layers are purely abstractions, and they may not corresponds to physical distribution. A layered
system is well- designed system because each layer is responsible for a separate task. Here is a typical
layer partitioning:
● A presentation layer it contains components dealing with user interfaces and user interaction.
For example, the presentation layer of a stand alone application could be written in visual basic.
The presentation layer of web-based deployment could use java servlets, java server pages or
applets.
● A business logic layer it contains components that work together to solve business problems.
These components could be high performance engines, such as catalog engines. Typically these
components are written in a type-safe language such as java or c++.
● A Data layer it is used by the business logic layer to persist state permanently. Central to the data
layer is one or more databases that house the stored data.
The advantage to partitioning an application into these logical layers is to isolate each layer from the
others.
The physical separation of these layers is another story. In two-tier architecture, two of these layers
are physically separated from the third, forming two physically separated tiers. On the other hand, a
three tier architecture separates each of these three abstract, logical layers into three physically distributed
tiers. In each of these architectures, the tiers are separated from one another by some physical
boundaries.

3
Two-tier architectures
Traditionally, most high-end deployments have been two tiered. Two tier deployments combine the
business logic layer with one of the other two layers. There are two combinations possible:
● Combining the presentation layer with the business logic layer
● Pushing some of the business logic layer into the data layer.
Combining the presentation layer with the business logic layer our presentation layer and the
business logic layer can be coupled together in a single tier, pushing the data access layer into a tier by
itself. This draws a tier boundary between the business logic layer and the data layer. This can be best
illustrated with the following figure. If you think of the first tier as a “client” and second tier as a
“server” this architecture effectively makes the client “fat” and the server “thin”.

In a two tier architecture, the client application typically communicates with the data layer through
database bridge API such as open database connectivity (ODBC) or java database connectivity (JDBC).
This decouples the client from the particular database being used.
Pushing some of the business logic layer into the data layer.
More recently, deployments have begun to combine parts of the business logic layer with the data layer
into a separate tier. This is illustrated in following figure. If we think of the first tier as a “Client” and
the second tier as the “Server”, this architecture effectively makes the client “thin” and the server
“fat”. To actualize this scenario, you push some of your business logic within the database. Database
allows us to execute logic within the database context by writing a suite of modules known as stored
procedures.

4
By pushing select parts of our logic into database enhance the scalability and performance.
N-tier architectures
An N-tier architecture adds one or more tiers to the two-tier model. In N-tier deployments, our
presentation layer, business logic layer and the data layer are separated into respectively physical tiers.
With four or more physical tiers we decompose each of these layers even further to allow various parts
of your system to scale independently.
A complete example of an N-tier architecture is a three-tiered web-based deployment, as illustrated in
following figure.

5
A three-tiered web-based deployment is typically broken down as follows
Presentation tier runs within the address space of one or more web servers. It consists of java
servlets, ASP, JSP etc.
Business Logic Tier runs within the address space of one or more application servers. Application
servers are necessary to provide a suitable containment environment for the business logic components
to run it.
Data Tier consists of one or more databases and may contain data related logic in the form of stored
procedures.
Server –Side Component Architecture solutions
As we learnt that in N-tier architecture we have a need of application servers that provides the usable
runtime environment in which components can execute and provide the needed middleware services
for reliability and scalability. Since there has not been a definition of what a middle-tier component
really is, each application server has been providing component services in a non-uniform, proprietary
way. This greatly reduces portability and is an especially tough pill to swallow in the java world, which
promotes portability. Thus there is a need for standards architecture for server side components. This
architecture needs to craft a well-formed interface between the application server, which contain the
component, and the components themselves.

6
There are so many server-side component architectures provided by different vendors. For Example:
Microsoft Distributed Internet Application Architecture (DNA), Sun Microsystems and Object
Management Group (OMG) etc. we know concentrate on Sun Microsystems’s Java 2 Platform,
Enterprise Edition (J2EE).
Java 2 Platform, Enterprise Edition (J2EE). To enable server side computing in java Sun has
produced a complete development platform called the Java 2 platform enterprise edition. The Mission
of J2EE is to provide a platform-independent, portable, multi-user, secure, and standard enterprise-
class platform for server – side deployment written in the java language. The cornerstone of J2EE is
Enterprise Java Beans (EJB), a standard for building server – side components in java.
The J2EE Technologies The java 2 platform, enterprise edition is a robust suite of middleware
services that make life very easy for server-side application developers. The technologies included
with J2EE are as.
1. Enterprise Java beans (EJB)
2. Java Remote Method Invocation (RMI) : RMI is a mechanism for invoking methods remotely
on other machines. It is tightly integrated with the java language itself. RMI allows java programmers
to communicate in a distributed object fashion using an almost identical programming style to
coding a standalone java applet or application
3. Java Naming and Directory Interface (JNDI) the JNDI is a interface for naming and directory
services. Enterprise java beans rely on JNDI for looking up distributed components across the
network. The JNDI hinges on the notion of a directory service. A directory service stores information
about where resources reside, as well as other information such as user name and passwords.
4. Java Database Connectivity (JDBC) the JDBC 2.0 package is a standard Java extension for
data access that allows java programmers to code to unified relational database API. By using
JDBC, programmer can represent database connections; issue SQL statements, process database
results, and more in a relatively portable way.
5. Java Transaction API (JTA) and java Transaction Service (JTS) . A transaction is a unit of
work that makes a set of guarantees about its execution. For example, one guarantee that transactions
give you is that any code executing within the scope of a transaction is guaranteed either to all be
executed or to not executed at all. To facilitate transactions, the sun Microsystems has produced
two APIs: the java Transaction API (JTA) and Java Transaction Server (JTS). JTA is a high level
transaction interface that our application use to control transactions. JTS is a set of low level
transaction interfaces that EJB uses behind the scenes. JTS make it possible for multiple vendors
to collaborate when performing transactions in a distributed, heterogeneous environment.
6. Java Messaging service (JMS) A messaging service allows for distributed objects to
communicate in an asynchronous, reliable manner. By passing messages asynchronously rather
than synchronously, the overall system scalability is increased. Sun microsystem has released an
API called Java messaging service (JMS) that can be used as a portable messaging service. By
using a common API, distributed objects can communicate in a scalable, transactional, fault-tolerant,
asynchronous and most important, vendor-independent manner.
7. Java Servlets and Java Server Pages (JSPs). Servlets are networked components that we can
use to extend the functionality of a web server.
8. Java IDL Java IDL is sun Microsystems’s java based implementation of CORBA. Java IDL

7
allows for integeration with other languages.
9. Java Mail. The JavaMail service allows us to send e-mail messages in a platform-independent ,
protocol independent manner from our java program. For Example in server side J2EE deployment
we can use java mail to confirm a purchase made on our internet e-commerse site by sending an e-
mail to customer.
The following figure shows the J2EE technologies.

Enterprise Java beans (EJB)


EJB is a component architecture that allows developers to quickly create scalable enterprise applications.
It provides complex middleware enterprise features at no cost to application developers. It defines how
server side components are written and provides a standard contract between the components and the
application server that manage them
The contract between Six Parties
The foundations for EJB portability are the contracts and roles that each party must follow. Going with
the divide-and-conquer theme, EJB partitions the responsibility of an EJB deployment to up to six
different parties. These parties are:
1. The bean provider it provides reusable business components that companies can purchase and
use to help solve business problems. Beans are not complete applications, but rather are deployable
components that can be assembled into complete solutions. The enterprise bean are distributed,
server-side components. They provide useful functionality that can be assembled to form larger
applications.

8
2. The container provider it supplies the low level runtime execution environment needed to run
EJB applications. The EJB container provides a playground where our enterprise bean can run.
There can be many beans running within a container. Bean container are responsible for managing
the beans running within them.
3. The Server provider it supplies the application server logic to contain, manage and deploy
components. Currently there is no distinction between EJB Container providers and EJB server
providers. For examples BEA’s weblogic, Jboss-server etc. the EJB server provides a runtime
environment for one or more containers. EJB servers manage low-level system resources, allocating
resources to containers as they needed. The relationship between the EJB server and Container is
depicted in following Figure.

4. The Application Assembler it is the overall application architect, perhaps for a specific deployment.
He or she is responsible for understanding how various components fit together and writes the
applications that use components.
5. The Deployer takes prewritten components, usually chosen by the application assembler, and
applies his or her deployment expertise to install the components in one or more application servers.
6. The System Administrator oversees the well-being of a deployed system
These parties interact as shown in following figure.

9
Session Bean
Composition Of Enterprise Bean Component
Enterprise beans are distributed, deployable server-side components that can be assembled into larger
applications. Enterprise beans can be portioned across multiple tiers, can be transactional, can be
multi-user secure, and can be deployed in any EJB-compatible container/server product.
Enterprise beans currently have two flavors: session beans and entity beans. Session beans
represent a business process, whereas entity beans represent permanent business data.
The Enterprise bean component is composed of the Enterprise bean class, the remote interface, the
EJB object, the Home interface, the Home object, the deployment descriptor, the manifest, and the
EJB-jar file.
The Enterprise Bean Class
As we have discussed in previous chapters that the Enterprise Java beans specification defines the
contracts between parties involved in deployment. In order for a bean to work in any container, and to
work with any client of that bean, the bean must adhere to a well-defined interface.
In EJB we can provide our Enterprise bean component implementation using Enterprise Bean Class.
This is simply a java class that conforms to a well-defined interface and obeys certain rules.
The EJB specification defines a few standard interfaces that our bean class can implement. These
interfaces force our bean class to expose certain methods that all bean must provide, as defined by the
EJB model. The container calls these required methods to manage your bean and alert your bean to
significant events.
The most basic interface that all bean classes must implement is the javax.ejb.EnterpriseBean interface,
which in turn extends java.io.serializable. The signature of this interface is as:
public interface javax.ejb.EnterpriseBean extends java.io.Serializable
{
}
For session beans we have to implement javax.ejb.SessionBean interface and for entity bean we
have to implement javax.ejb.EntityBean. Both these interfaces are inherited from
javax.ejb.EnterpriseBean
The EJB Object
When a client wants to use an instance of an enterprise bean class, the client never invokes the method

10
directly on an actual bean instance. Rather, the invocation is interprecepted by the EJB container and
then delegated to the bean instance because:
● Our Enterprise Bean Class is not network-enabled, so it can’t be called across the network. Thus
EJB container handles networking by wrapping our bean in a network enabled object. The network
enabled object then receives the calls from clients and delegates these calls to instances of our
bean class.
● By intercepting request, the EJB container can automatically perform some necessary management.
This includes transaction logic, security logic, bean instance pooling logic, and any other logic that
the container may require
Thus the EJB container is acting as a layer of indirection between the client code and the bean. This
layer of indirection manifests itself as single network object, called the EJB Object. The EJB object is
a surrogate object that knows about networking, transactions, security, and more. It is an intelligent
object that knows how to perform intermediate logic that the EJB container requires before a method
call is serviced by a bean class instance. We depict the ejbHome in following figure as:

The Remote Interface


As we learnt that, the bean clients invoke methods on EJB object, rather than the bean themselves. To
perform this the EJB object must clone every business method that our bean class expose. This is done
by creating an Interface called Remote Interface. This Is an Interface, which contains all the business
logic methods that the corresponding bean class exposes, and is created by bean provider.
All Remote Interfaces must derive from a common interface that is provided by sun Microsystems.
This interface is called javax.ejb.EJBObject its Signature is as follows:
Public interface javax.ejb.EJBObject extends java.rmi.Remote
{
public abstract javax.ejb.EJBHome getEJBHome( )
throws java.rmi.RemoteException;

11
public abstract java.lang.Object getPrimaryKey( )
throws java.rmi.RemoteException;
public abstract void remove( )
throws java.rmi.RemoteException, javax.ejb.RemoveException;
public abstract javax.ejb.Handle getHandle( )
throws java.rmi.RemoteException;
public abstract Boolean isIdentical(javax.ejb.EJBObject)
throws java.rmi.RemoteException;
}
The explanation of each method is as:
Method Explanation
GetEJBHome( ) retrieves a reference to the corresponding home object
getPrimaryKey( ) Returns the primary key for this EJBObject. For entity bean only
remove( ) Destroys this EJBObject. The system resources for the EJBObject can
then be reclaimed
getHandle( ) Acquires the handle for this EJBObject. It is a persistent reference to an
EJBObject that the client can stow away somewhere.
IsIdentical( ) Tests whether two EJBObjects are identical
In addition to the methods listed above, our remote interface duplicates bean’s business methods.
The Home Object
As we learnt that, the client code deals with EJB Object and never with beans directly. But the question
is how do clients acquire reference to EJB Object. The client cannot instantiate EJB Object directly
because EJB Object could exist on a different machine than the one the client is on.
To acquire a reference to an EJBObject, client code asks for an EJBObject factory. This factory is
responsible for instantiating EJBObject. The EJB specification calls such a factory a home object. The
chief responsibilities of home object are:
● Create EJB Objects
● Find existing EJB Objects
● Remove EJB Objects
Home objects are proprietary and specific to each EJB container. These are physically part of the
container and are auto-generated by the container vendor’s tools.
The Home Interface
As we have learnt that home objects are factories for EJB objects. But question is how does a home
object know how we would like our EJBObject to be initialized. E.g. one EJB object might expose an
initialization method that takes an integer as a parameter, while another EJB object might take a string
instead. The container needs to know this information to generate home object. We provide this
information by specifying a Home Interface.

12
Home Interface simply defines methods for creating destroying and finding EJB objects. As usual EJB
defines some required methods that all home interfaces must support. These required methods are
defined in the javax.ejb.EJBHome interface- an interface that your home interface must extend. The
following figure shows the home Object

Deployment Descriptors
The next file we must include with our Enterprise bean component is a deployment descriptor. Deployment
descriptor enable EJB container to provide implicit middleware services to enterprise bean components.
An implicit middleware service is a service that your beans can gain without coding to any middleware
API-the bean gain the service automatically. To inform the container about our middleware needs, we
as a bean provider must declare components’ middleware service requirement in a deployment descriptor
file. E.g. we can use a deployment descriptor to declare how the container should perform life-cycle
management, persistence, transaction control, and security services.
Bean-Specific Properties
Finally we can include a Java-based properties file with our bean. Our bean can read these properties
in at runtime and use the properties to tune how the bean functions.
Ejb-jar-File
Once we have generated bean classes, home interfaces, remote interfaces, deployment descriptors,
and bean’s properties, it’s time to package them up into one entity. This entity is called Ejb-jar-file. It is
a compressed file that contains every thing we have discussed, and it follows the .ZIP compression
format. Jar files are convenient, compact modules for shipping our Java software.
Once we have made Ejb-jar-file, our Enterprise bean is complete, and it is a deployable unit within an
application server. When they are deployed, the tools that EJB container vendors supply are responsible
for decompressing and reading and extracting the information contained within the Ejb-jar-file.
What is a Session Bean?
Session beans are Enterprise beans that represent work performed for a client. Session beans are

13
intended to represent business. A session bean is relatively short-lived component. Roughly it has the
lifetime equivalent of a client’s session. A client’s session duration could be as long as a browser
window is open, perhaps connecting to an E-commerce site with deployed session bean. It could also
be as long as your Java applet is running, as long as stand-alone application is open, or as long as
another bean is using our bean.
Session beans are nonpersistent. This means that session beans are not saved to permanent storage.
They can perform database operations, but they itself is not a persistent object.
Session beans can be divides in two categories:
● Stateless Session Bean
● Stateful Session Bean
Stateless Session Bean
A stateless session bean is a bean that holds conversations that span a single method call. They are
stateless because they do not hold multimethod conversation with their client. After each method call,
a stateless session bean clears itself out of all information pertaining to past invocations.
Stateful Session Bean
Stateful session beans are components that hold conversations with clients that may span many method
calls. During a conversation, the bean holds conversational state for that client and that client alone.
Thus, Stateful session bean are more functional than stateless session bean because they retain
conversational state.
All session Bean’s Methods are Serialized
When we call a method on a session bean instance, then EJB container guarantees that no other clients
are using that instance. The container exclusively holds that bean instance and directs concurrent
clients to other instances or makes them wait until you’re done with that instance. Thus if multiple
clients simultaneously invoke methods on a session bean, the invocations are serialized, or perform in
lock step. This means that the container automatically makes clients lineup one by one to use a bean
instance.
Writing Session Beans
To write a session enterprise bean class, our class must implement the javax.ejb.SessionBean interface,
which in turn is inherited from javax.ejb.EnterpriseBean interface. The signature of
javax.ejb.SessionBean is as:
public interface javax.ejb.SessionBean extends javax.ejb.EnterpriseBean
{
public abstract void setSessionContext(SessionContext ctx)
throws java.rmi.RemoteException;
public abstract void ejbPassivate( )
throws java.rmi.RemoteException;
public abstract void ejbActivate( )
throws java.rmi.RemoteException;

14
public abstract void ejbRemove( )
throws java.rmi.RemoteException;
}
Let us discuss each method in detail.
setSessionContext(SessionContext ctx)
The container calls this method to associate our bean with a session context. A session context is
bean’s gateway to interact with container. Our bean can use session context to query the container
about current transactional state, current security state etc.
A typical bean implementation would store the context away in a member variable so the context can
be queried later. For Example:
import javax.ejb.* ;
public class MyBean implements SessionBean
{
private SessionContext ctx;
public void setSessionContext(SessionContext ctx)
{
this.ctx = xtx;
}
}
ejbCreate(…)
This method initializes our session bean. We can define several ejbCreate (…) methods, and each can
take different argument. This allows clients to initialize bean in different ways.
þ There is no ejbCreate(…) method listed in javax.ejb.SessionBean interface. But you
must provide at least one ejbCreate (…) method in your bean.
import javax.ejb.* ;
public class MyBean implements SessionBean
{
private int var;
public void ejbCreate(int num)
{
this.var = num;
}
}
ejbCreate (…) methods are callback methods that container will invoke. Client code never calls
ejbCreate (…) methods because clients never deal with bean directly – they must go through container.
R You must duplicate each ejbCreate () method in your home interface, because home
interface is the factory method that clients calls to initialize our bean. In home interface
you must leave off the “ejb” part of the signature.

15
EjbPassivate ()
If too many beans are instantiated, the EJB container can passivate some of them, which means
writing the beans to a temporary storage such as a database or file system. The container can then
release the resources the beans had claimed. Immediately before your beans are passivated, the container
calls your ejbPassivate( ) method.
þ Passivation does not apply to session bean because stateless session beans do not
hold state and can simply be created/destroyed rather then passivated/activated.
ejbActivate()
When a client needs to use a bean that’s been passivated, the reverse process automatically occurs.
The container kicks the bean back into memory, or activates the bean. Immediately after your bean is
activated, the container calls your ejbActivate() method.
þ Passivation does not apply to session bean because stateless session beans do not
hold state and can simply be created/destroyed rather then passivated/activated.
ejbRemove()
When the container is about to remove your session bean instance, it calls your bean’s ejbRemove( )
callback method. EjbRemove( ) is a clean up method, alerting your bean that it is about to be destroyed
and allowing it to end its life gracefully
þ There is only one ejbRemove( ) method per bean, which is in stark contrast to ejbCreate(
), which has many forms.

þ The container may never call bean’s ejbRemove( ) method, such as if the container
crashes or if critical exception occurs.
Business Methods
In addition to required callback methods, we should define zero or more business method in our bean.
These methods actually solve the business problems. For Example:
import javax.ejb.*;
public class MyBean implements SessionBean
{
public int add(int I, int j)
{
return (I+j);
}
}
þ For clients to call business method, we must list our business methods in bean’s home
interface.
Calling Session Bean At Client Side
In real world client can exist in any scenario:

16
● On a stand-alone machine communicating with beans deployed locally
● In a stand-alone application communicating over the network with remote beans.
● In a java-based applet running inside a web browser, communicating over the network with remote
beans.
● Behind a web server, communicating over a LAN with remote beans. The end user might be using
an HTML-based user interface, communicating over the Internet, bound to the bean client with
glue-code such as Java Server Pages or Java Servlet.
In any of these scenarios we have following steps.
● Look up home object
● Use the home object to create an EJB object.
● Call business methods on the EJB objects.
● Remove the EJBObject.
Looking Up Home Object
To look up home object client must use the JNDI. To achieve location transparency, EJB container
masks the specific locations of home objects from enterprise bean’s client code. Clients do not hard
code the machine names that home objects reside on, but rather they use JNDI to look up home
objects. Home objects are physically located on somewhere on the network.
For clients to locate home object, we must provide a nickname for bean’s home objects. Clients will
use this nickname to identify the home object it wants. For Example, if you have bean called MyBean,
you may specify a nickname MyHome to the home object. Then any client on any machine across a
multi-tier deployment can use that nickname to find home objects, without regard to physical machine
locations. Clients use the JNDI API to do this. For that our client code must execute the following
steps to acquire a reference to a home object via JNDI:
● Set up your environment we must specify which directory service we are using. Specify the
network location of the directory service we desire.
● Form the initial context The initial context is a local starting point for connecting to directory
structures.
● Retrieve the home object To retrieve the home object, we must perform JNDI lookup ()
operation on the remote directory. The returned object is an RMI remote object that you must cast
to a home object. The following code segment illustrates these steps:
// Get the system properties for JNDI initialization
Properties props = System.getProperties();
// form an initial context
Context ctx = new InitialContext(props);
// Get a reference to the Home object – the factory for EJB objects
MyHome home = (MyHome) ctx.lookup(“MyHome”);

17
Creating An EJB Object
Once our client code has a reference to a home object, we can use that home as a factory to create
EJB objects. To create an EJB object, call one of the create( ) methods on the home. The following line
illustrates this:
MyRemoteInterface ejbObject = home.create( );
þ When we call create( ), then the bean instance’s ejbCreate( ) method may not be
called because the container can pool and reuse existing beans.
Calling a Method
Now the bean’s clients has an EJB object, so it can start calling one or more of the methods that the
bean exposes through the EJB Object. When the client calls a method on the EJB object, the EJB
object must choose a bean instance to service the request. The EJB object may create new instance or
reuse existing one.
The following line illustrates calling add ( ) business method through the EJB object:
Ejbobject.add ();
Destroying the EJB Object
Finally when we want to destroy an EJB Object, call a remove( ) method on the EJB Object or home
object. The syntax is:
Ejbobject.remove ();
þ As with creating a bean, destroying a bean might not necessarily correspond with
literally destroying in-memory bean objects because EJB container controls their life
cycles to allow for pooling between heterogeneous clients.

18
Stateless Session Bean
Writing a “Hello World” Stateless Session Bean
Let us create one small example of stateless session bean, a component running in a distributed object
frame work, will be responsible for the mighty task of returning the string “Hello World” to the client.
● Constructing The “Hello World” Remote Interface The remote interface duplicates business
method that our bean expose. The container will implement the remote interface; the implementation
is the EJB object. The EJBObject will delegate all client requests to actual beans. This interface is
inherited by javax.ejb.EJBObject and has one business method hello (), which returns the string
“hello world” back to the client.
package book;
import javax.ejb.* ;
import java.rmi.RemoteException;
import java.rmi.Remote;
public interface Hello extends EJBObject
{
public String hello( ) throws java.rmi.RemoteException;
}
● Implementing the “Hello World” Bean Let us create the bean itself. We will implement our
one business method hello (). To make it session bean we will implements the
javax.ejb.SessionBean.
package book;
import javax.ejb.*;
public class HelloBean implements SessionBean
{
public void ejbCreate()
{
System.out.println(“ejbCreate() is executing”);
}
public void ejbRemove()
{

19
System.out.println(“ejbRemove() is executing”);
}
public void ejbActivate()
{
System.out.println(“ejbActivate() is executing”);
}
public void ejbPassivate()
{
System.out.println(“ejbPassivate() is executing”);
}
public void setSessionContext(SessionContext ctx)
{
System.out.println(“setSessionContext () is executing”);
}
//Business method
public string hello( )
{
System.out.println(“Hello() executed”);
Return “Hello World !”;
}
}
● Constructing the “Hello World” Home Interface Our home interface specifies mechanisms
to create and destroy EJB objects. To make it home interface we extends javax.ejb.EJBHome.
This home interface also exposes one method to create an EJB objects and takes no arguments.
This is correct because we are dealing with ststeless session beans, and stateless sessions have
empty create () method
package book;
import javax.ejb.*;
import java.rmi.RemoteException;
public interface HelloHome extends EJBHome
{
Hello create() throws RemoteException, CreateException;
}

● Writing The Deployment Descriptor Next we need to generate a Deployment Descriptor;


which describes our bean’s middleware requirement to the container. Deployment Descriptor s are
the one of the key features of EJB because they allow us to declaratively specify attributes on our
bean, rather than programming this functionality into the bean itself. In EJB 1.0, a deployment
descriptor is a serialized object that we store as a file on disk. In EJB 1.1, a deployment descriptor
is an XML document. Following are the settings which we have to specify into Deployment
descriptor.

20
ü Bean home name. The nickname that clients use to lookup bean’s home object.
ü Enterprise Bean class name. The fully qualified name of the enterprise bean class.
ü Home interface class name. The fully qualified name of home interface.
ü Remote interface class name. The fully qualified name of the remote interface.
ü Re-entrant whether the enterprise bean allows re-entrant calls. This setting must be false for
session beans.
ü Stateful or stateless Whether the session bean is Stateful or stateless session bean.
ü Session Timeout the length of time (in seconds) before a client should timeout when calling
methods on your bean.
Here is the setting of deployment descriptor of our HelloBean
Deployment Descriptor Setting Value
Bean home name HelloHome
Enterprise bean class name HelloBean
Home Interface Class Name HelloHome
Remote interface class name Hello
Environment properties <empty>
Re-entrant false
Stateful or stateless STATELESS_SESSION
Session timeout 10 second
þ For JBOSS server the Deployment Descriptor is as follows:
<?xml version=”1.0"?>
<!DOCTYPE ejb-jar PUBLIC ‘-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN’ ‘http:/
/java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd’>
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>Hello</ejb-name>
<home>book.HelloHome</home>
<remote>book.Hello</remote>
<ejb-class>book.HelloBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>Hello</ejb-name>
<method-name>*</method-name>
</method>

21
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
The above file should be named, as ejb-jar.xml and it should be in META-INF folder
● The Jar File Now the final step is to package all the necessary files that we have created into one
single Ejb-jar file. The following file must be included in an Ejb-jar file:
Enterprise Bean
Remote interface
Home interface
Deployment descriptor
þ If we are working with ejb1.0, than we can also include manifest file containing a list of
what’s in the Ejb-jar file. Manifests are simple text files that can be part of a jar file. In Ejb-
1.0, the manifest file identifies which enterprise beans are inside Ejb-jar file. In EJB-1.1
manifests are not necessary because the XML deployment descriptor contains all the
necessary descriptive information. Here’s the manifest that goes with our “Hello World”
Name: HelloBean.ser
Enterprise-Bean: True
ü Here the first line locates our serialized deployment descriptor within the jar
ü The second line simply indicates to the container that we are indeed supplying an enterprise bean.
● Generating the Ejb-jar file we generate the Ejb-jar file with the following statement:
The structure of jar file is like as:
META-INF\
Ejb-jar.xml
Book\
Hello. class
HelloBean.class
HelloHome.class
To create the jar file type the following command at DOS prompt, remaining in the parent directory of
book.
Jar –cvf Hello.jar META-INF/ejb-jar.xml book/*.class
● Deploying the Bean To deploy the Bean in Jboss-server is very simple. What we have to do only
is put the Hello.jar file in deploy folder of Jboss – server. So next time whenever we start the
server the bean is automatically load in the server.
þ Include all the jar files available in the client folder of Jboss server in your classpath
● Writing Client Code for Our Stateless Bean The complete client code is as:
package book;

22
import javax.ejb.*;
import javax.naming.*;
import javax.rmi.*;
import java.util.Properties;
public class HelloClient
{
public static void main( String args[])
{
try
{
Properties prop = new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY,”org.jnp.
interfaces.NamingContextFactory”);
prop.put(Context.PROVIDER_URL,”localhost:1099");
Context ctx = new InitialContext(prop);
Object objref = ctx.lookup(“Hello”);
HelloHome home = (HelloHome)javax.rmi.PortableRemoteObject.
narrow (objref,HelloHome.class);
Hello hello = home.create();
System.out.println(hello.hello());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
The client code performs the following tasks:
1. Looks up home object
2. Uses the same object to create an EJB object
3. Calls hello( ) on the EJB object
4. Remove the EJB object.
● Running the System Following steps we have to perform in running our bean
1. First of all include all the jar files of client folder of Jboss server in your classpath
2. open the instance of MS-DOS and change the path to \JBoss-2.4.3_Tomcat-3.2.3\jboss\bin\>
type the command RUN then enter. This run command will start the server
3. open another instance of MS-DOS and change path to the parent folder of book (our package
name) then type the following command.
Java book.HelloClient
● Client Output
Hello World !

23
● Server output
SetSessionContext() is executing
EjbCreate () is executing
Hello () executed.

Let us create one more EJB which calculates the Interest and return it to the client. Following are
the necessary files for that:

Interest.java
This is our Remote interface

package finance;

import javax.ejb.* ;
import java.rmi.RemoteException;
import java.rmi.Remote;

public interface Interest extends EJBObject


{
public double interest(double amt,double time,double rate) throws
java.rmi.RemoteException;
}
In above remote interface we have define one business method interest(double amt,double
time,double rate). We will implement it in our entity bean class
InterestHome.java
This is our Home interface
package finance;
import javax.ejb.*;
import java.rmi.RemoteException;
public interface InterestHome extends EJBHome
{
Interest create() throws RemoteException, CreateException;
}
InterestBean.java
This is our entity bean
package finance;
import javax.ejb.*;
public class InterestBean implements SessionBean
{

24
public void ejbCreate()
{
System.out.println(“ejbCreate() is executing”);
}
public void ejbRemove()
{
System.out.println(“ejbRemove() is executing”);
}
public void ejbActivate()
{
System.out.println(“ejbActivate() is executing”);
}
public void ejbPassivate()
{
System.out.println(“ejbPassivate() is executing”);
}
public void setSessionContext(SessionContext ctx)
{
System.out.println(“setSessionContext () is executing”);
}
//Business method
public double interest(double amt,double time,double rate)
{
double minterest;
System.out.println(“Interest () called”);
minterest = (amt*time*rate)/100;
return minterest;
}
}
The deployment Descriptor ejb-jar.xml of our enterprise bean is as:
<?xml version=”1.0"?>
<!DOCTYPE ejb-jar PUBLIC ‘-//Sun Microsystems, Inc.//DTD Enterprise
JavaBeans 1.1//EN’ ‘http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd’>
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>Interest</ejb-name>
<home>finance.InterestHome</home>
<remote>finance.Interest</remote>
<ejb-class>finance.InterestBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>

25
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>Interest</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
þ The above Deployment Descriptor should be in META-INF folder.
Generating Interest.JAR file
Start the instance of MS-Dos and change current directory to the parent of META-INF. In same
directory you have to put finance folder, which is our package. Then Type the following command.
Jar –cvf Interest.jar META-INF\ejb-jar.xml finance\*.class
InterestClient.java
This is our clint-side programme.
package finance;
import javax.ejb.*;
import javax.naming.*;
import javax.rmi.*;
import java.util.Properties;
public class InterestClient
{
public static void main( String args[])
{
try
{
double mamt = Double.parseDouble(args[0]);
double mtime = Double.parseDouble(args[1]);
double mrate = Double.parseDouble(args[2]);
Properties prop = new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY,”org.
jnp.interfaces.NamingContextFactory”);
prop.put(Context.PROVIDER_URL,”localhost:1099");
Context ctx = new InitialContext(prop);
Object objref = ctx.lookup(“Interest”);
InterestHome home = (InterestHome)javax.rmi.
PortableRemoteObject.narrow(objref,InterestHome.class);

26
Interest hello = home.create();
System.out.println(“Interest is : “ +
hello.interest(mamt,mtime,mrate));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Deploying and running the EJB
1. copy the Interest.jar to deploy folder of Jboss-server.
2. start the Jboss-server by typing the run command at dos prompt
þ Make sure the Path is correct
3. open another MS-DOS instance. Change path to the parent folder of finance folder (Our
Package), then type the following command.
Java finance.InterestClient 1000 2 10
þ You may change the value of amount, time and rate of interest.
OutPut
200
Let us create another client for the above Enterprise bean Interest, having GUI interface. This interface
is provided using Abstract Window Toolkit (AWT).
The coding as follows:
InterestFrame.java
package finance;
import javax.ejb.*;
import javax.naming.*;
import javax.rmi.*;
import java.util.Properties;
import java.awt.*;
import java.awt.event.*;
public class InterestFrame extends Frame implements ActionListener
{
Label l1, l2, l3;
TextField tf1, tf2, tf3,tf4;
Button b1,b2;
Panel p1, p2, p3;
Interest hello;

27
public InterestFrame()
{
super();
//finding reference of ejb
try
{
Properties prop = new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY,”org.jnp.
interfaces.NamingContextFactory”);
prop.put(Context.PROVIDER_URL,”localhost:1099");
Context ctx = new InitialContext(prop);
Object objref = ctx.lookup(“Interest”);
InterestHome home = (InterestHome)javax.rmi.
PortableRemoteObject.narrow(objref,InterestHome.class);
hello = home.create();
}
catch(Exception e)
{
System.out.println(e);
}
//adding form elements
setLayout(null);
p1 = new Panel(new GridLayout(4,2));
p2 = new Panel(new GridLayout(2,4,5,5));
p3 = new Panel(new GridLayout(2,1));
p1.add(l1 = new Label(“Amount”));
p1.add(tf1 = new TextField(20));
p1.add(l2 = new Label(“Rate”));
p1.add(tf2 = new TextField(20));
p1.add(l3 = new Label(“Time Duration”));
p1.add(tf3 = new TextField(20));
p1.add(l3 = new Label(“Interest”));
p1.add(tf4 = new TextField(20));
p2.add(b1 = new Button(“Calculate”));
p2.add(b2 = new Button(“Quit”));
b1.addActionListener(this);
b2.addActionListener(this);
p3.add(p1);
p3.add(p2);
add(p3);

28
p3.setBounds(10, 40, 300, 180);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == b1)
{
double mamt = Double.parseDouble(tf1.getText());
double mrate = Double.parseDouble(tf2.getText());
double mtime = Double.parseDouble(tf3.getText());
double interest=0;
//calling the business method of enterprise bean
try
{
interest = hello.interest(mamt,mtime,mrate);
}
catch(Exception e)
{
System.out.println(e);
}
String ss=””;
ss=ss+interest;
tf4.setText(ss);
}
else
{
System.exit(0);
}
}
public static void main(String args[])
{
InterestFrame f = new InterestFrame();
f.setSize(500, 500);
f.show();
}

29
The output is as:

Compiling the Client file


Open an instance of MS-DOS and change path to the parent of finance folder (Package). Then type
the following command:
Javac I*.java
Running the Client
Change the path to the parent of finance (package), then type the following command
Java finance.InterestFrame

30
Stateful Session Beans
Stateful session beans are conversational beans because they hold conversations with clients that span
multiple method invocations. Stateful session beans store conversational state within the bean. That
conversational state is specific to particular client.
Characteristics of Stateful Session Beans Following are the characteristics of Stateful beans:
● Achieving the effect of pooling with Stateful Beans Stateful session bean can also achieve the
effect of polling as that by stateless session bean, but in a different way. With Stateful session
beans, polling is not so simple, because when a client invokes a method on bean, he or she is
starting a conversation with the bean, and the conversational state stored in the bean must be
available for that same client’s next method request. Therefore, container cannot easily pool beans
and dynamically assign them to handle arbitrary client method requests, since each bean is storing
state on behalf of a particular client. The container solves this problem using Passivation and
activation. During Passivation the container swap out a Stateful bean, saving its conversational
state to a hard disk or other storage. After passivating a Stateful session bean, the conversational
state is safely stored away, allowing resources such as memory to be reclaimed. In activation
reversed process took place. Whenever the original client invokes a method, the passivated
conversational state is swapped in to a bean. This process is called activation.
þ The bean that receives the activated state may not be the original bean instance, but
that’s all right because the instance is resuming its conversation from the point where
the original instance was passivated.
● Governing Conversational State using Java Object Serialization When a container passivates
a bean, it uses object serialization to convert bean’s conversational state into a bit-blob. It can then
write that blob out to storage. Once the bean is written to storage, the memory is available to be
freed by the garbage collector. Activation reverse the process – a serialized blob that had been
written to storage is read back into memory and converted to in – memory bean data. The whole
process works because javax.ejb.EnterpriseBean interface which extends java.io.Serializable,
and every enterprise bean class indirectly implements this interface.
● Activation/Passivation Callback When an EJB container passivates a bean, the container writes
the bean’s conversational state to secondary storage, such as file or database. The container informs
the bean that it is about to perform Passivation by calling the bean’s required ejbPassivate( )
callback method. The container inform the bean using ejbPassivate( ) so that the bean can relinquish
held resources. These resources include database connections, open files etc. the exact opposite
occurs during activation process. Here the serialized conversational state is read back into memory,
and constructs the in-memory state using object serialization or the equivalent. The container then

31
calls the bean’s ejbActivate( ) method. ejbActivate( ) gives the bean chance to restore the open
resources that it released during ejbPassivate( ).
A Simple Stateful Session Bean Example
Let us discuss a simple example of Stateful session bean. In this example our bean will be a counter
bean, and will be simply responsible for counting up one by one. The current count will be stored within
the bean, and it will increment as client request arrive. Following are the steps:
1. The count Bean’s Remote Interface our remote interface defines a single business method
count( ), which we will implement in the enterprise bean class
import javax.ejb.*;
import java.rmi.RemoteException;
public interface Count extends EJBObject
{
public int count () throws RemoteException;
}
2. Creating Session Bean named CountBean Our bean implementation has one business method
count (), which is responsible for incrementing an integer member variable, called val. The
conversational state is the Val member variable. The code is as follows:
import javax.ejb.*;
public class CountBean implements SessionBean
{
private SessionContext ctx;
//The current counter is our conversational state.
public int val;
//Buisness method
public int count()
{
System.out.println(“count()”);
return ++val;
}
//EJB required methods
public void ejbCreate(int val) throws CreateException
{
this.val = val;
System.out.println(“Ejb Create()”);
}
public void ejbRemove()
{
System.out.println(“Ejb Remove()”);
}

32
public void ejbActivate()
{
System.out.println(“Ejb Activated()”);
}
public void ejbPassivate()
{
System.out.println(“Ejb Passivated()”);
}
public void setSessionContext(SessionContext ctx)
{
}
}
3. Creating Count Bean’s Home Interface To complete our Stateful bean code, we must define a
home interface. The home interface will detail how to create and destroy our count EJB object.
The code is as follows:
import javax.ejb.*;
import java.rmi.RemoteException;
public interface CountHome extends EJBHome
{
Count create(int val) throws RemoteException, CreateException;
}
4. Creating Deployment Descriptor here’s the Deployment descriptor of our count bean.
Deployment Descriptor Setting Value
Bean home name CountHome
Enterprise bean class name CountBean
Home Interface Class Name CountHome
Remote interface class name Count
Environment properties <empty>
Re-entrant false
Stateful or stateless STATEFUL_SESSION
Session timeout 10 second
Max beans loaded at any time 2
The Deployment descriptor ejb-jar.xml is shown below:
<?xml version=”1.0"?>
<!DOCTYPE ejb-jar PUBLIC ‘-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN’
‘http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd’>
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>Count</ejb-name>

33
<home>counter.CountHome</home>
<remote>counter.Count</remote>
<ejb-class>counter.CountBean</ejb-class>
<session-type>Stateful</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>Count</ejb-name>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
5. The Count Bean’s Client Code Following steps we have to perform in client’s code
1. We acquire a JNDI initial context.
2. We locate the home object using JNDI.
3. We use the home object to create three different Count Ejb Objects. Thus we are creating
three different conversations and are simulating three different clients.
4. Our deployment descriptor limits the bean pool size to two beans, so during the previous step
some of the three beans must have been passivated. We print out a message using ejbPassivate()
callback to illustrate this.
5. Next, we call count () on each EJB object. This forces the container to activate the instances,
restoring the conversations to memory once again.
6. Finally all the EJB objects are removed.
The code is as:
import javax.ejb.*;
import javax.naming.*;
import java.util.Properties;
public class CountClient
{
public static void main(String args[])
{
try
{
//Get System properties for JNDI //initialization
Properties props = System.getProperties();

34
//Get a reference of the Home Object
Context ctx = new InitialContext(props);
CountHome home = (CountHome)ctx.lookup(“CountHome”);
//An array to hold 3 count objects.

Count count[] = new Count[3];


int countVal = 0;
System.out.println(“Instantiating the beans”);
for(int i = 0;i<3;i++)
{
//create an EJB object and initialize it
to the current count value
count[i] = home.create(countVal);
//calling buisness method
countVal = count[i].count();
System.out.println(countVal);
//sleep for 1/2 second
Thread.sleep(500);
}
//Let’s call count() on each object to make
sure the beans
//were passivated and activated properly
System.out.println(“Calling count() on
beans...”);

for(int i = 0;i<3;i++)
{
countVal = count[i].count();
System.out.println(countVal);
Thread.sleep(500);
}
//Removing EJB objects
}catch(Exception e)
{
e.printStackTrace();
}
}
}
6. Running the client
1. First of all include all the jar files of client folder of Jboss server in your classpath
2. open the instance of MS-DOS and change the path to \JBoss-2.4.3_Tomcat-3.2.3\jboss\bin\>
type the command RUN then enter. This run command will start the server
3. open another instance of MS-DOS and change path to the parent folder of book (our package

35
name) then type the following command.
Java book.CountClient
7. The Client-Side Output After running the client, we see the following output:
Instantiating Bean…
1
2
3
Calling count () on beans….
2
3
4

36
Entity Bean
In this chapter we are going to discuss about what is an entity bean, how it differs the session Bean and
some characteristics of entity bean
What is an Entity Bean?
In today’s object-oriented multitier deployment we have two different kinds of components:
● Application Logic Component These components are method providers that perform common
tasks. Their tasks might include the following:
1. Computing the price of an order
2. Billing a customer’s credit card.
3. Computing the inverse of matrix, or any kind of business process.
These application logic components are well represented by Session Beans.
● Persistent Data Component These are the objects that know how to render themselves into
persistent storage. These kinds of objects represent data – simple or complex information that
we’d like saved. Examples here includes:
1. Bank account information, such as account number and balance.
2. Human resource data, such as names, departments etc, or any kind of business data that we’d
like to save.
These persistent data components are best represented by Entity Beans. Entity beans are enterprise
beans that know how to persist themselves permanently to a durable storage such as database.
Entity bean store data as fields, such as bank account number etc. they also have methods associated
with them, such as getBankAccountNo( ) etc. we can think of entity bean instance as the following.
§ An in-memory java representation of persistent data
§ Smart enough to know how to read itself from storage and populate its fields with the
stored data.
§ An object that can be modified in-memory to change the value of data
§ Persist able, so that it can be saved back into storage again, thus updating the
database data.
For example, we might want to read bank account data into an entity bean instance, thus loading the
stored database information into the in-memory entity bean instance’s fields. We can play with the java
object and modify its representation in memory because we are working with convenient java objects,
rather than bunch of records. We can increase the bank account balance in memory, thus updating the
entity bean’s in-memory bank account balance field. Then we can save the java object, pushing the

37
data back into the underlying storage. This would effectively deposit money into the bank account.
Files Included With Entity Beans
Following are the files that make up an entity bean component:
● The Entity bean class It is a java class that models persistent data. An entity bean class maps to
an entity definition in a database schema. For example an entity bean class could map to a relational
table definition. In this case an entity bean instance of that class would map to a row in that table.
Our entity bean class can expose simple methods to manipulate or access that data, such as a
method to decrease a bank account balance. Like session bean class, EJB also requires that an
entity bean class must fill in some standard callback methods.
● The Entity Bean’s Remote Interface It is the interface to our beans on which clients invoke. In
it, we should place each of our entity bean’s business method signatures.
● The entity Bean’s Home Interface It is the interface that clients use to create, find and destroy
entity bean EJB objects. In it, we should put the different possible methods we’d like available to
create new entity bean Ejb Objects, and to find or destroy old ones.
● The Entity Bean’s primary key class it is a unique identifier for your entity bean. Primary keys
make every entity bean different. For Example, if we have one million different bank account
entity beans, each bank account needs to have unique ID that can never be repeated in any other
bank account. A primary key is an object that may contain any number of attributes. This could be
whatever data necessary to uniquely identify an entity bean data instance. EJB gives us the flexibility
to define what our unique identifier is by including primary key class with our entity bean. The one
rule is that our primary key class must be serializable and follows the rule for java object serialization.
● The Entity Bean’s Deployment Descriptor It contains a list of properties that should be used
by the container on deployment
● The Entity Bean’s environment properties It allows end users to customize our entity bean on
deployment. These are optional.
Features of Entity Beans
Let’s now take a look at the features of Entity Beans.
● Entity Beans Are Long Lived Entity Beans in comparison to Session bean can last for days,
months or even years. For Example we definitely would want our bank account to last for a few
years.
● Entity Beans Survive Failure Because entity beans are part of persistent storage, a crash of
Java Virtual Machine (Or database) does not affect the life cycle of an entity bean. As soon as the
things come back online, the entity bean instances can be created once more, simply by rereading
the data from the database and instantiating entity bean instances to represent that data in memory.
● Several Entity Bean Instances May Represent The Same Underlying Data Let’s consider
the scenario where many threads of execution want to access the same database data simultaneously.
To facilitate many clients accessing the same data, and to boost performance, we could allow
containers to instantiate multiple instances of the same entity bean class. This would allow for
many clients to concurrently interact with separate instances, each representing the same underlying
entity data. Thus client request do not necessarily need to run independently - they can now run

38
simultaneously in several different bean instances. Having multiple bean instances represent the
same data now raises a new problem: data corruption. If many bean instances are representing the
same underlying data, the we are dealing with multiple in – memory cached replicas. Some of these
replicas could become stale, representing data that is not current. To achieve entity bean instance
cache consistency, each entity bean instance needs to be routinely synchronized with the underlying
storage. The container synchronizes the bean with the underlying storage by calling the ejbLoad ()
and ejbStore () callbacks.
þ ejbLoad () reads the data in from the persistent storage into the entity bean’s in-
memory fields.

þ ejbStore () saves bean instance’s current fields to the underlying data storage. It is
the complement of ejbLoad ()
● Entity Bean Instances can Be Pooled To save precious time in instantiating objects, entity bean
instances are recyclable objects and may be pooled depending on container’s policy. The container
may pool and reuse entity bean instances to represent different instances of same type of data in
an underlying storage. For Example a container could use a bank account entity bean instance to
represent different bank account records. Thus when you are done using an entity bean instance,
that instance may be assigned to handle a different client request and may represent different data.
The container performs this by dynamically assigning the entity bean instance to different client-
specific EJB Object. Not only this saves the container from unnecessarily instantiating bean instance,
but also this scheme saves on total amount of resources held by the system. The polling process
can be best demonstrated using following diagram

39
Unlike Session bean here also ejbActivate () and ejbPassivate () methods will invokes. But here before
calling ejbPassivate () , the container invokes the entity bean’s ejbStore() method and prior to calling
ejbActivate (), the container calls ejbLoad () method.
● Entity Beans can be created, Removed, or Found Like session bean Entity beans also support
methods for initialization as well as destruction. Along with these two methods it also support
method for finding a bean. When a new entity bean instance is created then container invokes a
ejbCreate () method and in case of removal container invokes ejbRemove () method. In case of
Entity bean the ejbCreate () method is responsible for creating some data in underlying database
that correlates with the in-memory instance. Similarly ejbRemove () method is responsible for
removing database data. Because entity bean data is uniquely identified in an underlying storage,
entity beans can also be found rather than created. Finding an entity bean is analogous to performing
a SELECT statement in SQL. When we find an entity bean we are searching a persistent store for
some entity bean data. This differs with session beans because they cannot be found. We can
define many ways to find an entity bean. We list these ways as methods in entity bean’s home
interface. These are called finder methods
● Entity Beans can be Modified without going through EJB Usually we will create, destroy
and find entity bean data by using the entity bean’s home object. But we can interact with entity
beans another way, too: by directly modifying the underlying database where the bean data is
stored. For Example if entity bean instances are being mapped to a relational database, you can
simply delete the rows of the database corresponding to an entity bean instance. We can also
create new entity bean data and modify existing data by directly touching the database. The concept
can be best illustrated by following diagram.

Developing and Using Entity Bean


To write an entity bean class, our class must implement the javax.ejb.EntityBean Interface that is
extended by javax.ejb.EnterpriseBean. This interface defines a number of required methods that our

40
entity bean must implement. Most of them are management methods that are called by Ejb container.
Following code represent these methods:
Public interface javax.ejb.EntityBean implements
javax.ejb.EnterpriseBean
{
public abstract void setEntityContext (javax.ejb.EntityContext);
public abstract void unsetEntityContext ();
public abstract void ejbRemove();
public abstract void ejbActivate ();
public abstract void ejbPassivate ();
public abstract void ejbLoad ();
public abstract void ejbStore ();
}
Creation of Entity Beans: ejbCreate ()
An entity bean instance’s ejbCreate () method is used to initialize a bean for a particular client and to
create underlying database data. Each ejbCreate we define gives clients a different way to create your
entity beans.
Here are some rules about ejbCreate ():
● You do not need to write any ejbCreate () methods with entity bean. Session beans require
ejbCreate () methods, but they are optional for entities. We’d define an ejbCreate () method if we
want to provide a way to create some underlying data through EJB. Since the Ejb does allow for us
to create data indirectly, via direct database inserts or legacy systems. Thus ejbCreate () is optional.
● The parameters to ejbCreate () can vary this allows for multiple ways to initialize an entity
bean instance and thus allow for different ways to create entity bean data in a database. For
Example one ejbCreate () method might create a checking account, while another might create a
saving account.
● You must duplicate ejbCreate () methods in your home interface. In Ejb, client don’t directly
invoke on beans-they invoke an EJB object proxy. The Ejb object is generated through the home
object. Therefore, for each ejbCreate () method signature you define in our bean, we must define
a corresponding create () in the home interface. The client calls the objects create (), which delegates
to our bean’s ejbCreate ().
Finding Existing Entity Beans: ejbFind ()
Our entity bean class’s finder methods are used to find an existing entity bean in storage. Finder
methods do not create any new database data- they simply load some old entity bean data. We can
have many different finder methods, which all perform different operations. For example:
Here are the some rules about finder methods:
● All finder methods must begin with “ejbFind”
● We must have at least one finder method; called ejbFindByPrimaryKey This method finds
one unique entity bean instance in the database based on its unique primary key. Because every
entity bean has an associated primary key, it makes sense that every entity bean class supports this
method.

41
● We can have many different finder methods, with different names and different parameters
to each method. This allows us to find using different semantics.
● A finder method must return either the primary key for the entity bean it finds or an
enumeration of primary keys if it finds more than one. Because we could find more than one
data instance in the database, finder methods can return enumerations of primary keys.
● As with ejbCreate (), clients do not invoke our finder methods on the bean instance itself.
A finder method is just like any other method on our entity bean class – client never directly call
any bean’s methods. Rather, clients invoke finder methods on home objects, implemented by the
EJB container, that delegate to your bean. Therefore for each finder method we define in our bran
class, we must define a corresponding finder in the home object.
Destruction of Entity Beans: ejbRemove ()
To destroy an entity bean’s data in a database, the client must call remove () on the Ejb object or home
object. This method causes the container to issue an ejbRemove () call on the bean. The ejbRemove ()
does not mean the in-memory entity bean instance is going to be destroyed-ejbRemove () destroys only
database data. The bean instance can be recycled to handle a different database data instance. This
can be best illustrated with following diagram. EjbRemove () is required method of all entity beans and
it takes no parameters. There is only one form of ejbRemove (). With entity beans, ejbRemove () is not
called if the client times out because the lifetime of an entity bean is longer than the client’s session.

Entity Contexts
All enterprise beans have a context object that identifies the environment of the bean. These context
objects contain environment information that the EJB container sets. Our bean can access the context

42
to retrieve all sorts of information, such as transaction and security information. For entity beans the
interface is javax.ejb.EntityContext, which is inherited from javax.ejb.EJBContext. The interface is
as:
public interface javax.ejb.EJBContext
{
public abstract javax.ejb.EJBHome getEJBHome ();
public abstract java.util.Properties getEnvironment ();
public abstract java.security.Identity getCallerIdentity ();
public abstract boolean isCallerInRole (java.security.Identity);
public abstract javax.jts.UserTransaction getUserTransaction ();
public abstract void setRollbackOnly ();
public abstract boolean getRollbackOnly ();
}
getEjbObject ()
This method retrieve the current, client-specific EJB object that is associated with the entity bean.
getPrimaryKey ()
It retrieves the primary key that is currently associated with this entity bean instance. Primary key
uniquely identify an entity bean. When an entity bean is persisted in storage, the primary key can be
used to uniquely retrieve the entity bean because we can never have two entity bean database data
instance that have the same primary key.
Life Cycle of an Entity Bean
The following figure shows the life cycle of an entity bean.

43
Let us discuss what is going on in above figure.
1. The does not exist state represents entity bean instance that have not been instantiated yet.
2. To create a new instance, the container calls the newInstance () method on the entity bean
class. This calls our entity bean’s default constructor, bringing a new instance into memory.
Next, the container associates our entity bean with an entity context object.
3. After step 2-entity bean is in a pool of other entity beans. At this point our entity bean does not
have an entity bean database data loaded into it, and it does not hold any bean specific resources,
such as socket connections etc. our bean instance can be used in this mode to find entity data
in the database, by servicing a finder method on behalf of client. If the container wants to
reduce pool size, it can destroy our bean. The container signals our bean instance that it is
about to destroy by calling the unsetEntityContext () method on our bean. Once this is done, the
container releases any references to our bean, and eventually, the java garbage collector will
cleanup the memory our bean instance had been using.
4. When client wants to create some new database data, it calls a create () method on our entity
bean’s home object. The container then grabs an entity bean instance from the pool, and the
instance’s ejbCreate () method is called. EjbCreate () initializes the entity bean to a specific
data set. Now our bean is in the “Ready” state.
5. While our bean is in ready state, it is tied to specific data and hence a specific EJB object. If
there are other entity bean instances that are views into the same database data, the container
may occasionally need to synchronize our bean instance with the underlying database, so that
we will always be working with the most recent data. The ejbLoad () and ejbStore () method
do this.
6. There are two ways for our entity beans to be kicked back into the pool. If a client calls remove
() on the home object, then the container will call our instance’s ejbRemove (). The underlying
database data is destroyed, and so.
7. The second way our bean can return to the pool is if the EJB container decides that our client
has timed out, if the container needs to use our bean to service a different client, or if the
container is simply running out of resources. At this point our bean is passivated, and the
container calls ejbStore () method to ensure the database has the most recent version of our in-
memory data. Next, the container calls ejbPassivate () method – allowing our bean instance to
release all bean-specific resources. Our bean instance then enters the pool.
8. When the container wants to assign you to an EJB object again, our bean instance must be
activated. The container calls our bean’s ejbActivate () method, allowing our bean to acquire
bean – specific resources. The container then calls our instance’s ejbLoad () method to load
the database data into our bean.
Extra Study Material
Let us consider an example, which represents a simple bank account entity bean. This bank account
bean can be used to represent and manipulate real bank account data in an underlying relational database.
The object model for our bank account is in following figure.

44
Let’s take a look at each of the files that we must create for our entity bean component.
Account.java
It is our entity bean’s remote interface
package account;
import javax.ejb.*;
import java.rmi.RemoteException;
public interface Account extends EJBObject
{
public void deposit(double amt) throws RemoteException;
public void withdraw(double amt) throws RemoteException;
public double getBalance() throws RemoteException;
public String getOwnerName () throws RemoteException;
public void setOwnerName(String name) throws RemoteException;
public String getAccountId () throws RemoteException;
public void setAccountId (String id) throws RemoteException;
}
AccountHome.java
It is our bean’s Home interface

45
package account;
import javax.ejb.*;
import java.rmi.RemoteException;
import java.util.Enumeration;
public interface AccountHome extends EJBHome
{
Account create(String accounted) throws CreateException,RemoteException;
Public Account findByPrimaryKey(AccountPK key) throws FinderException,RemoteException;
Public Enumeration findByOwnerName(String name) throws
FinderException,RemoteException;
}
AccountPK.java
Our entity bean’s primary key class is defined by AccountPK.java. our primary key is a simple string-
the account ID string. This string must be unique to it’s bank account.
package account;
import java.io.Serializable;
public class AccountPK implements java.io.Serializable
{
public string accountID;
public AccountPK(String id)
{
this.accounted = id;
}
public AccountPK()
{
}
public String toString()
{
return accountID;
}
}
AccountBean.java
It is our entity bean implementation class.
package account;
import java.sql.*;
import javax.naming.*;
import java.ejb.*;
import java.util.*;
import java.rmi.RemoteException;

46
public class AccountBean implements EntityBean
{
protected EntityContext ctx;
public String accounted; //PK
public String ownerName;
public double balance;
public properties env;
public AccountBean ()
{
System.out.println(“New bank account entity bean java object
created by EJB container”);
}
public void deposit(double amt)
{
System.out.println(“deposit(“ + amt + “) called”);
Balance += amt;
}

public void withdraw(double amt)


{
System.out.println(“withdraw(“ + amt + “) called”);
If(amt > balance)
{
throw new AccountException(“your balance is less thane
amount, u can not withdrawl”);
}
Balance -= amt;
}
public double getBalance()
{
System.out.println(“getBalance() called”);
return balance;
}
public void setOwnerName(String name)
{
System.out.println(“setOwnerName() called”);
OwnerName = name;
}
public String getOwnerName()
{
System.out.println(“geOwnerNAme() called”);

47
return ownerName;
}
public void setAccountID(String id)
{
System.out.println(“setAccountId() called”);
this.accountID = id;
}
public String getAccountId()
{
System.out.println(“getAccountId() called”);
return accountId;
}
public void ejbActivate () throws RemoteException
{
System.out.println(“ejbActivate() called”);
}
public void ejbRemove () throws RemoteException
{
System.out.println(“ejbRemove() called”);

AccountPK pk = (AccountPK) ctx.getPrimaryKey();


String id = pk.accountID;
/*
*/
PreparedStatement psmt = null;
Connection con = null;
Try
{
conn = getConnection();
pstmt = conn.prepareStatement(“delete from accounts where id = ?”);
pstmt.setString(1,id);
if(pstmt.executeUpdate() == 0)
{
throw new RemoteException(“Account failed to remove from database”);
}
}catch(Exception e)
{
System.out.println(e);
}
}

48
public void ejbPassivate() throws RemoteException
{
System.out.println(“EjbPassivate() called”);
}
public void ejbLoad() throws RemoteException
{
System.out.println(“ejbLoad() called”);
AccountPk = (AccountPk) ctx.getPrimaryKey();
String id = pk.accountId;
PreparedStatement pstmt = null;
Connection conn = null;
Try
{
conn = getConnection();
pstmt = conn.prepareStatement(“Select ownerName,balance from
accounts where id = ?”);
pstmt.setString(1,id);
ResultSet rs = pstme.executeQuery();
rs.next();
ownerName = rs.getString(“ownerName”);
balance = rs.getDouble(“balance”);
}
catch(Exception e)
{
System.out.println(e);
}
}
public void ejbStore() throws RemoteException
{
System.out.println(“Ejbstore() called”);
PreparedStatement pstmt = null;
Connection conn = null;
Try
{
conn = getConnection();
pstmt = conn.prepareStatement(“update accounts set ownerName
= ?, balance=? Where id = ?”);
pstmt.setString(1,ownerName);
pstmt.setDouble(2,balance);
pstmt.setString(3,accountID);
pstmt.executeUpdate();
}

49
catch(Exception e)
{
System.out.println(e);
}
}
public void setEntityContext(EntityContext ctx) throws
RemoteException
{
System.out.println(“setEntityContext() called”);
This.ctx = ctx;
env = ctx.getEnvironment ();
}
public void unsetEntityContext() throws RemoteException
{
System.out.println(“unsetEntityContext() called”);
This.ctx = null;
env = null;
}
public void ejbPostCreate(String accountId, String ownerName)
throws RemoteException
{
}
public AccountPK ejbCreate(String accountId, String ownerName)
throws CreateException,RemoteException
{
PreparedStatement pstmt = null;
Connection conn = null;
Try
{
System.out.println(“ejbCreate() called”);
this.accountId = accountId;
this.ownerName = ownerName;
this.balance = 0;
conn = getConnection();
pstmt = conn.prepareStatement(“insert into
accounts(id,ownerName,balance) values(?,?,?)”);
pstmt.setString(1,accountId);
pstmt.setString(2,ownerName);
pstmt.setdouble(1,balance);
pstmt.executeUpdate();
return new AccountPK(accountId);
}

50
catch(Exception e)
{
System.out.println(e);
}
}
public AccountPK ejbFindByPrimaryKey(AccountPK key) throws
FinderException,RemoteException
{
PreparedStatement pstmt = null;
Connection conn = null;
Try
{
System.out.println(“ejbFindByPrimaryKey () called”);
conn = getConnection();
pstmt = conn.prepareStatement(“select id from accounts where id
= ?”);
pstmt.setString(1,key.toString());
ResultSet rs = pstmt.executeQuery();
rs.next();
return key;
}
catch(Exception e)
{
System.out.println(e);
}
}
public Enumeration ejbFindByOwnerName(String name) throws
FinderException, RemoteException
{
PreparedStatement pstmt = null;
Connection conn = null;
Try
{
System.out.println(“ejbFindByOwnerName () called”);
Vector v = new Vector();
conn = getConnection();
pstmt = conn.prepareStatement(“select id from accounts where
ownerName= ?”);
pstmt.setString(1,name);
ResultSet rs = pstmt.executeQuery();
while (rs.next())
{

51
String id = rs.getString(“id”);
v.addElement(new AccountPK(id));
}
return v.elements();
}
catch(Exception e)
{
System.out.println(e);
}
}
public static final String JDBC_URL = “JDBC_URL”;
public Connection getConnection () throws SQLException
{
String jdbcurl = (String) env.get(JDBC_URL);
Return DriverManager.getConnection(jdbcurl,env);
}
}
AccountException.java
Our custom exception class is AccountException.java. it simply delegates to the parent
java.lang.Exception class.
package account;
public class AccountException extends Exception
{
public AccountException ()
{
super();
}
public AccountException (Exception e)
{
super(e.toString());
}
public AccountException (String s)
{
super(s);
}
}
Client.java
In client code we perform some bank account operations in the try block.
package account;

52
import javax.ejb.*;
public class Client
{
public static void main(String args[])
{
Account account = null;
Try
{
Context ctx = new InitialContext(System.getProperties());
AccountHome home = (AccountHome) ctx.lookup(“AccountHome”);
Home.create(“123-456-7890”,”john”);
//find an account
Enumeration e = home.findByOwnerName(“John”);
if(e != null)
{
account = (Account) e.nextElement();
}
else
{
throw new Exception(“could not found account”);
}
// call the balance
System.out.println(“Initial Balance = “ +
account.getBalance());
//Deposit 100 into the account
account.deposit(100);
System.out.println(“After depositing 100 the account balance is : ”
+ account.getBalance());
//Retrieve the primary key
AccountPK pk = (AccountPK) account.getPrimaryKey();
//release our old EJB Object reference. Now call find () again
//this time querying on AccountId (i.e. primary key).
account = null;
account = home.findByPrimaryKey(pk);
//find out current balance
System.out.println(“Found account with ID “ + pk + “. Balance =
“ + account.getBalance());
// try to withdraw 150
account.withdraw(150);
}
catch(Exception e)
{

53
System.out.println(e)
}
finally
{
//destroy the bean permanently
try
{
System.out.println(“Destroying the Account”);
if(account != null)
{
account.remove();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
The Deploument Descriptor (ejb-jar.xml)
<?xml version=”1.0"?>
<!DOCTYPE ejb-jar PUBLIC ‘-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 1.1//EN’ ‘http:/
/java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd’>
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>Account</ejb-name>
<home>account.AccountHome</home>
<remote>account.Account</remote>
<ejb-class>account.AccountBean</ejb-class>
<persistence-type>Bean</persistence-type>
<prim-key-class>account.AccountPK</prim-key-class>
<reentrant>False</reentrant>
<resource-ref>
<res-ref-name>jdbc/demoPool</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

54
</entity>
</enterprise-beans>
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>Account</ejb-name>
<method-intf>Remote</method-intf>
<method-name>*</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
Running the Client program
Type following command at DOS-prompt
J a v a – d j a v a . n a m i n g . f a c t o r y. i n i t i a l = w e b l o g i c . j n d i . Te n g a h I n i t i a l C o n t e x t F a c t o r y -
djava.naming.provider.url=t3://localhost:7001 account.Client

55
RMI
Remote Method Invocation (RMI) is a part of the J2EE. It allows us to develop distributed applications.
Distributed systems require computation that are running in different address space, practically on
different machines, must be able to communicate between one machine to another. Java RMI facilitates
such a communication specifically for java applications. The RMI platform is independent because
java is platform independent.
In RMI the application is divided into objects. The objects communicate with each other through interface.
This interface is used to access the remote object and its methods. RMI passes objects by their true
type, as a result the behavior of those objects is not changed when they are sent to another virtual
machine. To develop the distributed application using RMI we have to follow the following steps.
1. Define the Interfaces.
2. Implementing the Interfaces.
3. Compile the interfaces and their implementations with the java compiler.
4. Compile the server implementation with RMI compiler.
5. Run the RMI registry
6. Run the application.
Overview of RMI
RMI applications are developed as two separate programs: a server and a client. Server application
creates a number of remote objects, makes references to those remote objects. Client application gets
a remote reference to one or more remote objects in the server and then invokes method on them. RMI
provides the mechanism by which the server and the client communicate and pass information back
and forth.
RMI distributed application uses the registry to obtain references to remote object. The server creates
the objects, registers them in the local registry by the object name. The client looks up the remote
object by its name in the server’s registry and then invokes a method of the server object. The RMI
system also uses the existing web server to load java class byte codes (objects) from server to client
and from client to server, when needed.
RMI can load class byte codes using any Uniform Resource Locator protocol, supported by java system.
RMI architecture consists of four layers and each layer can perform specific function.
1. Application Layer: it has contained the actual object definition.
2. Proxy Layer: it consists of two parts namely stub and skeleton. These are used for marshaling
and unmarshaling the data that is transferred through the network. Marshaling is the process

56
by which we can convert the java byte codes into a stream of bytes, and unmarshaling is the
reverse process of it. Stub is a proxy of server and is placed on client side of the application,
whereas the skeleton is placed on the server side.
3. Remote Interface Layer: it gets the stream of bytes from the transport layer and sends it to
the proxy layer.
4. Transport Layer: this layer is responsible for handling the actual machine-to-machine
communication.
A p plication Layer A p plication Layer

C lient C lient

P roxy L ayer P roxy L ayer

S tub S tub

R em ote R eference R em ote R eference


L ayer L ayer

Tran sport L ayer

TCP
Tran sport L ayer

R M I L ayers
Application Layer
The application layer is the actual implementation of the client and server application. Here high-level
calls are made in order to access and export remote objects. The client can access the remote method
through an interface that extends java.rmi.Remote. when we want to define a set of methods that
will be remotely called, they must be declared in one or more interfaces that should extend
java.rmi.Remote.
Once the methods described in the remote interfaces have been implemented, the object must be
exported. This can be done implicitly if the object extends the UnicastRemoteObject class of
java.rmi.server package. Then the application will register itself with a naming server or registry.
The client to obtain a reference of objects uses this. On the client side, a client simply requests a
remote object from either a registry or remote object whose reference has already been obtained.
After getting th e reference the proxy layer has to perform the important role of communication between
the client and the server.

57
þ In coming application, the CalcClient and CalcServer from the Application layer.
Proxy Layer
The Proxy layer consists of the stub and the skeleton. stub and skeleton are created using RMI compiler
(rmic). These are simply class files that represent the client and the server side of remote object. The
stub is placed in the client side while the skeleton is placed in the server side. The following figure
illustrates this.
C lien t S erv er

C a lc C lien t C a lc S erv er

S tu b S k eleto n

J a v a Virtu al M a ch in e
a n d R M I S y stem

J a v a Virtu al M a ch in e
a n d R M I S y stem

P ro x y L a y er

The stub is a client side proxy of the remote object. It has three primary responsibilities.
1. It represents the same remote interfaces as the object CalcServer. Therefore, from the
perspective of the CalcClient, the stub is equivalent to the remote object.
2. It works with java virtual machine and RMI system on client machine to serialize any arguments
to remote method call and sends this information to server machine.
3. The stub receives any result from the remote method and returns it to the client.
The Skeleton is server side proxy of the remote object. It has three primary responsibilities.
1. It receives the remote method call and any associated arguments. It works with the JVM and
RMI system on the server machine to deserialize any arguments for this remote method call.
2. It invokes the appropriate method in the CalcServer.
3. It receives any return value from this method call and works with the JVM and RMI system on
server machine to serialize this return value and sends the information back to CalcClient.
Remote Reference Layer
The Remote reference layer is effective between stub and skeleton classes and the transport layer
handles the actual communication protocols. When transmitting the parameter or objects through the
network it should be in the form of a stream. The java virtual machine works on the byte codes. It can

58
get the stream-oriented data from the transport layer and give it to the proxy layer and vice-versa.
This layer is used to:
1. Handle the replicated objects. Once this feature is incorporated into the RMI system, the
replicated objects will allow simple dispatch to many programs that are exporting substantially
the same Remote objects
2. It is responsible for establishing persistence and strategies for recovery of lost connections.
The Transport Layer
The Transport layer’s responsibilities are:
1. It is responsible for handling the actual machine to machine communication, the default
communication will take place through a standard TCP/IP protocol
2. It creates a stream that is accessed by the remote interface layer to send and receive data to
and from other machine.
3. It sets up the connection to remote machine.
4. It manages the connections.
5. It monitors the connection to make sure that they are live.
6. It listens for connections from other machine.
Let us learn each of the steps involve in developing RMI program using a simple example:
Create on remote object that contains the one remote method sum (int, int) and returns the sum of two
numbers passed as arguments. Then call this remote method using client application. In this example:
CalcInt is the remote interface
CalcServer is the server or remote object
CalcClient is the client
Let us discuss each an every step.
Defining Interfaces
Defining interfaces is the first step to writing RMI Programs. In RMI programming, any class that
exports objects must implement an interface that defines the methods that can be accessed via a
remote application (i.e. client). The class may have methods that are not defined in the interface.
Each remote object is identified by its remote interface. The remote interface is an interface that
declares a set of methods that may be invoked from a remote java virtual machine. A client gets a
handle to the interface describing the remote method of an object. This interface must extends from
java.rmi.remote. the java.rmi.remote serves to identify all remote interfaces. All the remote objects
must directly or indirectly implement this interface. Only the remote interface can be invoked via RMI.
Local interfaces cannot be called in this manner.
To develop our remote interface write down following coding in CalcInt.java file
import java.rmi.*;
public interface CalcInt extends Remote
{
public int sum (int num1, int num2) throws RemoteException;
}

59
Here we have created one Remote interface named CalcInt having one remote method public int sum
(int num1, int num2)
þ A Remote exception must throws RemoteException. This exception is thrown by RMI
during a remote method call to indicate if either a communication failure or protocol
error occurs.
Implementation of interfaces now let us discuss the next step server and client implementations of
the interfaces.
Server Implementation the server implementation class of a remote interface should do the following.
1. Declare the remote interfaces being implemented
2. Define the constructor for the remote object
3. Provide an implementation for each remote method in the remote interfaces.
The server needs to create a remote object and register it with the local registry. This procedure can be
encapsulated in a main () method in the remote object implementation class.
Write following coding in CalcServer.java file
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class CalcServer extends UnicastRemoteObject implements CalcInt
{
// Creating constructor
public CalcServer () throws RemoteException
{
System.out.println (“Server started”);
}
// Provide implementation for each remote method. In our case sum ()
method
public int sum (int num1, int num2)
{
return (num1 + num2);
}
public static void main (String args[])
{
try
{
CalcServer CS = new CalcServer ();
Naming.rebind (“CalcServer”,CS);
System.out.println (“Server is Ready..”);
}catch(Exception e)
{
System.out.println(e);

60
}
}
}
In above program the main () method creates an object of the CalcServer class, registers it with the
registry using Naming.rebind () and then gives an output that the server is ready. The java.rmi.Naming
interface is used as a front-end API for binding, or registering, and looking up remote objects in the
registry. Once a remote object is registered with the RMI registry on the local machine, callers on any
machine can look up the remote object by name, obtain its reference, and then invoke remote methods
on the objects.
The following parameters are the arguments to call Naming.rebind () method.
1. An URL-formatted name associated with the remote object: it represents the location and the
name of the remote object. The location includes the name or IP address of the server. By
default it takes the local machine. We can also include the port number in URL. the default is
1009.
2. A new remote object to associate with the name. The RMI runtime substitutes a reference
to the stub for the remote object reference specified by the argument. Remote implementation
objects, such as instance of CalcServer, never leave the virtual machine where they are created.
So when a client performs a lookup in a server’s remote object registry, a reference to the stub
is returned.
Client Implementation
After writing the server implementation, we move onto the client implementation. Write the following
code in CalcClient.java
import java.rmi.*;
public class CalcClient
{
public static void main (String args[])
{
// Variable to store reference of remote interface
CalcInt ck;
int first,second,total;
// Looking up the reference of remote object.
try
{
ck = (CalcInt)Naming.lookup (“rmi://localhost/CalcServer”);
first = Integer.parseInt (args[0]);
second = Integer.parseInt (args[1]);
//Calling remote method
total = ck.sum(first, second);
System.out.println (“Sum is : “ + total);
}
catch(Exception e)

61
{
System.out.println (e);
}
}
}
In above Program Naming.lookup () is a static method that searches for the server using the server
name registered with the RMI registry. It takes in a single parameter of string type representing the
URL-formatted name for the remote object and return a reference (i.e. stub) for the remote object
associated with the specified name. If the name is not currently bound to the registry, then it throws the
NotBoundException. If the registry could not be contacted then the lookup method throws a
RemoteException. If the operation is not permitted then the lookup method throws the
AccessException.
Creating Stub and Skeleton. we have compiled all the java files using the javac command and hence
.class files for all the java files are available. We can create stub and skeleton class by using the
command rmic.
Rmic CalcServer
After this command is executed the stub and skeleton classes will be created in the current folder, with
the name: CalcServer_Stub.class and CalcServer_Skeleton.class.
RMI Registry
RMI registry is a simple server that enables an application to lookup objects that are exported for
remote method invocation. It is also called bootstrap registry. The registry simply keeps track of the
addresses of remote objects that are being exported by their application. In any distributed system all
the objects are assigned unique names that are used to identify the object.
How to register the object into the registry
In the RMI system, certain methods can be called from the rmi.registry.Registry interface, or from
the rmi.Naming class. In our application CalcServer.java we have registered the object using following
command:
CalcServer cs = new CalcServer (); // creates the object
Naming.rebind (“CalcServer”, cs); // registering the objects.
Running the Application following are the steps that we have to follow to run a RMI application.
1. Open an instance of MSDOS prompt.
2. Run the registry by giving the following command at the prompt: rmiregistry
3. Minimize the instance
4. Open another instance of MSDOS prompt set the appropriate CLASSPATH then run the server
by typing the command Java CalcServer
5. Minimize the screen and open another MSDOS Instance
6. Run the client by typing the command Java CalcClient
þ In The above program the client and the server both runs on the same machine. To run
client on different machine we have to make a single line change in client code as:

62
import java.rmi.*;
public class CalcClient
{
// Variable to store reference of remote interface
CalcInt ck;
int first,second,total;
public static void main (String args[])
{
// Looking up the reference of remote object.
try
{
ck = Naming.lookup (“rmi://Servername/CalcServer”); // this line has
to be changed to run client
//on different machine
first = Integer.parseInt (args[0]);
second = Integer.parseInt (args[1]);
//Calling remote method
total = ck.sum(first, second);
System.out.println (“Sum is : “ + total);
}
catch(Exception e)
{
System.out.println (e);
}
}
}
After that copy stub and skeleton classes on both machines: server as well as client. Then Step 5 and
6 perform on client machine.
Let us discuss one another example in which we create one RMI server having one method showRecord(int
mempno) which takes empno as argument and then display the whole record of that empno.
þ Rmiemp is the table in Oracle. RmiDsn is the Datasource
Following are the files that we have to create for our application
DataInt.java
This is our interface
import java.rmi.*;
public interface DataInt extends Remote
{
public String showRecord (int mempno) throws RemoteException;
}

63
DataServer.java
This file is our RMI server. It is our server side implementation of interface.
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
import java.sql.*;
public class DataServer extends UnicastRemoteObject implements DataInt
{
// Creating constructor
public DataServer () throws RemoteException
{
System.out.println (“Server started”);
}
// Provide implementation for each remote method. In our case shoRecord
() method
public String showRecord (int mempno)
{
String rec = “”;
try
{
Connection con = null;
ResultSet rs = null;
PreparedStatement psmt = null;
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
System.out.println(“Before...”);
con =
DriverManager.getConnection(“jdbc:odbc:RmiDsn”,”scott”,”tiger”);
System.out.println(“after...”);
psmt=con.prepareStatement(“select * from rmiemp where empno = ?”);
psmt.clearParameters();
psmt.setInt(1,mempno);
rs = psmt.executeQuery();
if(rs.next())
{
rec = rs.getString(“empno”)+” “+rs.getString(“ename”)+”
“+rs.getString(“hiredate”)+” “+rs.getString(“sal”);
}
else
{
rec = “Record not found”;
}
}

64
catch(Exception e)
{
System.out.println(e);
}
return rec;
}
public static void main (String args[])
{
try
{
DataServer DS = new DataServer ();
Naming.rebind (“DataServer”,DS);
System.out.println (“Server is Ready..”);
}catch(Exception e)
{
System.out.println(e);
}
}
}
Generating stub and skeletone
1. compile all the files
2. type following command at MS-DOS
3. rmic DataServer
Running the client
1. run Rmiregistry at one Instance of MS-DOS
2. at another MS-DOS instance run DataServer by typing following command
Java DataServer
3. open another MS-DOS instance then type the following command
Java DataClient 7369
þ you may pass other empno as command line argument

65
STUDY REFERENCE

ENTERPRISE JAVA BEANS

Prepared by

AZURE Technologies & Information Services Pvt. Ltd.


Ahmedabad
PREFACE
A few years ago, various fields were researched independently, they never assisted,
interfered or interacted with other researches. Thereafter a few more years down the
line came in the set of ‘INFORMATION TECHNOLOGY’ which altered the entire
globe. It plugged on all researches scientific and otherwise via the tool named
‘Internet’. Today we are using these computer aided tools to enhance and represent
our business and information in a more appealing and presentable manner. At the
gateway of the 21 st century, the tools and connectivity of digital age have given us
better ways to obtain, share and act on information in new and remarkable ways.

As a Director of Azure, my dream is to spread this Information technology


through the community to be successful and enterprising IT professionals leading
this industry to a brighter future by developing powerful tools for analysis and aptly
using the information provided by these solutions. I feel that the flow of Information
and knowledge always flow from father to son, like a child learn so many things from
family itself. So, when a father knows about IT he always insist that his son should
learn IT. This way only I think we can end this IT word in the each corner of the
world. This module will be just hit or help you to get acquire of this technology and
spared it through the community.

To achieve this objective we have succeeded to establish well equipped GLSIIT,


Gujarat Institute of Technology (GIT), Institute of Computer Technology (ICT), H. K.
Computer Centre, C. U. Shah Science College Computer Centre, H. A. College of
Commerce Computer Centre, City College Computer Centre, Jyoti Sangh Computer
Centre, Dharamsinh Desai Institute of Commerce Computer Centre (Nadiad), Shri N.
P. Patel Computer Science Centre (Kalol), Mohinaba Computer Centre, Ahmedabad
and are imparting training to more than 3500 students every year. Furthermore it
has been a matter of pride that we have successfully met the milestones on the road
to success to impart the best and latest technology to the students.

I highly appreciate the efforts put in by the staff members of our organization
who have jointly contributed to put together this module. In addition, I would also
like to thank our printers Moti Enterprise.

So, continue your strive to attain success with this module. All the best

Dushyant Joshi
Director
Contents
Server Side Component Architectures .............................................................. 1
The Need for a Server-Side Component Architecture ..................................................................... 1
Software Components.......................................................................................................................... 1
Component Architectures .................................................................................................................... 1
Component architectures in Java ........................................................................................................ 2
The needs of the Server Side .............................................................................................................. 3
Multi- tier - Architectures ................................................................................................................... 3
Two-tier architectures .......................................................................................................................... 4
Pushing some of the business logic layer into the data layer. .......................................................... 4
N-tier architectures .............................................................................................................................. 5
Server –Side Component Architecture solutions ............................................................................... 6
Enterprise Java beans (EJB) ............................................................................................................... 8
The contract between Six Parties ...................................................................................................... 8

Session Beans ......................................................................................................10


Composition Of Enterprise Bean Component .................................................................................. 10
The Enterprise Bean Class ................................................................................................................ 10
The EJB Object .................................................................................................................................. 10
The Remote Interface ....................................................................................................................... 11
The Home Object ............................................................................................................................... 12
The Home Interface .......................................................................................................................... 12
Deployment Descriptors .................................................................................................................... 13
Bean-Specific Properties ................................................................................................................... 13
Ejb-jar-File .......................................................................................................................................... 13
What is a Session Bean? ................................................................................................................... 13
Stateless Session Bean ...................................................................................................................... 14
Stateful Session Bean ........................................................................................................................ 14
All session Bean’s Methods are Serialized ...................................................................................... 14
Writing Session Beans ....................................................................................................................... 14
setSessionContext(SessionContext ctx) ........................................................................................... 15
ejbCreate(…) ..................................................................................................................................... 15
EjbPassivate () ................................................................................................................................... 16
ejbActivate() ....................................................................................................................................... 16
Business Methods .............................................................................................................................. 16
Calling Session Bean At Client Side ................................................................................................. 16
Looking Up Home Object .................................................................................................................. 17
Calling a Method ................................................................................................................................ 18
Destroying the EJB Object ................................................................................................................ 18

Stateless Session Bean ...................................................................................... 1 9


Writing a “Hello World” Stateless Session Bean ............................................................................ 19

Stateful Session Beans ...................................................................................... 3 1


A Simple Stateful Session Bean Example ........................................................................................ 32

Entity Bean .......................................................................................................... 3 7


What is an Entity Bean? .................................................................................................................... 37
Files Included With Entity Beans ...................................................................................................... 38
Features of Entity Beans ................................................................................................................... 38
Developing and Using Entity Bean ................................................................................................... 40
Creation of Entity Beans: ejbCreate () ............................................................................................. 41
Finding Existing Entity Beans: ejbFind () ......................................................................................... 41
Destruction of Entity Beans: ejbRemove () ..................................................................................... 42
Entity Contexts ................................................................................................................................... 42
getEjbObject () ................................................................................................................................... 43
getPrimaryKey () ............................................................................................................................... 43
Life Cycle of an Entity Bean ............................................................................................................ 43
Extra Study Material .......................................................................................................................... 44

RMI ....................................................................................................................... 5 6
Overview of RMI ............................................................................................................................... 56
Application Layer ............................................................................................................................... 57
Proxy Layer ........................................................................................................................................ 58
Remote Reference Layer .................................................................................................................. 58
The Transport Layer .......................................................................................................................... 59
Defining Interfaces ............................................................................................................................ 59

You might also like