A Practical Introduction to Enterprise Java Beans
A Component Technology
IN 30 MINs
DO YOU WANT TO ANSWER MOST OF THE EJB QUESTIONS ?
THEN LET ME HELP YOU!
EJB
The Heart of J2EE BY
Kantimahanti Prasad
[Link]@[Link] or Kanti1@[Link]
Copyright 2004 Kanti Prasad All rights reserved
1. Learning objectives
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. Component Technology characteristics Standard Infrastructure needs Application Servers Containers J2EE Architecture and its components EJB Model, Overview & JNDI EJB Specifications, Roles EJB Design Approaches, Architecture Types of Beans EJB Interfaces & Session Contexts Life cycles of different Beans EJB Jar files & Deployment Descriptor Sample examples Components comparison
A STAR or a different color represents important points to NOTE
Copyright 2004 Kanti Prasad All rights reserved
2. About the Author
[Link]
Worked in fortune 100 Corporates in Client Server Technologies. Specializes in Architecture, Designing, Development & Managing day-to-day activities. Presently doing a PhD at Queens Uty, U.K in Adaptable Software specific to Component Technologies and has a M.B.A (Computer Applications) from an U.S. Uty. Business domain strengths are in Investment banking & Insurance.
U NEVER FAIL TILL U QUIT
Process improvement strengths are in 6 - Sigma and CMM.
His present & past working experiences in various global locations are in corporates like Pramerica (Prudential U.S), J P Morgan Chase, A B N Amro Bank & SGS. He was a part time visiting faculty in affiliates of Sydney University, Australia and All India Management Institute teaching I.T, Project Management & Statistics. He has given some presentations on Project Management and TQM at various venues. He has won few Talent/STAR performance awards and plays almost all the sports what are under the Sun. He hails from Vizag/ Hyderabad India. His 3rd party tested Temperament Sorter results are below
[Link] [Link]
If you liked his presentation, tell others and if you have a comment, tell him. He can be reached at [Link]@[Link] or Kanti1@[Link]
3. Thank you note
He wishes to thank Paul Perrone , Paulo Merson & Ramesh Behra for making this tutorial look the way it does. He wishes to thank to Katherine Ballantyne, Choi Kwan who volunteers to edit all of his Articles & Presentations. He wishes to thank Joerg Mueller, Muruganandam, CharlesJohnson & Venu Gadium who had volunteered to do the editing of this presentation. Special thanks to all his Managers at Pramerica and Purdential U.S.
Thank you for downloading my Presentation
ARUNA
SUNAYANA
SADHGI
his Parents
[Link] & Family
his Brothers his Sisters & his Cousins
DEDICATED TO
Copyright 2004 Kanti Prasad All rights reserved
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
Copyright 2004 Kanti Prasad All rights reserved
5. Component Characteristics
Components Characteristics include
Properties Operations Events Deployable Self description Reusability Shareable Distributable Self Containment
Copyright 2004 Kanti Prasad All rights reserved
6. Component P O E
Components should have a mechanism for exporting
Properties
Operations Events
Copyright 2004 Kanti Prasad All rights reserved
7. Deployable Components
Components are operation independent of
Hardware The underlying operating system Their Application Server The network protocol they use
Copyright 2004 Kanti Prasad All rights reserved
8. Reusable Components
Component services can be used as a part of business logic of other components
Copyright 2004 Kanti Prasad All rights reserved
9. Shareable Components
If multiple clients are using a component simultaneously, the component will provide the same quality of service to all the clients
Copyright 2004 Kanti Prasad All rights reserved
10. Distributable Components
Components should provide services to clients running locally or remotely
Remote CLIENTS
EJB Container EJB
Local CLIENTS Possible Remote CLIENTS
Remote CLIENTS
Remote CLIENTS
Copyright 2004 Kanti Prasad All rights reserved
11. SelfContained Components
Components should only contain the code necessary to implement their services Infrastructure services should be injected by the execution environment
Copyright 2004 Kanti Prasad All rights reserved
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
Copyright 2004 Kanti Prasad All rights reserved
13. Applicatoin Servers
An application server provides the infrastructure and services to run components/applications Application Server products are mostly
J2EE based solutions
Non-J2EE solutions (PHP, Cold Fusion, Perl, etc.)
Microsoft Solutions (COM, [Link] [Link],C# etc.)
Copyright 2004 Kanti Prasad All rights reserved
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 CLIENT Network CLIENT EJB EJB
Pool
EJB EJB
DB
Copyright 2004 Kanti Prasad All rights reserved
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
[Link] [Link]
Copyright 2004 Kanti Prasad All rights reserved
16. Container
A Container :
Container means a pre developed Software
Fish cannot survive outside water & EJBs cannot survive outside containers
provides the environment in which a bean executes generates Home Object generates EJB Object Implicit Middleware manages individual bean instances
gained through declaration
To increase capability. clustering is taken care by the vendor
&
Container provides System services like
Security Connection Pooling Threading
Transaction
Persistence
App Server EJB Container
EJB EJB STUB CLIENT Network Container intercepts requests EJB
Container knows what to do, as you describe everything in a special descriptor file
Copyright 2004 Kanti Prasad All rights reserved
17. J2EE Overview
Deployment Descriptors (DDs)
Web Server Independence Application Server Independence Database Independence Enterprise Resource Management Services Distributed Communication Services
Enterprise Components
services standards component-based
J2EE Container/Server J2EE Interfaces Management Services Deployment/Configuration J2SE Language/Interfaces J2SE Runtime Operating System Platform Hardware Platform
Deploy Tools
Common Programming Services
Operating System Independence Hardware Independence
Data
Copyright 2004 Kanti Prasad All rights reserved
18. J2EE 1.4 APIs
J2EE defines a model for developing multi-tier, web based, enterprise applications with distributed components
Applet Container HTTP/S Applet J2SE Application Client Container HTTP/S Client
RMI/ IIOP RMI/ IIOP
Web Container JSP Servlet
EJB Container EJB
JAX- J J RPC A A X C SAAJ R C W J E M B S S
JSP Servlet ENGINE JAX- J J W J Java Mgmt J J J C RPC A A E M Mail N D T O
SAAJ X C B S R C S JAF
JMX A D N B I C
Java Mgmt J J J C N D Mail T O D B JAF JMX A N
I
J2SE 3 TIER
J2SE 4 TIER
JAX- J W Mgmt J J C RPC A E D M O X B JMX B SAAJ S N R S C
EIS
DAO DB
J2SE
2 TIER
MainFrames
For all the APIs refer [Link]
Copyright 2004 Kanti Prasad All rights reserved
19. Enterprise JavaBeans Model
EJB is Suns 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
EJBs need a Container EJBs are deployable components EJBs are assembled to form a complete Appl EJBs are based on RMI IIOP and JNDI Technologies
Copyright 2004 Kanti Prasad All rights reserved
!=
Java Beans
JBs do not need a container JBs are development components JBs are Classes with no argument constructor 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 Client Process
Home create remove find
Remote invoke
LocalHome
EJB Impl
create timeout remove passivate activate find load invoke store
Local
create remove find STUB
invoke STUB
EJB Client
Network
Delegate Delegate Delegate Delegate
EJB Pool
Copyright 2004 Kanti Prasad All rights reserved
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
Copyright 2004 Kanti Prasad All rights reserved
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 [Link] package and three other packages below it [Link] is the entry point to the EJB Server bind associates a name with an object lookup finds an object given the name
Copyright 2004 Kanti Prasad All rights reserved
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
Copyright 2004 Kanti Prasad All rights reserved
24. EJB Roles
Service & Tool Provider
provides Server, Container and integrates with distributed facilities
EJB Provider
creates EJB components
Application Assembler
assembles apps from per-built EJB comp
Deployment Specialist
deploys apps and understands architecture issues
supplies tools
builds application Application Assembler
deploys system
Tools Provider
Deployer
System Administrator maintains deployment
supplies Application Server develops EJBs EJB Provider
Copyright 2004 Kanti Prasad All rights reserved
Application Server Provider
25. EJB Design Approaches
EJB model is based on three basic design approaches for building distributed component systems
Stateless server approach Persistent Object approach Session-oriented approach
Implementing one of these interfaces indicates your JAVA class is an EJB.
The EJB specification provides these as
Stateless session Beans Stateful session Beans
All EntityBeans
implements Interface
Message driven beans Entity Beans
All MessageDrivenBeans
implements Interface
All SessionBeans
implements Interface
[Link]
extends
[Link]
extends
[Link]
extends
[Link] interface
extends It is only a marker Interface [Link] and there are no methods to Implement. Serialization is the reason EJB is distributable.
As all these are extending the two Interfaces hence they have the behavior of both the Interfaces.
Copyright 2004 Kanti Prasad All rights reserved
26. EJB Architecture
Naming Service such as LDAP
Naming
Transaction PersistenceServer A Security
SERVICES
H
Server B JNDI Initial Context
H
App Server
8
Home Interface
EJB Container Home Object (FACTORY) 5 creates 10 EJB
(Business Logic Class)
1
H
EIS DB MainFrames
4 6
RMI/IIOP Remote Interface
Application Client EJB
Home Obj Stub
7 11
EJB Object (Wrapper)
9 delegates request
Obj Stub
Container implements/autogenerates code for the Interfaces
we have written
We will write only this Container manages TRANSACTIONS, PERSISTENCE, SECURITY & POOLING
Copyright 2004 Kanti Prasad All rights reserved
27. EJB Flow Chart
Start
C
1 6
ask JNDI Server for the Home Object JNDI Server returns ref of Home Stub ask Home for the EJB Object creates EJB Object returns reference of Remote Stub
invokes a business method thru Remote Stub goes to the JNDI Server and gets the EJB Object Remote Interface then wraps a request to the Bean class
7
3 8
Clients receives the required info
9
C
Copyright 2004 Kanti Prasad All rights reserved
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 EJB Local Home Session Bean instance e.g Bank teller Credit Card authorization
Application Client
RMI/ IIOP
EJB Object or EJB Local Object
Entity Bean instance
e.g Bank account balance Purchase order
JMS Destination
Message Driven Bean instance
e.g 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.
Copyright 2004 Kanti Prasad All rights reserved
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
Copyright 2004 Kanti Prasad All rights reserved
30. EJB Home Interface
EJB home interfaces extends [Link]
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
Copyright 2004 Kanti Prasad All rights reserved
31. EJB Remote
EJB remote interfaces extends [Link]
EJB remote interfaces provide business-specific functionality of an EJB are similar to RMI Remote interface
Copyright 2004 Kanti Prasad All rights reserved
32. EJB Implementation
EJB implementation
Class in which EJB developer codes the business methods defined in the beans component interface(s) to provide any application specific business method invocation creation removal finding activation passivation, database storage database loading logic
Copyright 2004 Kanti Prasad All rights reserved
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
Copyright 2004 Kanti Prasad All rights reserved
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
Copyright 2004 Kanti Prasad All rights reserved
35. Stateless Session EJBs View
EJB Client Client Process EJB Client
Home Remote LocalHome Local
Stateless Session
Logic
input
Network
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 its 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 Container decided it needs more instances in the pool to service clients Bean Instance does not exiist [Link]() ejbRemove() Client called remove() on the EJB object (or the client times out)
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 Client Process EJB Client
Home Remote LocalHome Local
Logic State
input output
Network
EJB Pool
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 its 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 create(args) on the home Interface. Bean Instance does not exiist [Link]() ejbRemove() Client times out Client called remove() on the EJB object (or the client times out)
setSessionContext() Client called a non-transactional business method on the EJBObject ejbCreate(args)
Containers limit of instantiated beans are reached, so it must swap your bean out.
Non-Transactional Business Method
Client called a transactional business method on the EJB Object
Bean instance is ready to service method calls
ejbPassivate()
Bean instance is in the passive state
ejbActivate() beforeCompletion() afterCompletion(true) afterCompletion(false)
afterBegin() If transaction ended in a commit..
Client called a method on a passivated bean, so Container must swap your Bean back in
Bean instance is within a transaction and ready to service method calls Client called another Transactional business method on the EJB Object.
We need to write all the methods that are there in the Implemented class If transaction ended in an abort.
Transactional Business Method
If we implement [Link] then we need to write these methods.
39. Stateful vs Stateless
Stateful Bean
A stateful bean contains a conversational state that is retained across method calls and transactions. The create method takes arguments e.g. create(String id) , create(int I , String id) There can be one or more arguments in a create method e.g An EJB that unzips 100 bytes of data An EJB that checks to see if a stock symbol is valid
Stateless Bean
A stateless bean does not have any state between calls to its methods.
The create method does not take arguments e.g create() There can be no arguments in a create method e.g An EJB that books a flight and rents a car at a travel agents web site.
Method by method comparison can be seen in [Link] at [Link]
Copyright 2004 Kanti Prasad All rights reserved
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.
Copyright 2004 Kanti Prasad All rights reserved
41. BMP Entity EJBs
(BMP = Bean-Managed Persistence)
EJB Client
LocalHome Local
Entity Bean (BMP)
Hand Coded Logic
input output
Client Process EJB Client
Home Remote
Network
EJB Pool
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 [Link] all the members should be public It should implement hashCode() and equals(.. ) methods does not implement [Link]
Copyright 2004 Kanti Prasad All rights reserved
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
CLIENT Network CLIENT EJB
EJB Container
EJB
DB
Copyright 2004 Kanti Prasad All rights reserved
44. Life Cycle of BMP Entity Bean
Each method call is an Invocation from the container to the Bean Container decided it needs another Entity Bean insinstance Does not exiist Container decided it doesnt need the Entity Bean instance anymore
newInstance()
unsetEntityContext() JVM will garbage collectt and call finalize() Client called a finder Method on the home interface
setEntityContext() Client called instance independent ejbHome() Business method ejbHome() Client called create() on the home interface (this will Create new database data) ejbCreate() Container determined that the database is out of synch with the bean. The Bean needs to load the new Database data.
Pooled
ejbFind()
Activates the Bean ejbActivate()
Passivates the Bean ejbStore()\ ejbRemove()
Client called remove() on the EJB object (this will destroy Database data)
ejbPostCreate()
ejbLoad()
ejbPassivate()
ejbLoad() Client called a business method on a EJBObject
Ready
ejbStore()
Business Method
Container determined that the database is out of synch with the bean. The Bean needs to store its Data into the Database
45. CMP Entity EJBs
(CMP = Container-Managed Persistence) Entity Bean (CMP)
Generated Logic
input output
EJB Client
LocalHome Local
Client Process EJB Client
Home Remote
Network
EJB Pool
J2EE EJB Container/Server Persisted objects (via container services) data
Persistence 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 container to the Bean NOTE : BMP has no ejbSelect() Container decided it needs another Entity Bean in does not exiist Container decided it doesnt need the Entity Bean instance anymore
newInstance()
unsetEntityContext() JVM will garbage collectt and call finalize()
setEntityContext() Client called instance independent ejbHome() Business method ejbHome() Client called create() on the home interface (this will create new database data) ejbCreate() Container determined that the database is out of Synch with the bean. The Bean needs to load the new Database data.
Client called a finder method on the home Interface, or bean called its own ejbSelect() method to locate Database data
Pooled
ejbFind() or ejbSelect()
Activates the Bean ejbActivate()
Passivates the Bean ejbStore()\ ejbRemove()
Client called remove() on the EJB object (this will destroy Database data)
ejbPostCreate()
ejbLoad()
ejbPassivate()
ejbLoad() Client called a business method on a EJBObject
Ready
ejbStore()
Container determined that the database is out of Synch with the bean. The Bean needs to store its Data into the Database
Business Method Or ejbSelect()
47. BMP vs CMP
Bean Managed Persistance
BMP offers a tactical approach The developer takes care of handling persistence BMP uses hard coded queries so we can optimize our queries
Container Managed Persistance
CMP is more strategic Vendor takes care of everything by using O-R or OODB mappings using metadata. A developer cannot optimize performance as the vedor 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 [Link] at [Link] Copyright 2004 Kanti Prasad All rights reserved
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
Copyright 2004 Kanti Prasad All rights reserved
49. Message Driven EJBs
Producer Process Messaging Service
Message
Message-Driven Bean
Message Queue Message
Handler Logic
input
Message Messaging API Producer
Network
Message 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 Message DrivenBean Instance
newInstance()
Does not exiist
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.
Copyright 2004 Kanti Prasad All rights reserved
52. Other interfaces and classes
Local interfaces are used for access within server context
[Link] [Link]
E.g.: Inter component calls 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
Copyright 2004 Kanti Prasad All rights reserved
53. Exceptions
System exceptions are unchecked and propagated to the client as [Link] Application exceptions are checked and propagated to the client as a descendant of [Link] EJB-specific exceptions include FinderException, CreateException, RemoteException (all in [Link] package) Business method exceptions are at the discretion of the EJB developer
Copyright 2004 Kanti Prasad All rights reserved
EXAMPLE 1 STATELESS BEAN
Copyright 2004 Kanti Prasad All rights reserved
54. Steps to Develop an EJB
Start C Write .java files for the BEAN, HOME and REMOTE interfaces Configure your EJB Server. E.g DB connections thread pooling etc Then copy the EJB Jar file
1 5 2
Write the Deployment descriptor
Start your EJB container and 6 confirm that it has loaded the EJB Jar file. Connect to your EJB by writing a test 7 Client .java file compile it and run it .
Compile all the STEP 1 files into .class files Using the Jar utility create an EJB Jar file containing STEP 2 & STEP 3 files C
4
End
Please download the trial Application Server software from the links provided on the Reference slide at the end.
Copyright 2004 Kanti Prasad All rights reserved
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
[Link] [Link] [Link] [Link]
These Interfaces comes with EJB distribution
[Link] [Link]
Supplied by the Bean Provider / Developer/ We will write !
We Hello world Remote Interface
need to CODEHome Interface Hello World only this block
Hello World Bean Implementation Class
Generated for us by the Container verdors tools
Hello world EJB Object Hello World Home Object
NOTE : Object implementation is Vendor specific. The container may implement either A single object for each client or A single object for all the clients.
Copyright 2004 Kanti Prasad All rights reserved
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 [Link] 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 LOCAL IMROVES PERFORMANCE
These Interfaces comes with Java 2 Platform
[Link] [Link]
These Interfaces comes with EJB distribution
[Link] [Link]
[Link]
[Link]
Supplied by the Bean Provider / Developer/ We will write !
Hello world LocalInterfaceWe need to CODE only this block Hello World Local Home Interface
Hello World Bean Implementation Class
Generated for us by the Container verdors tools
Hello world EJB LocalObject Hello World Local Home Object
NOTE : Object implementation is Vendor specific. The container may implement either A single object for each client or A single object for all the clients.
Copyright 2004 Kanti Prasad All rights reserved
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).
Rules of Java says package declaration should be at the beginning and ends with a semi colon package examples ; import [Link]; import [Link]; Importing the required files import [Link]; import [Link]; public interface HelloHome extends [Link] Our interface HelloHome is extending EJBHome means it has all the behaviour of EJBHome { Hello create() throws [Link], [Link]; 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,NoteContainer will implement (autogenerate code) for Remote and Create . us, which is the EJBHome Object so In Home Interface we are throwing 2 exceptions this Home Interface for
NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.
Copyright 2004 Kanti Prasad All rights reserved
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 [Link]; import [Link]; import [Link]; import [Link];
Our interface HelloLocalHome is extending EJBLocalHome means it has all the behaviour of EJBLocalHome
public interface HelloLocalHome extends [Link] { HelloLocal create() throws [Link];
This method creates/manufactures the (autogenerate code) for this Local Home for method corresponds to the As for every Interface we need implementation, so Container will implementEJBLocal Object and returns it . This create() us, which isa semicolon ; Object Interface methods should end with the LocalHome ejbCreate() method in HelloBean. Note Interfaces states that we are throwing no Create and not so you will find only method signatures. NOTE : Rules of In LocalHome Interface there should be onlyimplementationRemote exception as there is no network
Copyright 2004 Kanti Prasad All rights reserved
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 .
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
package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon import [Link].*; Importing the required files import [Link]; import [Link]; public interface Hello extends [Link] Our interface Hello is extending EJBObject means it has all the behaviour of EJBObject { public String hello() throws [Link]; As our requirement wants a business logic to greet Hello World a single method would be sufficient . } Interface methods should end with a semicolon ;
NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.
Copyright 2004 Kanti Prasad All rights reserved
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 [Link]; public interface HelloLocal extends [Link] Our interface Hello is extending EJBLocalObject means it has all the behaviour of EJBLocalObject { Interface methods should end with a semicolon ; public String hello() ; 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.
Copyright 2004 Kanti Prasad All rights reserved
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 [Link].*; Importing the required files import [Link].*; public class HelloBean implements [Link] NOTE : Note : Entityis a class and not an Interface like the other two (Home /Message drivenis implementing SessionBean so it is a Session Bean If it is this Bean we will implement [Link] and if it is Remote). This bean we will implement [Link] As per the below note in red we need to write all the methods what are in [Link] . { private SessionContext ctx; This ejbCreate() corresponds to the Homeobject Create(). NOTE : in Stateless Bean no arguments are sent public void ejbCreate() { [Link](ejbCreate()); } public void ejbRemove() { [Link](ejbRemove());} There is nothing much called up. These are to clean Management or In Statelss Bean ejbActivate public void ejbActivate() { [Link](ejbActivate());} Call back methods and ejbPassivate Do not apply public void ejbPassivate() { [Link](ejbPassivate()); } public void setSessionContext([Link] ctx) { Storing the Context in a variable so that it can be queried later . [Link] = 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() { [Link](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
Copyright 2004 Kanti Prasad All rights reserved
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
So now lets complete our EJB by writing the deployment descriptor.
THERE ARE MANY TOOLS WHICH CREATES THE 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 [Link] XML Standard requirement <ejb-jar> <enterprise-beans> <session> The nickname for this particular Bean <ejb-name> Hello </ejb-name> <home>[Link]</home> The fully qualified name of the Home Interface <remote>[Link]</remote> The fully qualified name of the Remote Interface <local-home>[Link]</local-home> The fully qualified name of the Local HomeInterface <local>[Link]</local> The fully qualified name of the Local Interface <ejb-class>[Link]</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>
Copyright 2004 Kanti Prasad All rights reserved
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 [Link]; importing the necessary files import [Link]; import [Link]; As there is static key word this main method executes first before any other method in that class public class HelloClient { public static void main(String [] args) throws Exception{ Properties props = [Link](); 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 = [Link](HelloHome); Get a referenceserver Home Object- the factory for Hello EJB Objects. location of the to the etc. HelloHome home = (HelloHome) [Link]( obj, [Link]); Use the factory to create the Hello EJB Object. We are then calling the hello() method Hello hello = [Link](); 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. [Link]([Link]()); [Link]();}} 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 = [Link](java:comp/env/HelloLocalHome); ( to get a ref to LocalHome Object) HelloLocalHome home = (HelloLocalHome)obj;
Copyright 2004 Kanti Prasad All rights reserved
64. EJB Jar File
The folder structure within the Ejb-jar file is META-INF/[Link] META-INF/[Link] examples/[Link] examples/[Link] examples/[Link] examples/[Link]
Properties File
Remote/Local Interface
HomeLocalHome Interface
Enterprise Bean Class
Jar Creator
Jar file
Deployment Descriptor
Jar Manifest
DEPLOYED
Or manually run C:\>Jar cf [Link] *
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 Copyright 2004 Kanti Prasad All rights reserved
65. EJB Application Assembler
.JAR Jar file
Deployment Descriptor
.WAR
JAR ARC HIEVE (.jar) [Link] REMOTE HOME EJB
Deployment Tool WEB ARCHIEVE (.war) [Link] Enterprise Archive (.EAR Files) ([Link]) JSP Servlets HTML
Copyright 2004 Kanti Prasad All rights reserved
EXAMPLE 2 STATEFUL BEAN
Copyright 2004 Kanti Prasad All rights reserved
66. Stateful Session Remote Interface
package declaration should be in the beginning package [Link]; import [Link].*; import [Link]; import [Link]; import [Link];
Importing the required classes
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
Copyright 2004 Kanti Prasad All rights reserved
67. Stateful Session Home Interface
package declaration should be in the beginning package [Link]; import [Link]; import [Link]; import [Link]; import [Link];
Importing the required classes
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
Copyright 2004 Kanti Prasad All rights reserved
68. Stateful Session Bean Class
package [Link];
package declaration should be in the beginning
import [Link].*; import [Link].*; import [Link]; import [Link]; public class CartBean implements SessionBean {
Importing the required classes
CartBean Class is implementing sessionbean means this bean class is a session bean
String customerName; String customerId; Vector contents;
We defined this also represents the remotecreate(String person) method This method in the Cart Home interface.
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
Copyright 2004 Kanti Prasad All rights reserved
69. Stateful Session Bean Class
public void ejbCreate(String person, String id) throws CreateException { if (person == null) { This also represents the Home in the Cart remote interface We defined this method create(String person, String throw new CreateException("Null person not allowed."); } else { customerName = person; } IdVerifier idChecker = new IdVerifier(); if ([Link](id)) { We are calling the validate(id) customerId = id; } else { throw new CreateException("Invalid id: " + id); }
id) method we defined
The new operator is instantiating the instance of a class
method from the class ID Verifier
// 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) { [Link](title); }
We defined this method in the Cart remote interface
public void removeBook(String title) throws BookException { boolean result = [Link](title); We defined contents as if (result == false) { throw new BookException(title + " not in cart."); } } Copyright 2004 Kanti Prasad All rights reserved
a vector
70. Stateful Session Bean Class
We defined this method in the Cart remote interface
public Vector getContents() { return contents; } public CartBean() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) {} }
Bean class constructor We need to write these methods as we are implementing SessionBean
Rules of implement states we need to implement all methods that are there in the implemented interface
Copyright 2004 Kanti Prasad All rights reserved
71. Stateful Deployment Descriptor
<?xml version="1.0" encoding="UTF-8"?> <!-Copyright 2004 Sun Microsystems, Inc. All rights reserved. SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. --> <ejb-jar version="2.1" xmlns="[Link] xmlns:xsi="[Link] xsi:schemaLocation="[Link] [Link] <display-name>CartJAR</display-name> required by any XML document <enterprise-beans> <session> <display-name>CartEJB</display-name> The nickname for this particular Bean <ejb-name>CartEJB</ejb-name> <home>[Link]</home> The fully qualified name of the Home Interface <remote>[Link]</remote> The fully qualified name of the Remote Interface <ejb-class>[Link]</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> THERE ARE MANY TOOLS WHICH CREATES THE DESCRIPTOR FOR US
Copyright 2004 Kanti Prasad All rights reserved
72. Stateful Deployment Descriptor
<assembly-descriptor> <container-transaction> <method> <ejb-name>CartEJB</ejb-name> <method-intf>Remote</method-intf> <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> <method-params> <method-param>[Link]</method-param> </method-params> </method> <trans-attribute>NotSupported</trans-attribute> </container-transaction>
Passing Bean class methods and parameter info
Passing Bean class methods and parameter info
Copyright 2004 Kanti Prasad All rights reserved
73. Stateful Deployment Descriptor
<container-transaction> <method> <ejb-name>CartEJB</ejb-name> <method-intf>Remote</method-intf> <method-name>addBook</method-name> <method-params> <method-param>[Link]</method-param> </method-params> </method> <trans-attribute>Required</trans-attribute> </container-transaction> </assembly-descriptor> </ejb-jar>
Passing Bean class methods and parameter info
Copyright 2004 Kanti Prasad All rights reserved
74. Stateful Session Client
package [Link]; import [Link].*; import [Link]; import [Link]; import [Link]; public class CartClient {
package declaration should be in the beginning
Importing the required classes
Client class
public static void main(String[] args) { As static is there this main method will execute first try { The new operator is instantiating the instance of Context initial = new InitialContext(); Object objref = [Link]("java:comp/env/ejb/SimpleCart");
a class
Looking into JNDI
CartHome home = (CartHome)[Link](objref, [Link]); Casting with Cart shoppingCart = [Link]("Duke DeEarl","123"); [Link]("The Martian Chronicles"); [Link]("2001 A Space Odyssey"); [Link]("The Left Hand of Darkness"); Vector bookList = new Vector(); bookList = [Link]();
a suitable RMI IIOP object Creating the object
adding books to the object
Invoking the bean class method through remote interface Cart
Copyright 2004 Kanti Prasad All rights reserved
75. Stateful Session Client
Enumeration enumer = [Link](); while ([Link]()) { String title = (String) [Link](); [Link](title); }
We defined booklist as a vector After storing in the variable title we are printing it
[Link]("Alice in Wonderland"); [Link](); Removing a particular book
[Link](0);
using the bean class method removeBook through remote interface Cart as we defined it this way Cart shoppingCart = [Link]("Duke DeEarl","123");
} catch (BookException ex) { [Link]("Caught a BookException: " + [Link]()); [Link](0); We had written a new class BookException } catch (Exception ex) { [Link]("Caught an unexpected exception!"); [Link](); [Link](1); } } }
and using its method to catch any errors
Copyright 2004 Kanti Prasad All rights reserved
76. Book Exception
package [Link];
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); } }
Copyright 2004 Kanti Prasad All rights reserved
77. ID Verifier
package [Link];
public class IdVerifier { /** * Default constructor. */ public IdVerifier() { } public boolean validate(String id) { boolean result = true; for (int i = 0; i < [Link](); i++) { if ([Link]([Link](i)) == false) result = false; } return result; } }
Copyright 2004 Kanti Prasad All rights reserved
ALL EXAMPLES CAN BE SEEN AT
[Link] [Link] [Link] [Link]
Copyright 2004 Kanti Prasad All rights reserved
78. Component Comparison
Component Distributability EJB Can implement the Remote or Local Interface ActiveX Uses Microsofts 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
Copyright 2004 Kanti Prasad All rights reserved
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
Copyright 2004 Kanti Prasad All rights reserved
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
Copyright 2004 Kanti Prasad All rights reserved
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
Copyright 2004 Kanti Prasad All rights reserved
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
Copyright 2004 Kanti Prasad All rights reserved
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
Copyright 2004 Kanti Prasad All rights reserved
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
Copyright 2004 Kanti Prasad All rights reserved
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
Copyright 2004 Kanti Prasad All rights reserved
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 inprocess/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 vendors Implementation.
Copyright 2004 Kanti Prasad All rights reserved
87. Conclusion
We successfully completed a Tour on EJB . We looked at how an EJB is identified. How many different types of EJBs are there and what each EJB type implements. Why LocalInterfaces were introduced. We disected the EJB and went deeper into each part i.e. BEAN Class, Remote Interface, EJB Object, Local Object, Local Interface, Home Object. We looked Into the deployment descriptor and also seen all the files in EJBJar. We looked into each Beans Methods and also learned why we needed those methods. We had done 2 different Beans examples and we were directed to the Web links where all the examples are demonstrated. Once you can get an idea of all the Interfaces, methods & exceptions raised, you can attempt to try some examples to get familiar and master EJB. There are nearly 100s of Application servers but in this presentation you can see a few majorly used AppServers sample implementation web links. Just download any one of them and try out for yourself.
CONGRATULATIONS!
Now you know as much as he know of EJB If you have any comments or appreciations then please email him at Kanti1@[Link], [Link]@[Link] He likes to hear your feed back!
Copyright 2004 Kanti Prasad All rights reserved
88. References
Application Server Information , EJB Documentation & Tutorials are found here Notes on Deploying on different Application Servers. The Art of EJB Deployment [Link] Most of EJBs related information can be seen at [Link] [Link] Mastering Enterprise Java Beans by Ed Roman , Scott Ambler & Tyler Jewel. EJB Documentation [Link] [Link] Application Servers download information . Most of them are either free or have a 60 day trial version For JBOSS Open Source go to [Link] [Link] SUNs downloads and examples
[Link]
[Link] ,[Link] [Link] BEA WebLogic downloads and examples [Link] , [Link] [Link] WebSphere downloads and examples [Link] REDHAT Application Server and Examples [Link]
Copyright 2004 Kanti Prasad All rights reserved
Covers 90 % of the MARKET
Copyright 2004 Kanti Prasad All rights reserved