Kantimahanti PrasadKantimahanti Prasad Kantimahanti PrasadKantimahanti Prasad BYBYBYBY
The Heart of J2EEThe Heart of J2EE The Heart of J2EEThe Heart of J2EE
EJB
[email protected] or [email protected]
Copyright 2004 Kanti Prasad All rights reserved
IN 30 MIN’s
A Component TechnologyA Component Technology A Component TechnologyA Component Technology
A Practical Introduction toA Practical Introduction to A Practical Introduction toA Practical Introduction to Enterprise Java BeansEnterprise Java Beans Enterprise Java BeansEnterprise Java Beans
DO YOU WANT TO ANSWER MOST
OF THE EJB QUESTIONS ?
THEN LET MEHELP YOU!
A STAR or a different color
represents important
points to NOTE
1. 1. Learning objectivesLearning objectives1. 1. Learning objectivesLearning 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
9. Types of Beans
10. EJB Interfaces & Session Contexts
11. Life cycles of different Beans
12. EJB Jar files & Deployment Descriptor
13. Sample examples
14. Components comparison
Copyright 2004 Kanti Prasad All rights reserved
2. About the Author2. About the Author2. About the Author2. About the AuthorKantimahanti.N.S.Prasad
Worked in fortune 100 Corporates in Client Server Technologies.
Specializes inArchitecture, 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.
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 ManagementInstitute teaching I.T, Project Management & Statistics. He has given some presentations on ProjectManagement and TQM at various venues. He has won few Talent/STAR performance awards and playsalmost all the sports what are under the Sun.
He hails from Vizag/ Hyderabad – India. His 3rd party tested Temperament Sorter results are belowhttps://www.advisorteam.com/temperament_sorter/testresult.asp?TID=740281673499&PID=15800https://www.advisorteam.com/temperament_sorter/testresultc.asp?TID=740281662156&PID=13606
If you liked his presentation, tell others and if you have a comment, tell him. He can be reached at [email protected] or [email protected]
U NEVER FAIL
TILL U QUIT
Copyright 2004 Kanti Prasad All rights reserved
3. Thank you note3. Thank you note3. Thank you note3. Thank you note
He wishes to thank Paul Perrone , Paulo Merson & Ramesh Behra for makingthis tutorial look the way it does.
He wishes to thank Joerg Mueller, Muruganandam, CharlesJohnson & VenuGadium who had volunteered to do the editing of this presentation.
his Sisters
Thank you for downloading my PresentationThank you for downloading my Presentation
Special thanks to all his Managers at Pramerica and Purdential U.S.
& his Cousinshis BrothersDr.Rao &Family
his ParentsSADHGISUNAYANAARUNA
DEDICATED TOCopyright 2004 Kanti Prasad All rights reserved
He wishes to thank to Katherine Ballantyne, Choi Kwan who volunteers toedit all of his Articles & Presentations.
4. Component4. Component TechnologyTechnology4. Component4. Component TechnologyTechnology
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. 5. Component CharacteristicsComponent Characteristics5. 5. Component CharacteristicsComponent Characteristics
Properties Reusability
Operations Shareable
Events Distributable
Deployable Self Containment
Self description
Components Characteristics include
Copyright 2004 Kanti Prasad All rights reserved
Components should have a mechanism for exporting
6. 6. Component P O E Component P O E 6. 6. Component P O E Component P O E
Properties
Operations
Events
Copyright 2004 Kanti Prasad All rights reserved
7. Deployable Components7. Deployable Components7. Deployable Components7. 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 Components8. Reusable Components8. Reusable Components8. 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 Components9. Shareable Components9. Shareable Components9. 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 Components10. Distributable Components10. Distributable Components10. Distributable Components
Components should provide services to clients
running locally or remotely
Remote CLIENTS
EJB Container
EJB
Possible Remote
CLIENTS
Remote CLIENTS
Remote CLIENTS
Local CLIENTS
Copyright 2004 Kanti Prasad All rights reserved
11. SelfContained Components11. SelfContained Components11. SelfContained Components11. 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 Needs12. Standard Infrastructure Needs12. Standard Infrastructure Needs12. 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 Servers13. Applicatoin Servers13. Applicatoin Servers13. Applicatoin Servers
An application server provides the infrastructure and
services to run components/applications
J2EE based
solutions
Non-J2EE solutions
(PHP, Cold Fusion, Perl, etc.)
Microsoft Solutions
(COM, ASP.Net VB.Net,C# etc.)
Application Server products are mostly
Copyright 2004 Kanti Prasad All rights reserved
14. Object Pooling14. Object Pooling14. Object Pooling14. 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
CLIENTNetwork
DB
CLIENTEJB
EJB
EJBEJB
EJB
EJB
Pool
Copyright 2004 Kanti Prasad All rights reserved
15. Directory of Application Servers15. Directory of Application Servers15. Directory of Application Servers15. 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 athttp://www.devx.com/enterprise/html/16268
http://www.javacommerce.com/articles/serverlist.htm
Copyright 2004 Kanti Prasad All rights reserved
Container provides System services like
App Server
CLIENT
NetworkSTUB
Persistence Security Connection Pooling ThreadingTransaction
EJB Container
EJB
Fish cannot survive outside water &EJB’s cannot survive outside containers
Container interceptsrequests
Copyright 2004 Kanti Prasad All rights reserved
Container knows what to do, as you describe everything in a special descriptor file
A Container :• provides the environment in which a bean executes
• generates Home Object
• generates EJB Object
• manages individual bean instances
EJB
EJB
&
Container means apre developed Software
To increase capability.clustering is taken care
by the vendor
Implicit Middleware
gained through declaration
16. Container16. Container16. Container16. Container
17. 17. J2EE OverviewJ2EE Overview
Hardware Platform
Operating System Platform
J2EE Container/Server
Operating System Independence
Hardware Independence
Common Programming Services
Distributed Communication Services
J2SE RuntimeJ2SE Language/Interfaces
services standards component-based
Enterprise ComponentsApplication Server
Independence
Database Independence
Web Server Independence
Enterprise Resource Management Services
Deployment/ConfigurationManagement Services
J2EE Interfaces
Data
DeploymentDescriptors (DDs)
DeploymentDescriptors (DDs)
DeployTools
Copyright 2004 Kanti Prasad All rights reserved
J2SE
Application ClientContainer
DBSAAJ
JAX-RPC
CONJMX
JMS
WEBS
JAXR
JDBC
MgmtDAO
Client
J2SE
SAAJ
JAX-RPC
JTA
CONJMX
Mgmt
JAF
JavaMail
JMS
JACC
WEBS
JAXR
JNDI
JDBC
AppletContainer
J2SE
HTTP/S
HTTP/S
Web Container
JSP ServletApplet
2 TIER
3 TIER
SAAJ
JAX-RPC
JTA
CONJMX
Mgmt
JAF
JavaMail
JMS
JACC
WEBS
JAXR
JNDI
JDBC
EJB Container
J2SE
RMI/IIOP
RMI/IIOP
4 TIER
EIS
MainFrames
EJB
J2EE defines a model for developing multi-tier, web based, enterprise applications with distributed components
18. 18. J2EE 1.4 APIsJ2EE 1.4 APIs18. 18. J2EE 1.4 APIsJ2EE 1.4 APIs
For all the APIs refer http://java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html
JSP Servlet ENGINE
Copyright 2004 Kanti Prasad All rights reserved
19. 19. Enterprise JavaBeans ModelEnterprise JavaBeans Model19. 19. Enterprise JavaBeans ModelEnterprise 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
Copyright 2004 Kanti Prasad All rights reserved
JBs do not need a containerJBs are development componentsJBs are Classes with no argument constructorJBs have a get and a set method on them
EJBs need a ContainerEJBs are deployable components
EJBs are assembled to form a complete Appl EJBs are based on RMI IIOP and JNDI Technologies
EnterpriseJava Beans != Java Beans
J2EE EJB Container/Server
20. 20. EJB OverviewEJB Overview
EJB Pool
Client Process
Delegate
EJB Client
DelegateDelegate
Remoteinvoke
Homecreateremove
find
Network
EJB Implcreateremove
findinvoke
timeoutpassivateactivate
loadstore
STUB STUB
LocalHome
createremove
find
Local
EJB Client
invoke
Delegate
EJB simplified distributed development–Develop EJB implementation logic–Define Home/Local Remote/Local interfaces–Container delegates client calls–Container manages resources/lifecycle/callbacks
Copyright 2004 Kanti Prasad All rights reserved
21. 21. When to use EJBWhen to use EJB21. 21. When to use EJBWhen 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. 22. Java Naming and Java Naming and Directory Interface (JNDI)Directory Interface (JNDI)
22. 22. Java Naming and Java Naming and Directory Interface (JNDI)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
Copyright 2004 Kanti Prasad All rights reserved
23. EJB Specification23. EJB Specification23. EJB Specification23. 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 Roles24. EJB Roles24. EJB Roles24. EJB Roles
Service & Tool Providerprovides Server, Container and integrates with distributed facilities
Tools Provider
EJB Provider
Application Assembler
Application Server Provider
Deployer System Administratormaintains deployment
supplies tools builds application
develops EJBssupplies Application Server
deploys system
EJB Provider
creates EJB componentsDeployment Specialistdeploys apps and understands architecture issues
Application Assemblerassembles apps from per-built EJB comp
Copyright 2004 Kanti Prasad All rights reserved
25. EJB Design Approaches25. EJB Design Approaches25. EJB Design Approaches25. EJB Design ApproachesEJB model is based on three basic design approaches for
building distributed component systemsStateless server approach Session-oriented approach
Persistent Object approach
Copyright 2004 Kanti Prasad All rights reserved
javax.ejb.EnterpriseBean interface
javax.ejb.EntityBean
The EJB specification provides these as Stateless session Beans Message driven beans
Stateful session Beans Entity Beans
All EntityBeans All SessionBeans All MessageDrivenBeans
extends extends extends
implements implements implementsInterface Interface Interface
extends
javax.ejb.SessionBean javax.ejb.MessageDrivenBean
Implementing one of these interfaces indicates your JAVA class is an EJB.
It is only a marker Interfaceand there are no methods to
Implement.
As all these are extending the two Interfaces hence they have
the behavior of both the Interfaces.Serialization is the reason EJB is distributable.
java.io.Serializable
26.26. EJB ArchitectureEJB Architecture26.26. EJB ArchitectureEJB Architecture
RMI/IIOP
Server A
App Server
EJB Container
creates
Naming Service such as LDAP
Server B
JNDI Initial Context
H
H
1
SERVICES Naming Transaction Persistence Security
DB
EIS
MainFrames
3
2
4 56
7
8
9
10
11
HomeInterface
RemoteInterfaceApplication
Client
EJB (Business Logic Class)
We will write only this
delegates request
Container manages TRANSACTIONS, PERSISTENCE, SECURITY & POOLING
Container implements/autogenerates code for the Interfaces
Home Object(FACTORY)
EJB Object(Wrapper)
Home Obj Stub
EJB Obj Stub
Copyright 2004 Kanti Prasad All rights reserved
H
H
we have written
creates EJB Object
27. 27. EJB Flow ChartEJB Flow Chart27. 27. EJB Flow ChartEJB Flow Chart
C
ask JNDI Server for the Home Object 1
Remote Interface then wraps a request to the Bean class
JNDI Server returns ref of Home Stub
ask Home for the EJB Object
returns reference of Remote Stub
C
goes to the JNDI Server and gets the EJB Object
invokes a business method thru Remote Stub
Clients receives the required info
End
Start
2
3
4
5
6
7
8
9
Copyright 2004 Kanti Prasad All rights reserved
App Server
EJB Container
28. 28. Client View of Client View of EJB EJB 28. 28. Client View of Client View of EJB EJB
Application Client
RMI/IIOP
Entity Beaninstance
EJB Home orEJB Local Home
e.g•Bank account balance•Purchase order
e.g•Stock trade messages•Work flow messages
e.g•Bank teller•Credit Card authorization
Message DrivenBean instance
Session Beaninstance
Copyright 2004 Kanti Prasad All rights reserved
ENTITY BEANS are like NOUNS as they represent data or data 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.
EJB Object orEJB Local Object
JMS Destination
SESSION BEANS are like VERBS as they represent action or business process related logic.
29. 29. EJB ClientEJB Client29. 29. EJB ClientEJB Client
EJB clients
utilizes the Java Naming and Directory Interface (JNDI) to look upfor the references to home interfaces
use home and remote EJB interfaces to utilize all EJB-basedfunctionality
Copyright 2004 Kanti Prasad All rights reserved
30. 30. EJB Home InterfaceEJB Home Interface30. 30. EJB Home InterfaceEJB 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
Copyright 2004 Kanti Prasad All rights reserved
31. 31. EJB RemoteEJB Remote31. 31. EJB RemoteEJB Remote
EJB remote interfaces extends javax.ejb.EJBObject
EJB remote interfaces • provide business-specific functionality of an EJB• are similar to RMI Remote interface
Copyright 2004 Kanti Prasad All rights reserved
32. 32. EJB ImplementationEJB Implementation32. 32. EJB ImplementationEJB 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
Copyright 2004 Kanti Prasad All rights reserved
33. Session Context33. Session Context33. Session Context33. 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 EJB34. Stateless Session EJB34. Stateless Session EJB34. 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
J2EE EJB Container/Server
35. 35. Stateless Session EJBsStateless Session EJBs View View
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
Client Process
EJB Client Remote
Home
Stateless SessionLocalHome Local
EJB Client
Network
Logic
input
outputEJB Pool
Pool of equivalentmethod ready instances
ejbRemove()
ejbCreate()
Bean Instancedoes not exiist
Container decided it needs more instancesin the pool to service clients
Client called remove() on the EJB object (or the client times out)
Class.newInstance()
setSessionContext()
Each method call is an invocation from the
container to the Bean
36. Life Cycle 36. Life Cycle of of Stateless SessionStateless Session Bean Bean
TransactionalBusiness Method
Client called another Transactional business methodon the EJB Object.
J2EE EJB Container/Server
37. 37. StateStatefulful Session EJBs Session EJBs View View
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
Client Process
EJB Client Remote
Home
Stateful Session
LocalHome Local
EJB Client
Network
Logic
input
outputEJB Pool
State
If we implement Javax.ejb.SessionSynchronization then we need to write these methods.
Bean instance is in the passive state
Bean instance is readyto service method calls
Non-TransactionalBusiness Method
afterBegin()
ejbRemove()
ejbCreate(args)
Bean Instancedoes not exiistClient called create(args)
on the home Interface.
Container’s limit ofinstantiated beansare reached, so it mustswap your bean out.
Client called remove() on the EJB object (or the client times out)
Client called a transactional business method on theEJB Object
Client called a non-transactional businessmethod on the EJBObject
Class.newInstance()
setSessionContext()
ejbActivate()
beforeCompletion()
afterCompletion(true)
ejbPassivate()
Each method call is an Invocation from the
container to the Bean
38 .Life Cycle 38 .Life Cycle of of Stateful SessionStateful Session Bean Bean
TransactionalBusiness Method
Client called another Transactional business methodon the EJB Object.
Client called a methodon a passivated bean, so Container must swap your Bean back in
Bean instance is withina transaction and ready to service method calls
afterCompletion(false)
If transaction endedin an abort.
If transaction endedin a commit..
Client times out
We need to write all
the methods that
are there in the
Implemented class
39. Stateful vs Stateless39. Stateful vs Stateless39. Stateful vs Stateless39. Stateful vs Stateless
Copyright 2004 Kanti Prasad All rights reserved
e.g
An EJB that unzips 100 bytes of data
An EJB that checks to see if a stock symbol is valid
e.g
An EJB that books a flight and rents a car at a travel agent’s
web site.
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
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
Stateful Bean Stateless Bean
Method by method comparison can be seen in EJB20Matrix.doc at http://www.volantec.biz/cmp20.htm
40. Entity Bean40. Entity Bean40. Entity Bean40. 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
J2EE EJB Container/Server
Client Process
EJB Client Remote
Home
Entity Bean (BMP)
LocalHome Local
EJB Client
Network EJB Pool
41. 41. BMP Entity EJBsBMP Entity EJBs
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
(BMP = Bean-Managed Persistence)
data
input
output
HandCodedLogic
Persisted objects (via hand-coding)
42. 42. Primary key classPrimary key class42. 42. Primary key classPrimary 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
Copyright 2004 Kanti Prasad All rights reserved
43. Shared Entity Bean43. Shared Entity Bean43. Shared Entity Bean43. 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
CLIENTNetwork
DB
CLIENTEJB
EJB
Copyright 2004 Kanti Prasad All rights reserved
ReadyejbLoad() ejbStore()
Pooled
Passivates the Bean
ejbCreate()
ejbPostCreate()
ejbRemove()
ejbHome() ejbFind()
Does not exiistContainer decided itneeds another Entity Bean insinstance
Container decided itdoesn’t need the Entity Bean instanceanymore
Client called a finderMethod on the home interface
Client called remove() on the EJB object (this will destroy Database data)
Container determinedthat the database is out ofsynch with the bean. The Bean needs to store its Data into the Database
Container determinedthat the database is out ofsynch with the bean. The Bean needs to load the new Database data.
Client called create() on the home interface (this willCreate new database data)
Client called instanceindependent ejbHome()Business method
Activates the Bean
newInstance()
setEntityContext()
unsetEntityContext()
JVM will garbage collectt and call finalize()
ejbActivate()
ejbLoad()
ejbStore()\
ejbPassivate()
Each method call is an Invocation from the
container to the Bean
44. Life Cycle 44. Life Cycle of of BMP BMP Entity BeanEntity Bean
Business Method
Client called a business method on a EJBObject
J2EE EJB Container/Server
Client Process
EJB Client Remote
Home
Entity Bean (CMP)
LocalHome Local
EJB Client
Network EJB Pool
data
input
output
GeneratedLogic
45. 45. CMP Entity EJBsCMP Entity EJBs
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
(CMP = Container-Managed Persistence)
PersistenceDDs
PersistenceDDs
Persisted objects (via container services)
ReadyejbLoad() ejbStore()
Pooled
Passivates the Bean
ejbCreate()
ejbPostCreate()
ejbRemove()
ejbHome() ejbFind() or ejbSelect()
does not exiistContainer decided itneeds another Entity Bean in
Container decided itdoesn’t need the Entity Bean instanceanymore
Client called a findermethod on the home Interface, or bean called its own ejbSelect() method to locate Database data
Client called remove() on the EJB object (this will destroy Database data)
Container determinedthat the database is out ofSynch with the bean. The Bean needs to store its Data into the Database
Container determinedthat the database is out ofSynch with the bean. The Bean needs to load the new Database data.
Client called create() on the home interface (this willcreate new database data)
Client called instanceindependent ejbHome()Business method
Activates the Bean
newInstance()
setEntityContext()
unsetEntityContext()
JVM will garbage collectt and call finalize()
ejbActivate()
ejbLoad()
ejbStore()\
ejbPassivate()
Each method call is an Invocation from the
container to the Bean
46. Life Cycle 46. Life Cycle of of CMP CMP Entity BeanEntity Bean
Business MethodOr ejbSelect()
Client called a business method on a EJBObject
NOTE : BMP has no ejbSelect()
47. BMP vs CMP47. BMP vs CMP47. BMP vs CMP47. BMP vs CMP
Copyright 2004 Kanti Prasad All rights reserved
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
BMP offers a tactical approach
The developer takes care of handling persistence
BMP uses hard coded queries so we can optimize our
queries
Bean Managed Persistance
CMP is more strategic
Vendor takes care of everything by using O-R or OODBmappings using metadata. A developer cannot optimize performance as the vedor takes care of it
Container Managed Persistance
48. Message Driven Bean48. Message Driven Bean48. Message Driven Bean48. 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
J2EE EJB Container/Server
Network
49. 49. Message Driven EJBsMessage Driven EJBs
Messaging Service
MessageQueueProducer Process
MessageProducer
Messaging
API
Message-Driven BeanHandler Logic
input
MessageListener
Message Message
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
EJB Pool
Asynchronous messaging
Pooled
ejbCreate()
Does not exiistContainer decided itneeds another Message DrivenBean Instance
newInstance()
setMessageDrivenContext()
Each method call is an Invocation from the
container to the Bean
50. Life Cycle 50. Life Cycle of of Message DrivenMessage Driven Bean Bean
onMessage()
ejbRemove()
51. Deployment51. Deployment51. Deployment51. 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
Copyright 2004 Kanti Prasad All rights reserved
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.
Declaring without programming helps the application assembler to change the XML file easily.
52. 52. Other interfaces and classesOther interfaces and classes52. 52. Other interfaces and classesOther interfaces and classes
Local interfaces are used for access within server context javax.ejb.EJBLocalHome javax.ejb.EJBLocalObject
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
E.g.:•Inter component calls•Servlet invocation
Copyright 2004 Kanti Prasad All rights reserved
53. 53. ExceptionsExceptions53. 53. ExceptionsExceptions
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
Copyright 2004 Kanti Prasad All rights reserved
Copyright 2004 Kanti Prasad All rights reserved
EXAMPLE 1STATELESS BEAN
Using the Jar utility create an EJB Jarfile containing STEP 2 & STEP 3 files
54. Steps to Develop an EJB54. Steps to Develop an EJB54. Steps to Develop an EJB54. Steps to Develop an EJB
C
Write .java files for the BEAN, HOME and REMOTE interfaces
1
Write the Deployment descriptor
Compile all the STEP 1 files into .class files
Configure your EJB Server. E.g DB connections thread pooling etc Then copy the EJB Jar file
C
Connect to your EJB by writing a testClient .java file compile it and run it .
Start your EJB container and confirm that it has loaded the EJB Jar file.
End
Start
2
3
4
6
7
Copyright 2004 Kanti Prasad All rights reserved
5
Please download the trial Application Server software from the links provided on the Reference slide at the end.
We will apply the previous slide flow chart procedure to make up our first EJB
example
Copyright 2004 Kanti Prasad All rights reserved
These Interfaces comes with Java 2 Platformjava.io.Serializablejava.rmi.Remote
These Interfaces comes with EJB distribution Javax.ejb.EJBObject Javax.ejb.EJBHome
Javax.ejb.EnterpriseBean
Javax.ejb.SessonBean
Supplied by the Bean Provider / Developer/ We will write !
Hello world Remote Interface Hello World Home InterfaceHello World Bean
Implementation Class
Generated for us by the Container verdor’s tools
Hello world EJB Object Hello World Home Object
We need to CODE only this block
55. 55. Hello World Object Model using RMIHello World Object Model using RMI55. 55. Hello World Object Model using RMIHello World Object Model using RMI
NOTE : Object implementation is Vendor specific. The container may implement eitherA single object for each client or A single object for all the clients.
56. Hello World Object Model using LOCAL56. Hello World Object Model using LOCAL56. Hello World Object Model using LOCAL56. Hello World Object Model using LOCAL
Copyright 2004 Kanti Prasad All rights reserved
These Interfaces comes with Java 2 Platformjava.io.Serializablejava.rmi.Remote
These Interfaces comes with EJB distribution Javax.ejb.EJBLocalObject Javax.ejb.EJBLocalHome
Javax.ejb.EnterpriseBean
Javax.ejb.SessonBean
Supplied by the Bean Provider / Developer/ We will write !
Hello world LocalInterface Hello World Local Home InterfaceHello World Bean
Implementation Class
Generated for us by the Container verdor’s tools
Hello world EJB LocalObject Hello World Local Home Object
We need to CODE only this block
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 LOCAL IMROVES PERFORMANCE
NOTE : Object implementation is Vendor specific. The container may implement eitherA single object for each client or A single object for all the clients.
57. HelloBean Home Interface57. HelloBean Home Interface57. HelloBean Home Interface57. HelloBean Home Interface
package examples ;
import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
public interface HelloHome extends javax.ejb.EJBHome
{
Hello create() throws java.rmi.RemoteException, javax.ejb.CreateException;
}
Copyright 2004 Kanti Prasad All rights reserved
Rules of Java says package declaration should be at the beginning and ends with a semi colon
This is the Home Interface for the Home EJB (HelloBean).
This method creates/manufactures the EJBObject and returns it . This create() method corresponds to the ejbCreate() method in HelloBean.Note In Home Interface we are throwing 2 exceptions Remote and Create .
NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.
Our interface HelloHome is extending EJBHome means it has all the behaviour of EJBHome
Interface methods should end with a semicolon ;
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 pleasesee the previous slide Hello World Object Model using RMI.
Importing the required files
As for every Interface we need implementation, so Container will implement (autogenerate code) for this Home Interface for us, which is the EJBHome Object
58. HelloLocalHome Interface58. HelloLocalHome Interface58. HelloLocalHome Interface58. HelloLocalHome Interface
package examples ;
import javax.ejb.EJBLocalHome;
import javax.ejb.CreateException;
import javax.ejb.FinderException;
import java.util.Collection;
public interface HelloLocalHome extends javax.ejb.EJBLocalHome
{
HelloLocal create() throws javax.ejb.CreateException;
}Copyright 2004 Kanti Prasad All rights reserved
Rules of Java says package declaration should be at the beginning and ends with a semi colon
This is the LocalHome Interface for the Home EJB (HelloBean).
This method creates/manufactures the EJBLocal Object and returns it . This create() method corresponds to the ejbCreate() method in HelloBean.Note In LocalHome Interface we are throwing only Create and not Remote exception as there is no network
So now lets code the HelloLocalHome Interface
NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.
Our interface HelloLocalHome is extending EJBLocalHome means it has all the behaviour of EJBLocalHome
Interface methods should end with a semicolon ;As for every Interface we need implementation, so Container will implement (autogenerate code) for this Local Home for us, which is the LocalHome Object
59. HelloBean Remote Interface59. HelloBean Remote Interface59. HelloBean Remote Interface59. HelloBean Remote Interface
package examples ;
import java.util.*;
import javax.ejb.EJBObject;
import java.rmi.RemoteException;
public interface Hello extends javax.ejb.EJBObject
{
public String hello() throws java.rmi.RemoteException;
}
Copyright 2004 Kanti Prasad All rights reserved
Rules of Java says package declaration should be at the beginning and ends with a semi colon
Clients interact with the EJB Object through this Remote interface that is why we need to write this interface .
As for every Interface we need implementation, so Container will implement (autogenerate code) for this Remote Interface for us, which is the EJBObject
As our requirement wants a business logic to greet Hello World a single method would be sufficient .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.
So lets code the Remote Interface
NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.
Our interface Hello is extending EJBObject means it has all the behaviour of EJBObject
Interface methods should end with a semicolon ;
Importing the required files
60. HelloLocal Interface60. HelloLocal Interface60. HelloLocal Interface60. HelloLocal Interface
package examples ;
import javax.ejb.EJBLocalObject;
public interface HelloLocal extends javax.ejb.EJBLocalObject
{
public String hello() ;
}
Copyright 2004 Kanti Prasad All rights reserved
Rules of Java says package declaration should be at the beginning and ends with a semi colon
Clients interact with the EJB Object through this Local interface when there is no network involved. .
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
NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.
Our interface Hello is extending EJBLocalObject means it has all the behaviour of EJBLocalObject
Interface methods should end with a semicolon ;
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
61. The Bean Class61. The Bean Class61. The Bean Class61. The Bean Class
package examples ;
import java.util.*;
import javax.ejb.*;
public class HelloBean implements javax.ejb.SessionBean
{
private SessionContext ctx;
public void ejbCreate() { System.out.println(“ejbCreate()”); }
public void ejbRemove() { System.out.println(“ejbRemove()”);}
public void ejbActivate() { System.out.println(“ejbActivate()”);}
public void ejbPassivate() { System.out.println(“ejbPassivate()”); }
public void setSessionContext(javax.ejb.SessionContext ctx) {
this.ctx = ctx; }
public String hello() { System.out.println(“Hello()”);
return “Hello World! “ ; }
}
Copyright 2004 Kanti Prasad All rights reserved
Rules of Java says package declaration should be at the beginning and ends with a semi colon
This is where we will code our Business logic
Note : this is a class and not an Interface like the other two (Home / Remote). This is implementing SessionBean so it is a Session Bean
This ejbCreate() corresponds to the Homeobject Create(). NOTE : in Stateless Bean no arguments are sent
So now lets code the actual EJB Class
As per the below note in red we need to write all the methods what are in javax.ejb.SessionBean .
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.
NOTE : If it is Entity Bean we will implement javax.ejb.EntityBean and if it is Message driven bean we will implement javax.ejb.MessagedrivenBean
These are called Management or
Call back methods
Our Business method which matchesour Remote Interface method signature
In Statelss Bean ejbActivateand ejbPassivate Do not apply
There is nothing much to clean up.
Storing the Context in a variable so that it can be queried later . 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.
Importing the required files
62. The Deployment descriptor62. The Deployment descriptor62. The Deployment descriptor62. The Deployment descriptor
<!DOCTYPE ejb-jar PUBLIC “-//Sun Microsystems, Inc. // DTD Enterprise JavaBeans 2.0 // EN “ “ http://java.sun.com.dtd/ejb-jar_2_0.dtd”>
<ejb-jar>
<enterprise-beans>
<session>
<ejb-name> Hello </ejb-name>
<home>examples.HelloHome</home>
<remote>examples.Hello</remote>
<local-home>examples.HelloLocalHome</local-home>
<local>examples.HelloLocal</local>
<ejb-class>examples.HelloBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
Copyright 2004 Kanti Prasad All rights reserved
As a Bean provider we need to specify the Middleware needs through this descriptor.
So now lets complete our EJB by writing the deployment descriptor.
XML Standard requirement
The nickname for this particular Bean
The fully qualified name of the Home Interface
The fully qualified name of the Remote Interface
The fully qualified name of the Local HomeInterfaceThe fully qualified name of the Local Interface
The fully qualified name of the EJB Class
Whether the session bean is stateful or stateless
THERE ARE MANY TOOLS WHICH CREATES THE DESCRIPTOR
FOR US
63. The Client 63. The Client 63. The Client 63. The Client
package examples;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Properties;
public class HelloClient {
public static void main(String [] args) throws Exception{
Properties props = System.getProperties();
Context ctx = new InitialContext(props);
Object obj = ctx.lookup(“HelloHome”);
HelloHome home = (HelloHome) javax.rmi.PortableRemoteObject.narrow(
obj, HelloHome.class);
Hello hello = home.create();
System.out.println(hello.hello());
hello.remove();}}
Copyright 2004 Kanti Prasad All rights reserved
Rules of Java says package declaration should be at the beginning and ends with a semi colon
So now lets code our Client to access our simple stateless session bean.
importing the necessary files
As there is static key word this main method executes first before any other method in that class
Assigning props variable with properties information for JNDI initialization
Obtaining the JNDI initial context is the starting point for connection to a JNDI tree
Get a reference to the Home Object- the factory for Hello EJB Objects.
We are casting HelloHome here, as Home Objects are RMI-IIOP objects and so weNeed to use a special RMI-IIOP cast.
Use the factory to create the Hello EJB Object. We are then calling the hello() methodOn the EJB Object. The EJB object will delegate the call to the Bean,receive theResults and return it to us . We then print it on the screen.
Once we are done with the EJB Object, we can remove it.
By passing environment properties we will choose our JNDI driver,network location of the server etc.
NOTE : To call Local Interface you need not cast with the PortableRemoteObject. So the block in red will be changed toObject obj = ctx.lookup(“java:comp/env/HelloLocalHome”); ( to get a ref to LocalHome Object)HelloLocalHome home = (HelloLocalHome)obj;
64. EJB Jar File64. EJB Jar File64. EJB Jar File64. EJB Jar File
PropertiesFile
Remote/LocalInterface
HomeLocalHomeInterface
EnterpriseBean Class
DeploymentDescriptor
Jar Manifest
JarfileJar Creator
DEPLOYED
Copyright 2004 Kanti Prasad All rights reserved
Jar file is a .ZIP compression format . META-MF file is a listing file automatically created by the Jar utility.
Or manually run C:\>Jar cf HelloWorld.jar *
The folder structure within the Ejb-jar file is META-INF/MANIFEST.MFMETA-INF/ejb-jar.xmlexamples/HelloBean.classexamples/HelloLocalHome.classexamples/HelloLocal.classexamples/Hello.class
Please read the Deployment instructions provided by the Application server as it is Vendor specific
65. EJB Application Assembler65. EJB Application Assembler65. EJB Application Assembler65. EJB Application Assembler
.JAR .WARDeployment Descriptor
Deployment Tool
Enterprise Archive(.EAR Files)
(Application.XML)
WEB ARCHIEVE (.war)
JSPServlets
HTMLWEB.XML
JAR ARC HIEVE (.jar)
HOMEEJB
REMOTEEJB-JAR.XML
Copyright 2004 Kanti Prasad All rights reserved
Jarfile
Copyright 2004 Kanti Prasad All rights reserved
EXAMPLE 2 STATEFUL BEAN
66. Stateful Session Remote Interface66. Stateful Session Remote Interface66. Stateful Session Remote Interface66. Stateful Session Remote Interface
Copyright 2004 Kanti Prasad All rights reserved
package declaration should be in the beginning
Importing the required classes
There will not be any implementation in Interfaces
EJB spec says all remote interface methods need to throw remote exception
Our bean class CartBean methods are mirrored here
Remote Cart is extending EJBObject means Cart has all the behaviour of it
package samples.ejb.stateful.simple.ejb;
import java.util.*;
import javax.ejb.EJBObject;
import java.rmi.RemoteException;
import samples.ejb.stateful.simple.tools.BookException;
public interface Cart extends EJBObject
{
public void addBook(String title) throws RemoteException;
public void removeBook(String title) throws BookException, RemoteException;
public Vector getContents() throws RemoteException;
}
67. Stateful Session Home Interface67. Stateful Session Home Interface67. Stateful Session Home Interface67. Stateful Session Home Interface
Copyright 2004 Kanti Prasad All rights reserved
package declaration should be in the beginning
Importing the required classes
There will not be any implementation in Interfaces
EJB spec says all Home interface methods need to throw remote & create exceptions
In a Stateful Bean you can have more than one create method taking arguments
CartHome is extending EJBHome means CartHome has all the behaviour of it
In our bean class CartBean these represent ejbCreate(String person) & ejbCreate(String person, String id)
package samples.ejb.stateful.simple.ejb;
import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
public interface CartHome extends EJBHome {
Cart create(String person) throws RemoteException, CreateException;
Cart create(String person, String id) throws RemoteException,
CreateException;
}
68. Stateful Session Bean Class68. Stateful Session Bean Class68. Stateful Session Bean Class68. Stateful Session Bean Class
Copyright 2004 Kanti Prasad All rights reserved
package declaration should be in the beginning
Importing the required classes
as this is the Bean class we will implement the business logic here
CartBean Class is implementing sessionbean means this bean class is a session bean
NOTE : AS we are implementing and not extending we need to write all the methods that are there in the Sessionbean
We defined this method in the Cart remote interface. This also represents the Home create(String person) method
package samples.ejb.stateful.simple.ejb;
import java.util.*;
import javax.ejb.*;
import samples.ejb.stateful.simple.tools.BookException;
import samples.ejb.stateful.simple.tools.IdVerifier;
public class CartBean implements SessionBean {
String customerName;
String customerId;
Vector contents;
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();
}
// This block is a supporting business method written in idVerifier class
69. Stateful Session Bean Class69. Stateful Session Bean Class69. Stateful Session Bean Class69. Stateful Session Bean Class
Copyright 2004 Kanti Prasad All rights reserved
We defined this method in the Cart remote interface This also represents the Home create(String person, String id) method we defined
The new operator is instantiating the instance of a class
We are calling the validate(id) method from the class ID Verifier
We defined this method in the Cart remote interface
We defined this method in the Cart remote interface
We defined contents as a vector
public void ejbCreate(String person, String id) throws CreateException {
if (person == null) {
throw new CreateException("Null person not allowed.");
} else {
customerName = person;
}
IdVerifier idChecker = new IdVerifier();
if (idChecker.validate(id)) {
customerId = id;
} else {
throw new CreateException("Invalid id: " + id);
}
contents = new Vector();
}
public void addBook(String title) {
contents.addElement(title);
}
public void removeBook(String title) throws BookException {
boolean result = contents.removeElement(title);
if (result == false) {
throw new BookException(title + " not in cart.");
}
}
70. Stateful Session Bean Class70. Stateful Session Bean Class70. Stateful Session Bean Class70. Stateful Session Bean Class
Copyright 2004 Kanti Prasad All rights reserved
We defined this method in the Cart remote interface
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
Bean class constructor
public Vector getContents() {
return contents;
}
public CartBean() {}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext(SessionContext sc) {}
}
<?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="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>
<session>
<display-name>CartEJB</display-name>
<ejb-name>CartEJB</ejb-name>
<home>samples.ejb.stateful.simple.ejb.CartHome</home>
<remote>samples.ejb.stateful.simple.ejb.Cart</remote>
<ejb-class>samples.ejb.stateful.simple.ejb.CartBean</ejb-class>
<session-type>Stateful</session-type>
<transaction-type>Container</transaction-type>
<security-identity>
<use-caller-identity/>
</security-identity>
</session>
</enterprise-beans>
71. Stateful Deployment Descriptor71. Stateful Deployment Descriptor71. Stateful Deployment Descriptor71. Stateful Deployment Descriptor
Copyright 2004 Kanti Prasad All rights reserved
required by any XML document
The nickname for this particular Bean
The fully qualified name of the Home Interface
The fully qualified name of the Remote Interface
The fully qualified name of the EJB Class
Bean type is mentioned here
Closing session and ejb
THERE ARE MANY TOOLS WHICH CREATES THE DESCRIPTOR
FOR US
72. Stateful Deployment Descriptor72. Stateful Deployment Descriptor72. Stateful Deployment Descriptor72. Stateful Deployment Descriptor
Copyright 2004 Kanti Prasad All rights reserved
Passing Bean class methods and parameter info
Passing Bean class methods and parameter info
<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>java.lang.String</method-param>
</method-params>
</method>
<trans-attribute>NotSupported</trans-attribute>
</container-transaction>
73. Stateful Deployment Descriptor73. Stateful Deployment Descriptor73. Stateful Deployment Descriptor73. Stateful Deployment Descriptor
Copyright 2004 Kanti Prasad All rights reserved
Passing Bean class methods and parameter info
<container-transaction>
<method>
<ejb-name>CartEJB</ejb-name>
<method-intf>Remote</method-intf>
<method-name>addBook</method-name>
<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 Client74. Stateful Session Client74. Stateful Session Client74. Stateful Session Client
Copyright 2004 Kanti Prasad All rights reserved
package declaration should be in the beginning
Importing the required classes
Client class
As static is there this main method will execute first
The new operator is instantiating the instance of a class
Looking into JNDI
Casting with a suitable RMI IIOP object
Creating the object
Invoking the bean class method through remote interface Cart
adding books to the object
package samples.ejb.stateful.simple.ejb;
import java.util.*;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
public class CartClient {
public static void main(String[] args) {
try {
Context initial = new InitialContext();
Object objref = initial.lookup("java:comp/env/ejb/SimpleCart");
CartHome home =
(CartHome)PortableRemoteObject.narrow(objref,
CartHome.class);
Cart shoppingCart = home.create("Duke DeEarl","123");
shoppingCart.addBook("The Martian Chronicles");
shoppingCart.addBook("2001 A Space Odyssey");
shoppingCart.addBook("The Left Hand of Darkness");
Vector bookList = new Vector();
bookList = shoppingCart.getContents();
75. Stateful Session Client75. Stateful Session Client75. Stateful Session Client75. Stateful Session Client
Copyright 2004 Kanti Prasad All rights reserved
We defined booklist as a vector
After storing in the variable “title” we are printing it
Removing a particular book using the bean class method removeBook through remote interface Cart –as we defined it this wayCart shoppingCart = home.create("Duke DeEarl","123");
We had written a new class BookException and using its method to catch any errors
Enumeration enumer = bookList.elements();
while (enumer.hasMoreElements()) {
String title = (String) enumer.nextElement();
System.out.println(title);
}
shoppingCart.removeBook("Alice in Wonderland");
shoppingCart.remove();
System.exit(0);
} catch (BookException ex) {
System.err.println("Caught a BookException: " + ex.getMessage());
System.exit(0);
} catch (Exception ex) {
System.err.println("Caught an unexpected exception!");
ex.printStackTrace();
System.exit(1);
}
}
}
76. Book Exception76. Book Exception76. Book Exception76. 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);
}
}
Copyright 2004 Kanti Prasad All rights reserved
77. ID Verifier77. ID Verifier77. ID Verifier77. 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;
}
}
Copyright 2004 Kanti Prasad All rights reserved
Copyright 2004 Kanti Prasad All rights reserved
ALL EXAMPLESCAN BE SEEN AT
http://www.weblogic.com/docs/examples/ejb/Package-examples.ejb.htmlhttp://my.execpc.com/~gopalan/java/entity.htmlhttp://java.sun.com/developer/onlineTraining/Beans/EJBTutorial/http://developers.sun.com/prodtech/javatools/jsstandard/reference/techart/entitybeans.html
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
CORBAORB makes use of GIOP and other protocols to perform IPC
78. 78. Component Component ComparisonComparison78. 78. Component Component ComparisonComparison
Component Distributability
Copyright 2004 Kanti Prasad All rights reserved
EJB
exports operations through Remote Interface
ActiveX
exports operations in the same interface
CORBA
exports methods through Interface Repository
79. 79. Component Component ComparisonComparison79. 79. Component Component ComparisonComparison
Components provide interfaces in the form of Operations
Copyright 2004 Kanti Prasad All rights reserved
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
ActiveXTransactions, 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
CORBACORBAServices have different APIs. CORBAServices can be complicated
to code with. CORBAServices are not supported by all ORBs
80. 80. Component Component ComparisonComparison80. 80. Component Component ComparisonComparison
Self – Container Components
Copyright 2004 Kanti Prasad All rights reserved
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
81. 81. Component Component ComparisonComparison81. 81. Component Component ComparisonComparison
Components provide interfaces in the form of Properties.
Copyright 2004 Kanti Prasad All rights reserved
EJB
Events supported through JMS with Message
Driven Bean
ActiveX
exports Events in the same interface
CORBAEvents supported through Event Service but cannot be exported
82. 82. Component Component ComparisonComparison82. 82. Component Component ComparisonComparison
Components provide interfaces in the form of Events.
Copyright 2004 Kanti Prasad All rights reserved
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
83. 83. Component Component ComparisonComparison83. 83. Component Component ComparisonComparison
Component Reusability
Copyright 2004 Kanti Prasad All rights reserved
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
84. 84. Component Component ComparisonComparison84. 84. Component Component ComparisonComparison
Component Reusability
Copyright 2004 Kanti Prasad All rights reserved
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
85. 85. Component Component ComparisonComparison85. 85. Component Component ComparisonComparison
Component Reusability
Copyright 2004 Kanti Prasad All rights reserved
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.
ActiveXuses Microsoft's in–process/out-of-process architecture for sharing
multiple ActiveX components and Client components.
CORBAORB makes multiple instances of CORBA objects. Clients’ contexts are
managed by ORB but can behave differently based upon vendor’s
Implementation.
86. 86. Component Component ComparisonComparison86. 86. Component Component ComparisonComparison
Components Shareability
Copyright 2004 Kanti Prasad All rights reserved
If you have any comments or appreciations then please email him at [email protected], [email protected]
He likes to hear your feed back!
CONGRATULATIONS! Now you knowas much as he know of EJB
87. 87. ConclusionConclusion87. 87. ConclusionConclusion
Copyright 2004 Kanti Prasad All rights reserved
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 EJB–Jar. 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.
Application Servers download information . Most of them are either free or have a 60 day trial version
REDHAT Application Server and Examples
http://www.redhat.com/docs/manuals/rhaps/jonas-guide/
WebSphere downloads and examples
http://www-306.ibm.com/software/webservers/appserv/doc/v20dcadv/doc/howto/ep001.html
Application Server Information , EJB Documentation & Tutorials are found here
http://my.execpc.com/~gopalan/java/java_tutorial.html
EJB Documentation http://java.sun.com/products/ejb/javadoc-2_0-fr/
http://www.theserverside.com/ Mastering Enterprise Java Beans
by Ed Roman , Scott Ambler & Tyler Jewel.
BEA WebLogic downloads and examples
http://commerce.bea.com/index.jsp , http://www.weblogic.com/docs/examples/index.html
http://dev2dev.bea.com/codelibrary/code/examples_ejb20.jsp
88. 88. ReferencesReferences88. 88. ReferencesReferences
Copyright 2004 Kanti Prasad All rights reserved
Most of EJB’s related information can be seen at http://www.volantec.biz/ejb.htm
SUN’s downloads and exampleshttp://developers.sun.com/prodtech/javatools/jsstandard/reference/docs/s1s5/partsuppliers.html
http://java.sun.com/j2se/1.4.2/download.html ,http://java.sun.com/j2ee/1.4/docs/tutorial/doc/
http://java.sun.com/developer/onlineTraining/EJBIntro/EJBIntro.html
For JBOSS Open Source go to http://www.jboss.org/downloads/index
http://www.kevinboone.com/jboss_tut_1.html
Notes on Deploying on different Application Servers.
The Art of EJB Deployment http://www.javaworld.com/javaworld/jw-08-2001/jw-0803-ejb.html
Covers 90 % of the MARKET
Copyright 2004 Kanti Prasad All rights reserved