You are on page 1of 89

Enterprise Java Beans

A Component Technology

EJB
1. Learning objectives
1. Component Technology characteristics
2. Standard Infrastructure needs
3. Application Servers
4. Containers
5. J2EE Architecture and its components
6. EJB Model, Overview & JNDI
7. EJB Specifications, Roles
8. EJB Design Approaches, Architecture A STAR or a
different color
9. Types of Beans represents
important
10. EJB Interfaces & Session Contexts points to NOTE

11. Life cycles of different Beans


12. EJB Jar files & Deployment Descriptor
13. Sample examples
14. Components comparison
4. Component Technology

Components are deployable units that provide a


business service to their clients.
• Each component provides an interface in the form of operations,
properties and events
• Components can be developed in any language such as JAVA,C++,VB
• Components are frequently organized into application frameworks for
vertical domains
• Component models such as Active X and EJB standardize
communication and allow for prebuilt purchased components
5. Component Characteristics
Components Characteristics include

 Properties  Reusability

 Operations  Shareable

 Events  Distributable

 Deployable  Self Containment

 Self description
6. Component P O E

Components should have a mechanism for exporting

 Properties

 Operations

 Events
7. Deployable Components

Components are operation independent of

• Hardware
• The underlying operating system
• Their Application Server
• The network protocol they use
8. Reusable Components

Component services can be used as a part of


business logic of other components
9. Shareable Components

If multiple clients are using a component


simultaneously, the component will provide
the same quality of service to all the clients
10. Distributable Components

Components should provide services to clients


running locally or remotely

Remote
EJB Container
CLIENTS
EJB

Local
CLIENTS Remote
Possible CLIENTS
Remote
CLIENTS

Remote
CLIENTS
11. SelfContained Components

Components should only contain the code


necessary to implement their services

Infrastructure services should be injected by


the execution environment
12. Standard Infrastructure Needs

Standard infrastructure services include

• Directory Services
• Distributed transaction management
• Security management
• Concurrent access management
• Persistence management
• Resource pooling (e.g. DB connections)
• Administration interface
• Load Balancing
• Fault tolerance
13. Applicatoin Servers

An application server provides the infrastructure and


services to run components/applications

Application Server products are mostly

Non-J2EE Microsoft Solutions


J2EE
solutions
based
(PHP, Cold Fusion, (COM, ASP.Net
solutions
Perl, etc.) VB.Net,C# etc.)
14. Object Pooling

An application server may create a pool of bare objects


that may be used as EJBs when requests are made

App Server
EJB Container
EJB
EJB
EJB

CLIENT
Pool
EJB EJB DB
Network
CLIENT EJB
15. Directory of Application Servers
Application Servers provide clients access to software or
other applications that run only on the server

Examples include web servers, e-mail servers and database servers

Popular Application Servers are:


• I.B.M. Web Sphere
• BEA Web Logic
• Sun Java System Application Server 7.x
• Jboss
The full list with vital statistics are available at
http://www.devx.com/enterprise/html/16268
http://www.javacommerce.com/articles/serverlist.htm
16. Container
Container means a Fish cannot survive outside water &
A Container : pre developed Software EJB’s cannot survive outside containers

• provides the environment in which a bean executes


• generates Home Object
• generates EJB Object Implicit Middleware

• gained through declaration


manages individual bean instances
To increase capability. &
clustering is taken care
by the vendor Container provides System services like
Transaction Persistence Security Connection Pooling Threading

App Server
EJB Container

EJB
EJB EJB
Container
Network intercepts
STUB
requests
CLIENT

Container knows what to do, as you describe everything in a special descriptor file
17. J2EE Overview
Deployment
Descriptors (DDs)

Web Server Independence


Enterprise Components
Application Server
Independence services standards component-based

Database Independence J2EE


Enterprise Resource Container/Server
Management Services
J2EE Interfaces Deploy
Tools
Distributed Communication Management Services
Services Deployment/Configuration
Common Programming J2SE Language/Interfaces
Services Data
J2SE Runtime
Operating System
Independence Operating System Platform
Hardware Independence
Hardware Platform
18. J2EE 1.4 APIs
J2EE defines a model for developing multi-tier, web based,
enterprise applications with distributed components

Applet RMI/
Web Container EJB Container
IIOP
Container HTTP/S
JSP Servlet EJB
Applet
JSP Servlet ENGINE
JAX- J J W J Java Mgmt J J JAX- J J W J Java Mgmt J J
J C J C
J2SE RPC A A E M Mail N D RPC A A E M Mail N D
T O T O
X C B S JMX A D N B X C B S D B
SAAJ JAF SAAJ JAF JMX A N
R C S I C R C S I C

Application Client J2SE J2SE


Container HTTP/S

3 TIER 4 TIER
Client

RMI/
EIS
JAX- J W Mgmt J IIOP
J C DAO
RPC A E D
M O
X B JMX B DB
SAAJ S N
R S C
J2SE 2 TIER
MainFrames

For all the APIs refer http://java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html


19. Enterprise JavaBeans Model
EJB is Sun’s J2EE transactional, vendor-neutral,
enterprise component architecture providing

• Modelling of business entities as well as synchronous and


asynchronous processes
• Persistence via explicit code (bean-managed) or via services of the EJB
server (container-managed)
• Vendor neutrality and inter operability
• XML driven deployment and configuration

EnterpriseJava Beans != Java Beans


EJBs need a Container JBs do not need a container
EJBs are deployable components JBs are development components
EJBs are assembled to form a complete Appl JBs are Classes with no argument constructor
EJBs are based on RMI IIOP and JNDI Technologies JBs have a get and a set method on them
20. EJB Overview
EJB simplified distributed development
–Develop EJB implementation logic
–Define Home/Local Remote/Local interfaces
–Container delegates client calls
–Container manages resources/lifecycle/callbacks

EJB Client
EJB Impl
LocalHome Local create timeout
Client Process create invoke remove passivate
remove find activate
find invoke load
Home store
STUB STUB
create
remove
EJB find
Client Remote Network
EJB
Delegate
Delegate
Delegate Pool
invoke Delegate
J2EE EJB Container/Server
21. When to use EJB

If any of these requirements hold for your application

• the application must be scalable and distributable


• Transactions will be required to ensure data integrity
• the application will have a variety of clients
22. Java Naming and
Directory Interface (JNDI)
JNDI
Provides a standardized way of accessing resources in a distributed
environment
Protocol and naming service agnostic
• DNS
• NDIS
• LDAP
• X.500
Implemented by the javax.naming package and three other packages
below it
javax.naming.InitialContext is the entry point to the EJB Server
• bind – associates a name with an object
• lookup – finds an object given the name
23. EJB Specification

The EJB specification defines interfaces between

• the EJB and its container


• the container and the application server
• the container and the client
24. EJB Roles

Service & Tool Provider


provides Server, Container and integrates with distributed facilities
EJB Provider Application Assembler
creates EJB components assembles apps from per-built EJB comp

Deployment Specialist
deploys apps and understands architecture issues

deploys system
supplies tools builds application

Application Assembler
Tools Provider Deployer System Administrator
maintains deployment

supplies Application Server


develops EJBs

EJB Provider Application Server Provider


25. EJB Design Approaches
EJB model is based on three basic design approaches for
building distributed component systems
Stateless server approach Session-oriented approach
Persistent Object approach Implementing one of these interfaces
indicates your JAVA class is an EJB.
The EJB specification provides these as
Stateless session Beans Message driven beans
Stateful session Beans Entity Beans

All EntityBeans All SessionBeans All MessageDrivenBeans


implements Interface implements Interface implements Interface

javax.ejb.EntityBean javax.ejb.SessionBean javax.ejb.MessageDrivenBean


extends extends extends

javax.ejb.EnterpriseBean interface
extends

It is only a marker Interface java.io.Serializable As all these are extending the


and there are no methods to two Interfaces hence they have
Implement.
Serialization is the reason the behavior of both the Interfaces.
EJB is distributable.
26. EJB Architecture
Naming Service such
2 Naming Transaction Persistence Server
Security
A
as LDAP
H SERVICES
Server B App Server
H JNDI
Initial Context 8 EJB Container
H Home Home Object
Interface (FACTORY) 10 EIS
1 3
4 5
H EJB
6 creates DB
(Business Logic Class)
Home
Obj
RMI/IIOP 9 MainFrames
Stub Remote EJB Object
Application 7 Interface (Wrapper) delegates request
Client EJB
Obj
Stub 11

we have written
Container implements/autogenerates code for the Interfaces
We will write only this Container manages TRANSACTIONS, PERSISTENCE, SECURITY & POOLING
27. EJB Flow Chart
Start C

invokes a business method


ask JNDI Server for the Home Object 1 6
thru Remote Stub

JNDI Server returns ref of Home Stub 2 goes to the JNDI Server
7 and gets the EJB Object

ask Home for the EJB Object 3


Remote Interface then wraps
8 a request to the Bean class
creates EJB Object 4

returns reference of Remote Stub Clients receives the required info


5 9

C End
28. Client View of EJB
ENTITY BEANS are like NOUNS as they represent data or data related logic.

App Server
EJB Container
EJB Home or e.g
EJB Local Home Session Bean •Bank teller
instance •Credit Card authorization

EJB Object or
EJB Local Object Entity Bean e.g
Application RMI/ instance •Bank account balance
Client IIOP
•Purchase order

JMS Destination Message Driven e.g


Bean instance •Stock trade messages
•Work flow messages

SESSION BEANS are like VERBS as they represent action or business process related logic.

MESSAGE DRIVEN BEANS have message oriented logic.

If all the processing is done in the same Application server then we use
EJB Local(Object & Home) interfaces. Using local interfaces are optional.
Local interfaces pass by REFERENCE and EJB (Object/Home) pass by VALUE.
Using local interfaces avoids stubs, skeletons, network and so it is faster.
29. EJB Client

EJB clients

utilizes the Java Naming and Directory Interface (JNDI) to look up


for the references to home interfaces

use home and remote EJB interfaces to utilize all EJB-based


functionality
30. EJB Home Interface

EJB home interfaces extends javax.ejb.EJBHome

EJB home interfaces provide operations for clients to


• create EJBs
• remove EJBs
• find handles to EJB remote interface objects
• have its stub placed into JNDI at startup
31. EJB Remote

EJB remote interfaces extends javax.ejb.EJBObject

EJB remote interfaces


• provide business-specific functionality of an EJB
• are similar to RMI Remote interface
32. EJB Implementation

EJB implementation

Class in which EJB developer codes the business methods


defined in the bean’s component interface(s) to provide any
application specific

• business method invocation


• creation
• removal
• finding
• activation
• passivation, database storage
• database loading logic
33. Session Context

The Container has already reference to the bean

The bean interacts with the Container through SessionContext and


• retrieves home interfaces
• gets and sets transactions attributes
• obtains security attribute

The setSessionContext method is used to inform the bean


about the session context
34. Stateless Session EJB
Stateless session EJBs have the following behaviour

• provide a single use service


• do not maintain state on behalf of the client
• are relatively short lived
• do not survive EJB server crashes
• any two instances of the same stateless session EJB
type are always identical
• each instance can be shared by multiple clients
35. Stateless Session EJBs View
EJB Client Stateless Session
LocalHome Local Logic
Client Process
Home
EJB input
Remote Network
Client EJB Pool output

J2EE EJB Container/Server


EJB Impl Developer View
EJB gets requests and generates responses
An instance can service multiple clients over time

EJB Client Developer View


creates it, uses it and then it’s done

EJB Container View


can pull instances from pool upon client request
can shrink/grow pool as needed
A few pooled beans can service thousands of clients
36. Life Cycle of Stateless Session Bean
Each method call is an
invocation from the
container to the Bean
Client called remove()
on the EJB object
(or the client times out)
Container decided it Bean Instance
needs more instances does not exiist
in the pool to service clients
Class.newInstance()

ejbRemove()
setSessionContext()

ejbCreate()

Pool of equivalent
method ready instances
Client called another
Transactional business method
on the EJB Object. Transactional
Business Method
37. Stateful Session EJBs View
Stateful Session
EJB Client
LocalHome Local Logic
Client Process
State
Home
EJB input
Remote Network
Client EJB Pool output

J2EE EJB Container/Server


EJB Impl Developer View
EJB gets requests and generates responses
An instance can service multiple clients over time

EJB Client Developer View


creates it, uses it and then it’s done

EJB Container View


can pull instances from pool upon client request
can shrink/grow pool as needed
38 .Life Cycle of Stateful Session Bean
Each method call is an
Invocation from the
container to the Bean
Client called remove()
on the EJB object
(or the client times out)
Bean Instance
Client called create(args) does not exiist
on the home Interface.

Class.newInstance() Container’s limit of


instantiated beans
are reached, so it must
ejbRemove() swap your bean out.
setSessionContext()
Client times out
Client called a
non-transactional business ejbCreate(args)
method on the EJBObject
Non-Transactional ejbPassivate()
Business Method Bean instance is ready
Bean instance is in
to service method calls
the passive state
Client called a transactional ejbActivate()
business method on the
EJB Object beforeCompletion() Client called a method
on a passivated bean, so
afterCompletion(true) afterCompletion(false) Container must swap your
afterBegin() Bean back in
If transaction ended
in a commit..
Bean instance is within
a transaction and ready We need to write all
to service method calls If transaction ended
the methods that
Client called another in an abort.
Transactional business method are there in the
on the EJB Object. Transactional Implemented class
Business Method

If we implement Javax.ejb.SessionSynchronization then we need to


write these methods.
39. Stateful vs Stateless
Stateful Bean Stateless Bean
A stateful bean contains a conversational state that is A stateless bean does not have any state between calls to
retained across method calls and transactions. its methods.

The create method takes arguments The create method does not take arguments
e.g. create(String id) , create(int I , String id) e.g create()
There can be one or more arguments in a create method There can be no arguments in a create method

e.g e.g
An EJB that unzips 100 bytes of data An EJB that books a flight and rents a car at a travel agent’s
An EJB that checks to see if a stock symbol is valid web site.

Method by method comparison can be seen in EJB20Matrix.doc at http://www.volantec.biz/cmp20.htm


40. Entity Bean

Entity Bean has the following behaviour

• They are a representation of persistent data


• They can survive a crash
• Multiple clients can be using EJBs that represent the
same data
• The EJB instance contains a copy of the data in the
persistent store
• has a Primary key like in a Database record.
41. BMP Entity EJBs
(BMP = Bean-Managed Persistence)

EJB Client Entity Bean (BMP)


LocalHome Local
Hand
Client Process Coded
Logic
Home
EJB
Remote Network EJB Pool input
Client
output
J2EE EJB Container/Server
Persisted objects (via hand-coding) data

EJB Impl Developer View


encapsulates data from a data source as objects
implements object-relational mapping (often JDBC)
implements inserts, deletes, queries and updates
EJB Client Developer View
creates, finds, updates and removes entity objects
EJB Container View
persists and manages concurrent access of instances
42. Primary key class

• Applicable only to entity beans


 Uniquely differentiates instances sharing the same
EJBHome
 Class must be a legal value type in RMI-IIOP
 Implements java.io.Serializable
 all the members should be public
 It should implement hashCode() and equals(.. ) methods
 does not implement java.rmi.remote
43. Shared Entity Bean

When multiple clients share an Entity EJB they


• receive their own instance
• share the underlying data
• do not have to handle synchronization

App Server

EJB Container
CLIENT
EJB DB
Network
CLIENT EJB
44. Life Cycle of BMP Entity Bean
Each method call is an
Invocation from the
container to the Bean

Container decided it
Container decided it Does not exiist doesn’t need the
needs another
Entity Bean instance
Entity Bean insinstance
anymore
newInstance() unsetEntityContext()

setEntityContext() JVM will garbage


collectt and call finalize()
Client called instance
independent ejbHome() Client called a finder
Business method Method on the home
interface
ejbHome() Pooled ejbFind()

Client called create() on


the home interface (this will
Create new database data) Activates the Bean Passivates the Bean Client called remove()
on the EJB object
(this will destroy
ejbCreate() ejbActivate() ejbStore()\ ejbRemove() Database data)
Container determined
that the database is out of
synch with the bean. The ejbPostCreate() ejbLoad() ejbPassivate()
Bean needs to load the
new Database data.
Container determined
Ready that the database is out of
ejbLoad() ejbStore() synch with the bean. The
Client called a business Bean needs to store its
method on a EJBObject Data into the Database
Business Method
45. CMP Entity EJBs
(CMP = Container-Managed Persistence)

EJB Client Entity Bean (CMP)


LocalHome Local
Client Process Generated
Logic
Home
EJB
Remote Network EJB Pool input
Client
output
J2EE EJB Container/Server
Persistence
Persisted objects (via container services) data DDs

EJB Impl Developer View


specifies CMP fields and relations among entities in DDs
specifies queries via EJB-QL in DDs
uses tools to map standard object view to specific relational view
EJB Client Developer View
creates, finds, updates and removes entity objects
EJB Container View
persists and manages concurrent access of instances
46. Life Cycle of CMP Entity Bean
Each method call is an
Invocation from the NOTE : BMP has no ejbSelect()
container to the Bean

Container decided it
Container decided it does not exiist doesn’t need the
needs another
Entity Bean instance
Entity Bean in
anymore
newInstance() unsetEntityContext()

Client called a finder


setEntityContext() JVM will garbage method on the home
collectt and call finalize() Interface, or bean
Client called instance
independent ejbHome() called its own
Business method ejbSelect()
method to locate
Database data
ejbHome() Pooled ejbFind() or ejbSelect()

Client called create() on


the home interface (this will
create new database data) Activates the Bean Passivates the Bean Client called remove()
on the EJB object
(this will destroy
ejbCreate() ejbActivate() ejbStore()\ ejbRemove() Database data)
Container determined
that the database is out of
Synch with the bean. The ejbPostCreate() ejbLoad() ejbPassivate()
Bean needs to load the
new Database data.
Container determined
Ready that the database is out of
ejbLoad() ejbStore() Synch with the bean. The
Client called a business Bean needs to store its
method on a EJBObject Data into the Database
Business Method
Or ejbSelect()
47. BMP vs CMP

Bean Managed Persistance Container Managed Persistance


BMP offers a tactical approach CMP is more strategic

The developer takes care of handling persistence Vendor takes care of everything by using O-R or OODB
mappings using metadata.

BMP uses hard coded queries so we can optimize our A developer cannot optimize performance as the vedor
queries takes care of it
We should start developing CMP beans, unless we require some kind of special bean, like multi-tables, that
cannot be completely realized with a single bean. Then when we realize that we need something more or that
we prefer handling the persistence (performance issue are the most common reason), we can change the bean
from a CMP to a BMP

Method by method comparison can be seen in EJB20Matrix.doc at http://www.volantec.biz/cmp20.htm


48. Message Driven Bean

MDB has the following behaviour


• Is stateless
• is a JMS listener
• when a JMS message arrives the method
onMessage() is executed
• does not survive EJB server crashes
• provides a single-use service
• is relatively short lived
• is only a bean class – no interfaces
49. Message Driven EJBs
Messaging Message-Driven Bean
Message
Service Queue Handler Logic
Producer Process

Messaging Message Network Message input


Message Message
Producer API Listener EJB Pool
J2EE EJB Container/Server

Asynchronous messaging

EJB Impl Developer View


gets async requests via messaging paradigm-specific interface
An instance can service multiple clients over time
EJB Client Developer View
Messages sent to endpoint & handled by messaging service
Specific to particular messaging paradigm used
EJB Container View
pulls instance from pool and delivers message
50. Life Cycle of Message Driven Bean
Each method call is an
Invocation from the
container to the Bean

Container decided it
needs another Does not exiist
Message DrivenBean
Instance
newInstance()
ejbRemove()
setMessageDrivenContext()

ejbCreate()

Pooled

onMessage()
51. Deployment

Deployment involves taking an EJB compliant bean and

• creates XML that describes the EJB


• packages the bean and XML into a Jar
• generates container files for the EJB
• configures properties of the EJB Server

Declaring without programming helps the application assembler to change the XML file easily.

BEAN Provider declares components’ middleware service requirements in a DEPLOYMENT DESCRIPTOR File.
Bean Provider describes how the Container should perform the LifeCycle Management, Persistence, Transaction and Security.
52. Other interfaces and classes
 Local interfaces are used for access within server context
 javax.ejb.EJBLocalHome E.g.:
•Inter component calls
 javax.ejb.EJBLocalObject •Servlet invocation

 Interfaces for serializing EJB references


 HomeHandle - reference to EJBHome
 Handle - reference to EJBObject

 EJBMetaData interface provides mechanism to gather


information about the bean
 reference to EJBHome object
 Home, component interface and primary key classes
 functions to determine bean type
53. Exceptions

 System exceptions are unchecked and propagated to the


client as java.rmi.RemoteException
 Application exceptions are checked and propagated to the
client as a descendant of java.lang.Exception
 EJB-specific exceptions include FinderException,
CreateException, RemoteException (all in javax.ejb
package)
 Business method exceptions are at the discretion of the
EJB developer
EXAMPLE 1
STATELESS BEAN
54. Steps to Develop an EJB
C
Start

Configure your EJB Server.


Write .java files for the BEAN, HOME 1 E.g DB connections thread pooling etc
and REMOTE interfaces Then copy the EJB Jar file
5

2
Write the Deployment descriptor Start your EJB container and
6 confirm that it has loaded
the EJB Jar file.
Compile all the STEP 1 files into 3
.class files
Connect to your EJB by writing a test
7 Client .java file compile it and run it .
Using the Jar utility create an EJB Jar
file containing STEP 2 & STEP 3 files 4
End
C

Please download the trial Application Server software from the links provided on the Reference slide at the end.
55. Hello World Object Model using RMI
We will apply the previous slide flow chart procedure to make up our first EJB
example

These Interfaces comes with Java 2 Platform


java.rmi.Remote java.io.Serializable

These Interfaces comes with EJB distribution


Javax.ejb.EnterpriseBean
Javax.ejb.EJBObject Javax.ejb.EJBHome
Javax.ejb.SessonBean

Supplied by the Bean Provider / Developer/ We will write !


Hello World Bean
Hello world Remote Interface Hello World Home Interface Implementation Class
We need to CODE only this block

Generated for us by the Container verdor’s tools NOTE : Object implementation


is Vendor specific. The container
may implement either
Hello world EJB Object Hello World Home Object A single object for each client or
A single object for all the clients.
56. Hello World Object Model using LOCAL
If all the processing is done in the same Application server then we use EJB Local (Object & Home) interfaces.
Using local interfaces are optional. Local interfaces pass by REFERENCE and EJB (Object/Home) which is the
previous slide model you saw will pass by VALUE. As these interfaces does not extend Java.rmi.Remote the
overhead of creating stubs, skeletons,network traffic is avoided and so it is faster but the drawback is if our
code relies on Local interfaces then we cannot call a bean remotely.

No Network so These Interfaces comes with Java 2 Platform


LOCAL IMROVES java.rmi.Remote java.io.Serializable
PERFORMANCE

These Interfaces comes with EJB distribution


Javax.ejb.EnterpriseBean
Javax.ejb.EJBLocalObject Javax.ejb.EJBLocalHome
Javax.ejb.SessonBean

Supplied by the Bean Provider / Developer/ We will write !


Hello World Bean
Hello world LocalInterface Hello World Local Home Interface Implementation Class
We need to CODE only this block
Generated for us by the Container verdor’s tools NOTE : Object implementation
is Vendor specific. The container
may implement either
Hello world EJB LocalObject Hello World Local Home Object A single object for each client or
A single object for all the clients.
57. HelloBean Home Interface
EJB Example requirement :
When the client interacts with the EJB we need to return a “Hello World” greeting.
To provide an EJB with the above requirement we have to create Remote & Home
Interfaces , Bean Business logic class and a deployment descriptor. For clarity please
see the previous slide Hello World Object Model using RMI.
This is the Home Interface for the Home EJB (HelloBean).

package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon

import java.io.Serializable;
import java.rmi.RemoteException; Importing the required files

import javax.ejb.CreateException;
import javax.ejb.EJBHome;
public interface HelloHome extends javax.ejb.EJBHome
Our interface HelloHome is extending EJBHome means it has all the behaviour of EJBHome
{
Hello create() throws java.rmi.RemoteException,
javax.ejb.CreateException; Interface methods should end with a semicolon ;
This method creates/manufactures the EJBObject and returns it . This create() method corresponds to the
ejbCreate() method in HelloBean.
As for every Interface we need implementation,Note
so Container will implement
In Home Interface we are(autogenerate code) forRemote
throwing 2 exceptions this Home
andInterface
Create . for us, which is the EJBHome Object
}
NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.
58. HelloLocalHome Interface
So now lets code the HelloLocalHome Interface

This is the LocalHome Interface for the Home EJB (HelloBean).

package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon
import javax.ejb.EJBLocalHome;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import java.util.Collection;
Our interface HelloLocalHome is extending EJBLocalHome means it has all the behaviour of EJBLocalHome

public interface HelloLocalHome extends javax.ejb.EJBLocalHome


{
HelloLocal create() throws javax.ejb.CreateException;
This methodso
As for every Interface we need implementation, creates/manufactures the EJBLocal
Container will implement Objectcode)
(autogenerate and returns
for this itmethods
Interface . This
Local create()
Home for method
should endwhich
us, corresponds
with isa the to the
semicolon
LocalHome ; Object
ejbCreate() method in HelloBean.
NOTE : RulesNote
of In LocalHome
Interfaces Interface
states we are
that there throwing
should be only Create and not Remote
no implementation so you exception
will find as
onlythere is no network
method signatures.
}
59. HelloBean Remote Interface

So lets code the Remote Interface

Clients interact with the EJB Object through this Remote interface that is why we need to write this interface.

package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon
import java.util.*;
import javax.ejb.EJBObject; Importing the required files

import java.rmi.RemoteException;
public interface Hello extends javax.ejb.EJBObject
{ Our interface Hello is extending EJBObject means it has all the behaviour of EJBObject

public String hello() throws java.rmi.RemoteException;


} As our requirement wants a business logic to greet Hello World a single method would be sufficient .
Interface methods should end with a semicolon ;
As Remote interface is used to interact with the Bean we need to mirror all the method signatures what
are there in a Bean class so that is why we are writing only one method in this Remote interface.
Note EJB specification states that all remote calls should throw RemoteException so we are throwing it.
As for every Interface we need implementation, so Container will implement (autogenerate code) for this Remote Interface for us, which is the EJBObject
NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.
60. HelloLocal Interface

Clients interact with the EJB Object through this Local interface when there is no network involved..

package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon
import javax.ejb.EJBLocalObject;
public interface HelloLocal extends javax.ejb.EJBLocalObject
Our interface Hello is extending EJBLocalObject means it has all the behaviour of EJBLocalObject
{
public String hello() ; Interface methods should end with a semicolon ;
As our requirement wants a business logic to greet Hello World a single method would be sufficient .
} As Local interface is used to interact with the Bean we need to mirror all the method signatures what
are there in a Bean class so that is why we are writing only one method in this Local interface.
Note As there is no remote calls no Remote Exception is thrown

As for every Interface we need implementation, so Container will implement (autogenerate code) for this Local Interface for us, which is the EJB Local Object

NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.
61. The Bean Class
So now lets code the actual EJB Class

This is where we will code our Business logic

package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon
import java.util.*;
Importing the required files
import javax.ejb.*;
public class HelloBean implements javax.ejb.SessionBean
NOTE : Note
If it is: Entity
this isBean
a class
weand
will not
implement
an Interface
javax.ejb.EntityBean
like the other two
and
(Home
if it is /Message
Remote).driven
This isbean
implementing
we will implement
SessionBean
javax.ejb.MessagedrivenBean
so it is a Session Bean
{ As per the below note in red we need to write all the methods what are in javax.ejb.SessionBean .

private SessionContext This ctx;


ejbCreate() corresponds to the Homeobject Create(). NOTE : in Stateless Bean no arguments are sent
public void ejbCreate() { System.out.println(“ejbCreate()”); }
public void ejbRemove() { System.out.println(“ejbRemove()”);} There is nothing
These much to clean up.
are called
Management or
public void ejbActivate() { System.out.println(“ejbActivate()”);} In Statelss Bean ejbActivate
Call back methods
and ejbPassivate Do not apply
public void ejbPassivate() { System.out.println(“ejbPassivate()”); }
public void setSessionContext(javax.ejb.SessionContext ctx) {
Storing the Context in a variable so that it can be queried later .
this.ctx = ctx; } NOTE : Because it is a Session Bean we are using setSessionContext for Entity Bean we
use setEntityContext and for Message Driven Bean we use setMessageDrivenContext.
public String hello() { System.out.println(“Hello()”);
return “Hello World! “ ; }
Our Business method which matches
} our Remote Interface method signature Java does not support multiple inheritance so you can extend only one class. To overcome
this they had given us the Implementation option . So when we use implement we need to
implement or write all the methods what are there in the interface we implemented.
62. The Deployment descriptor
THERE ARE MANY
TOOLS WHICH
CREATES THE
So now lets complete our EJB by writing the deployment descriptor. DESCRIPTOR
FOR US

As a Bean provider we need to specify the Middleware needs through this descriptor.

<!DOCTYPE ejb-jar PUBLIC “-//Sun Microsystems, Inc. // DTD Enterprise JavaBeans 2.0 //
EN “ “ http://java.sun.com.dtd/ejb-jar_2_0.dtd”> XML Standard requirement
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name> Hello </ejb-name> The nickname for this particular Bean
<home>examples.HelloHome</home> The fully qualified name of the Home Interface
<remote>examples.Hello</remote> The fully qualified name of the Remote Interface
<local-home>examples.HelloLocalHome</local-home>
The fully qualified name of the Local HomeInterface
<local>examples.HelloLocal</local> The fully qualified name of the Local Interface
<ejb-class>examples.HelloBean</ejb-class> The fully qualified name of the EJB Class
<session-type>Stateless</session-type> Whether the session bean is stateful or stateless
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
63. The Client
So now lets code our Client to access our simple stateless session bean.

package examples; Rules of Java says package declaration should be at the beginning and ends with a semi colon
import javax.naming.Context;
import javax.naming.InitialContext; importing the necessary files

import java.util.Properties;
public class HelloClient { As there is static key word this main method executes first before any other method in that class

public static void main(String [] args) throws Exception{


Properties props = System.getProperties(); Assigning props variable with properties information for JNDI initialization
Context ctx = new InitialContext(props); Obtaining the JNDI initial context is the starting point for connection to a JNDI tree
By passing environment properties we will choose our JNDI driver,network
Object obj = ctx.lookup(“HelloHome”); Get a reference
location to the Home
of the server etc. Object- the factory for Hello EJB Objects.

HelloHome home = (HelloHome) javax.rmi.PortableRemoteObject.narrow(


obj, HelloHome.class);
Use the factory to create the Hello EJB Object. We are then calling the hello() method
Hello hello = home.create(); We are casting HelloHome here, as Home Objects are RMI-IIOP objects and so we
On the EJB Object. The EJB object will delegate the call to the Bean,receive the
Need to use a special RMI-IIOP cast.
Results and return it to us . We then print it on the screen.
System.out.println(hello.hello());
hello.remove();}} Once we are done with the EJB Object, we can remove it.

NOTE : To call Local Interface you need not cast with the PortableRemoteObject. So the
block in red will be changed to
Object obj = ctx.lookup(“java:comp/env/HelloLocalHome”); ( to get a ref to LocalHome Object)
HelloLocalHome home = (HelloLocalHome)obj;
64. EJB Jar File
The folder structure within the Ejb-jar file is
META-INF/MANIFEST.MF
META-INF/ejb-jar.xml
examples/HelloBean.class
examples/HelloLocalHome.class
examples/HelloLocal.class
examples/Hello.class

Properties Remote/Local
File Interface

HomeLocalHome Enterprise Jar


Interface Bean Class Jar Creator file

Deployment Jar
Descriptor Manifest

DEPLOYED

Or manually run C:\>Jar cf HelloWorld.jar *

Jar file is a .ZIP compression format . META-MF file is a listing file automatically created by the Jar utility.

Please read the Deployment instructions provided by the Application server as it is Vendor specific
65. EJB Application Assembler

Deployment
.JAR .WAR
Jar Descriptor
file

Deployment
Tool
JAR ARC HIEVE (.jar)
WEB ARCHIEVE (.war)
EJB-JAR.XML
REMOTE WEB.XML
HOME Enterprise Archive HTML
EJB JSP
(.EAR Files) Servlets
(Application.XML)
EXAMPLE 2
STATEFUL BEAN
66. Stateful Session Remote Interface
package declaration should be in the beginning
package samples.ejb.stateful.simple.ejb;

import java.util.*;
import javax.ejb.EJBObject; Importing the required classes
import java.rmi.RemoteException;
import samples.ejb.stateful.simple.tools.BookException;
Remote Cart is extending EJBObject means Cart has all the behaviour of it
public interface Cart extends EJBObject Our bean class CartBean methods are mirrored here
{

public void addBook(String title) throws RemoteException;

public void removeBook(String title) throws BookException, RemoteException;

public Vector getContents() throws RemoteException;


}
EJB spec says all remote interface methods need to throw remote exception

There will not be any implementation in Interfaces


67. Stateful Session Home Interface

package declaration should be in the beginning


package samples.ejb.stateful.simple.ejb;

import java.io.Serializable;
import java.rmi.RemoteException;
Importing the required classes
import javax.ejb.CreateException;
import javax.ejb.EJBHome;

CartHome is extending EJBHome means CartHome has all the behaviour of it


public interface CartHome extends EJBHome {

In a Stateful Bean you can have more than one create method taking arguments
Cart create(String person) throws RemoteException, CreateException;

In our bean class CartBean these represent


ejbCreate(String person) & ejbCreate(String person, String id)

Cart create(String person, String id) throws RemoteException,


CreateException;
} EJB spec says all Home interface methods need to throw remote & create exceptions
There will not be any implementation in Interfaces
68. Stateful Session Bean Class

package samples.ejb.stateful.simple.ejb; package declaration should be in the beginning

import java.util.*;
import javax.ejb.*;
import samples.ejb.stateful.simple.tools.BookException; Importing the required classes
import samples.ejb.stateful.simple.tools.IdVerifier;

public class CartBean implements SessionBean {


CartBean Class is implementing sessionbean means this bean class is a session bean
String customerName;
String customerId;
We definedThis
thisalso
method in the Cart
the remote
Vector contents; interface. person) method
represents Home create(String
public void ejbCreate(String person) throws CreateException {
if (person == null) {
throw new CreateException("Null person not allowed.");
} else {
customerName = person;
}

customerId = "0";
contents = new Vector(); as this is the Bean class we will implement the business logic here
}

NOTE : AS we are implementing and not extending we need to write all the methods that are there in the Sessionbean
69. Stateful Session Bean Class
public void ejbCreate(String person, String id) throws CreateException {
Werepresents
if (person == null) { This also defined this
themethod
Home in the Cart remote
create(String interface
person, String id) method we defined
throw new CreateException("Null person not allowed.");
} else {
customerName = person;
}
The new operator is instantiating the instance of a class
IdVerifier idChecker = new IdVerifier();
if (idChecker.validate(id)) {
customerId = id; We are calling the validate(id) method from the class ID Verifier
} else {
throw new CreateException("Invalid id: " + id);
}
// This block is a supporting business method written in idVerifier class

contents = new Vector();


}
We defined this method in the Cart remote interface
public void addBook(String title) {
contents.addElement(title);
}
We defined this method in the Cart remote interface
public void removeBook(String title) throws BookException {
boolean result = contents.removeElement(title);
if (result == false) { We defined contents as a vector
throw new BookException(title + " not in cart.");
}
}
70. Stateful Session Bean Class
We defined this method in the Cart remote interface
public Vector getContents() {
return contents;
}

public CartBean() {} Bean class constructor

public void ejbRemove() {} We need to write these methods as we are implementing SessionBean

public void ejbActivate() {}

public void ejbPassivate() {}

public void setSessionContext(SessionContext sc) {}

Rules of implement states we need to implement all methods that are there in the implemented interface
71. Stateful Deployment Descriptor
THERE ARE MANY
TOOLS WHICH
<?xml version="1.0" encoding="UTF-8"?> CREATES THE
<!-- DESCRIPTOR
Copyright 2004 Sun Microsystems, Inc. All rights reserved. FOR US
SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
-->
<ejb-jar version="2.1" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd">
<display-name>CartJAR</display-name>
<enterprise-beans>
required by any XML document
<session>
<display-name>CartEJB</display-name>
The nickname for this particular Bean
<ejb-name>CartEJB</ejb-name>
<home>samples.ejb.stateful.simple.ejb.CartHome</home> The fully qualified name of the Home Interface
<remote>samples.ejb.stateful.simple.ejb.Cart</remote> The fully qualified name of the Remote Interface
<ejb-class>samples.ejb.stateful.simple.ejb.CartBean</ejb-class> The fully qualified name of the EJB Class
<session-type>Stateful</session-type>
Bean type is mentioned here
<transaction-type>Container</transaction-type>
<security-identity>
<use-caller-identity/>
</security-identity>
</session> Closing session and ejb
</enterprise-beans>
72. Stateful Deployment Descriptor
<assembly-descriptor>
<container-transaction>
<method>
<ejb-name>CartEJB</ejb-name>
<method-intf>Remote</method-intf> Passing Bean class methods and parameter info
<method-name>getContents</method-name>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
<container-transaction>
<method>
<ejb-name>CartEJB</ejb-name>
<method-intf>Remote</method-intf>
<method-name>removeBook</method-name> Passing Bean class methods and parameter info
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</method>
<trans-attribute>NotSupported</trans-attribute>
</container-transaction>
73. Stateful Deployment Descriptor
<container-transaction>
<method>
<ejb-name>CartEJB</ejb-name>
<method-intf>Remote</method-intf>
<method-name>addBook</method-name> Passing Bean class methods and parameter info
<method-params>
<method-param>java.lang.String</method-param>
</method-params>
</method>
<trans-attribute>Required</trans-attribute>
</container-transaction>
</assembly-descriptor>
</ejb-jar>
74. Stateful Session Client
package samples.ejb.stateful.simple.ejb;
package declaration should be in the beginning
import java.util.*;
import javax.naming.Context;
Importing the required classes
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

public class CartClient { Client class

public static void main(String[] args) {


As static is there this main method will execute first
try {
Context initial = new InitialContext(); The new operator is instantiating the instance of a class
Object objref = initial.lookup("java:comp/env/ejb/SimpleCart");
Looking into JNDI
CartHome home =
(CartHome)PortableRemoteObject.narrow(objref,
CartHome.class); Casting with a suitable RMI IIOP object

Cart shoppingCart = home.create("Duke DeEarl","123"); Creating the object


shoppingCart.addBook("The Martian Chronicles");
shoppingCart.addBook("2001 A Space Odyssey"); adding books to the object
shoppingCart.addBook("The Left Hand of Darkness");

Vector bookList = new Vector();


bookList = shoppingCart.getContents(); Invoking the bean class method through remote interface Cart
75. Stateful Session Client
Enumeration enumer = bookList.elements();
We defined booklist as a vector
while (enumer.hasMoreElements()) {
String title = (String) enumer.nextElement();
After storing in the variable “title” we are printing it
System.out.println(title);
}

shoppingCart.removeBook("Alice in Wonderland");
shoppingCart.remove(); Removing a particular book using the bean class method removeBook through
remote interface Cart –as we defined it this way
System.exit(0); Cart shoppingCart = home.create("Duke DeEarl","123");

} catch (BookException ex) {


System.err.println("Caught a BookException: " + ex.getMessage());
System.exit(0); We had written a new class BookException and using its method to catch any errors
} catch (Exception ex) {
System.err.println("Caught an unexpected exception!");
ex.printStackTrace();
System.exit(1);
}
}
}
76. Book Exception
package samples.ejb.stateful.simple.tools;

public class BookException extends Exception {

/**
* Default constructor.
*/
public BookException() {
}

/**
* Constructor with a <code>String<code> as a parameter.
* @param msg message, describing the exception.
*/
public BookException(String msg) {
super(msg);
}
}
77. ID Verifier

package samples.ejb.stateful.simple.tools;

public class IdVerifier {

/**
* Default constructor.
*/
public IdVerifier() {
}

public boolean validate(String id) {


boolean result = true;
for (int i = 0; i < id.length(); i++) {
if (Character.isDigit(id.charAt(i)) == false)
result = false;
}
return result;
}
}
ALL EXAMPLES
CAN BE SEEN AT
http://www.weblogic.com/docs/examples/ejb/Package-examples.ejb.html
http://my.execpc.com/~gopalan/java/entity.html
http://java.sun.com/developer/onlineTraining/Beans/EJBTutorial/
http://developers.sun.com/prodtech/javatools/jsstandard/reference/techart/entitybeans.html
78. Component Comparison
Component Distributability
EJB
Can implement the Remote or Local Interface

ActiveX
Uses Microsoft’s architecture for determining how clients’
invocation requests are sent to components. DCOM used as
underlying transport mechanism

CORBA
ORB makes use of GIOP and other protocols to perform IPC
79. Component Comparison
Components provide interfaces in the form of Operations

EJB
exports operations through Remote Interface

ActiveX
exports operations in the same interface

CORBA
exports methods through Interface Repository
80. Component Comparison
Self – Container Components
EJB
Containers inject code to handle transactions, database management,
security, distributability and other customisable services. Containers
can be provided independent of App Server and EJB providers

ActiveX
Transactions, database management, legacy integration have to be coded
into the logic of the component. Security policy can be inherited from
NTLM. Transactions can be aided through MTS

CORBA
CORBAServices have different APIs. CORBAServices can be complicated
to code with. CORBAServices are not supported by all ORBs
81. Component Comparison
Components provide interfaces in the form of Properties.

EJB
Properties are not explicitly exported but can be
mimicked through accessor operations

ActiveX
exports Properties in the same interface

CORBA
Properties not explicitly exported but can be
mimicked through attributes
82. Component Comparison
Components provide interfaces in the form of Events.

EJB
Events supported through JMS with Message
Driven Bean

ActiveX
exports Events in the same interface

CORBA
Events supported through Event Service but cannot
be exported
83. Component Comparison
Component Reusability

EJB
Incorporating the contents of an EJB can be done
in two ways:
• by having the new EJB use the services of an old
EJB as a direct client
or
• by writing an EJB class that inherits from an
existing one

These two methods of leveragability give developers


maximum flexibility
84. Component Comparison
Component Reusability

Active X
Incorporating the contents of an ActiveX can be done
in two ways:

• by having the new ActiveX use the services of an


old ActiveX as a client
or
• by Delegation

The Components being reused must be registered on


the development machine
85. Component Comparison
Component Reusability

CORBA
Every CORBA object has to have its own interface
definition

CORBA objects can use the services of other Objects

No mechanism for inheritance or Object reuse


inherently supported, though
86. Component Comparison
Components Shareability
EJB
Application Server makes multiple instances of EJB Objects. Client
contexts can be stored in different thread contexts. Different types
of EJBs identify levels of shareability.

ActiveX
uses Microsoft's in–process/out-of-process architecture for sharing
multiple ActiveX components and Client components.

CORBA
ORB makes multiple instances of CORBA objects. Clients’ contexts are
managed by ORB but can behave differently based upon vendor’s
Implementation.

You might also like