A Practical Approach To EnterPrise Java Beans - Site
A Practical Approach To EnterPrise Java Beans - Site
A Practical Approach To EnterPrise Java Beans - Site
A Component Technology
IN 30 MINs
DO YOU WANT TO ANSWER MOST OF THE EJB QUESTIONS ?
EJB
Kantimahanti Prasad
[email protected] or [email protected]
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
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
https://www.advisorteam.com/temperament_sorter/testresult.asp?TID=740281673499&PID=15800 https://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]
ARUNA
SUNAYANA
SADHGI
his Parents
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
5. Component Characteristics
Components Characteristics include
Properties Operations Events Deployable Self description Reusability Shareable Distributable Self Containment
6. Component P O E
Components should have a mechanism for exporting
Properties
Operations Events
7. Deployable Components
8. Reusable Components
9. Shareable Components
If multiple clients are using a component simultaneously, the component will provide the same quality of service to all the clients
Remote CLIENTS
Remote CLIENTS
Pool
EJB EJB
DB
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
&
Container provides System services like
Security Connection Pooling Threading
Transaction
Persistence
Container knows what to do, as you describe everything in a special descriptor file
Copyright 2004 Kanti Prasad All rights reserved
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
Data
JMX A D N B I C
J2SE 3 TIER
J2SE 4 TIER
EIS
DAO DB
J2SE
2 TIER
MainFrames
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
EJB Impl
create timeout remove passivate activate find load invoke store
Local
invoke STUB
EJB Client
Network
EJB Pool
EJB Provider
creates EJB components
Application Assembler
assembles apps from per-built EJB comp
Deployment Specialist
deploys apps and understands architecture issues
supplies tools
deploys system
Tools Provider
Deployer
All SessionBeans
implements Interface
javax.ejb.EntityBean
extends
javax.ejb.SessionBean
extends
javax.ejb.MessageDrivenBean
extends
javax.ejb.EnterpriseBean interface
extends It is only a marker Interface java.io.Serializable 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.
Naming
H
Server B JNDI Initial Context
H
App Server
8
Home Interface
1
H
EIS DB MainFrames
4 6
RMI/IIOP Remote Interface
7 11
9 delegates request
Obj Stub
we have written
We will write only this Container manages TRANSACTIONS, PERSISTENCE, SECURITY & POOLING
Copyright 2004 Kanti Prasad All rights reserved
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
C
Copyright 2004 Kanti Prasad All rights reserved
End
App Server
EJB Container
EJB Home or EJB Local Home Session Bean instance e.g Bank teller Credit Card authorization
Application Client
RMI/ IIOP
JMS Destination
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.
The setSessionContext method is used to inform the bean about the session context
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
setSessionContext() ejbCreate()
Pool of equivalent method ready instances Client called another Transactional business method on the EJB Object.
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
Containers limit of instantiated beans are reached, so it must swap your bean out.
ejbPassivate()
Bean instance is in the passive state
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.
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.
Network
EJB Pool
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
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
App Server
CLIENT Network CLIENT EJB
EJB Container
EJB
DB
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()
Client called remove() on the EJB object (this will destroy Database data)
ejbPostCreate()
ejbLoad()
ejbPassivate()
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
EJB Client
LocalHome Local
Network
EJB Pool
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
newInstance()
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()
Client called remove() on the EJB object (this will destroy Database data)
ejbPostCreate()
ejbLoad()
ejbPassivate()
Ready
ejbStore()
Container determined that the database is out of Synch with the bean. The Bean needs to store its Data into the Database
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 Copyright 2004 Kanti Prasad All rights reserved
Message-Driven Bean
Message Queue Message
Handler Logic
input
Network
Message Listener
EJB Pool
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
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.
javax.ejb.EJBLocalHome javax.ejb.EJBLocalObject
reference to EJBHome object Home, component interface and primary key classes functions to determine bean type
53. Exceptions
System exceptions are unchecked and propagated to the client as java.rmi.RemoteException Application exceptions are checked and propagated to the client as a descendant of java.lang.Exception EJB-specific exceptions include FinderException, CreateException, RemoteException (all in javax.ejb package) Business method exceptions are at the discretion of the EJB developer
1 5 2
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.
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.
Javax.ejb.EnterpriseBean
Javax.ejb.SessonBean
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.
This method creates/manufactures the EJBObject and returns it . This create() method corresponds to the ejbCreate() method in HelloBean. As for every Interface we need implementation,Note so Container implement (autogenerate code) for Remote this Home Interface for us, which is the EJBHome Object In Home will Interface we are throwing 2 exceptions and Create .
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
package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon import javax.ejb.EJBLocalHome; import javax.ejb.CreateException; import javax.ejb.FinderException; import java.util.Collection;
Our interface HelloLocalHome is extending EJBLocalHome means it has all the behaviour of EJBLocalHome
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 java.util.*; Importing the required files import javax.ejb.EJBObject; import java.rmi.RemoteException; public interface Hello extends javax.ejb.EJBObject Our interface Hello is extending EJBObject means it has all the behaviour of EJBObject { public String hello() throws java.rmi.RemoteException; As our requirement wants a business logic to greet Hello World a single method would be sufficient . } Interface methods should end with a semicolon ;
NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.
package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon import javax.ejb.EJBLocalObject; public interface HelloLocal extends javax.ejb.EJBLocalObject Our interface Hello is extending EJBLocalObject means it has all the behaviour of EJBLocalObject { 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.
package examples ; Rules of Java says package declaration should be at the beginning and ends with a semi colon import java.util.*; Importing the required files import javax.ejb.*; public class HelloBean implements javax.ejb.SessionBean NOTE : Note If it is: Entity this is Bean a class we and will not implement an Interface javax.ejb.EntityBean like the other two and (Home if it is /Message Remote). driven This is bean implementing we will implement SessionBean javax.ejb.MessagedrivenBean so it is a Session Bean As per the below note in red we need to write all the methods what are in javax.ejb.SessionBean . { private SessionContext This ctx; ejbCreate() corresponds to the Homeobject Create(). NOTE : in Stateless Bean no arguments are sent public void ejbCreate() { System.out.println(ejbCreate()); } much to clean up. public void ejbRemove() { System.out.println(ejbRemove());} There is nothing These are called Management or In Statelss Bean ejbActivate public void ejbActivate() { System.out.println(ejbActivate());} Call back methods and ejbPassivate Do not apply public void ejbPassivate() { System.out.println(ejbPassivate()); } public void setSessionContext(javax.ejb.SessionContext ctx) { Storing the Context in a variable so that it can be queried later . this.ctx = ctx; } NOTE : Because it is a Session Bean we are using setSessionContext for Entity Bean we use setEntityContext and for Message Driven Bean we use setMessageDrivenContext. public String hello() { System.out.println(Hello()); return Hello World! ; } Our Business method which matches } our Remote Interface method signature Java does not support multiple inheritance so you can extend only one class. To overcome
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.
As a Bean provider we need to specify the Middleware needs through this descriptor.
<!DOCTYPE ejb-jar PUBLIC -//Sun Microsystems, Inc. // DTD Enterprise JavaBeans 2.0 // EN http://java.sun.com.dtd/ejb-jar_2_0.dtd> XML Standard requirement <ejb-jar> <enterprise-beans> <session> The nickname for this particular Bean <ejb-name> Hello </ejb-name> <home>examples.HelloHome</home> The fully qualified name of the Home Interface <remote>examples.Hello</remote> The fully qualified name of the Remote Interface <local-home>examples.HelloLocalHome</local-home> The fully qualified name of the Local HomeInterface <local>examples.HelloLocal</local> The fully qualified name of the Local Interface <ejb-class>examples.HelloBean</ejb-class> The fully qualified name of the EJB Class <session-type>Stateless</session-type> Whether the session bean is stateful or stateless <transaction-type>Container</transaction-type> </session> </enterprise-beans> </ejb-jar>
Copyright 2004 Kanti Prasad All rights reserved
Properties File
Remote/Local Interface
HomeLocalHome Interface
Jar Creator
Jar file
Deployment Descriptor
Jar Manifest
DEPLOYED
Deployment Descriptor
.WAR
Deployment Tool WEB ARCHIEVE (.war) WEB.XML Enterprise Archive (.EAR Files) (Application.XML) JSP Servlets HTML
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 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
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
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 {
CartBean Class is implementing sessionbean means this bean class is a session bean
String customerName; String customerId; Vector contents;
We defined this also method in the Cart interface. person) method This represents the remote Home create(String
public void ejbCreate(String person) throws CreateException { if (person == null) { throw new CreateException("Null person not allowed."); } else { customerName = person; } customerId = "0"; contents = new Vector(); }
as this is the Bean class we will implement the business logic here
NOTE : AS we are implementing and not extending we need to write all the methods that are there in the Sessionbean
Copyright 2004 Kanti Prasad All rights reserved
a vector
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
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 = initial.lookup("java:comp/env/ejb/SimpleCart");
a class
We defined booklist as a vector After storing in the variable title we are printing it
System.exit(0);
using the bean class method removeBook through remote interface Cart as we defined it this way Cart shoppingCart = home.create("Duke DeEarl","123");
} catch (BookException ex) { System.err.println("Caught a BookException: " + ex.getMessage()); System.exit(0); We had written a new class BookException } catch (Exception ex) { System.err.println("Caught an unexpected exception!"); ex.printStackTrace(); System.exit(1); } } }
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); } }
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; } }
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
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
75. 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 [email protected], [email protected] He likes to hear your feed back!
76. References
Application Server Information , EJB Documentation & Tutorials are found here Notes on Deploying on different Application Servers. The Art of EJB Deployment http://www.javaworld.com/javaworld/jw-08-2001/jw-0803-ejb.html Most of EJBs related information can be seen at http://www.volantec.biz/ejb.htm http://www.theserverside.com/ Mastering Enterprise Java Beans by Ed Roman , Scott Ambler & Tyler Jewel. EJB Documentation http://java.sun.com/products/ejb/javadoc-2_0-fr/ http://my.execpc.com/~gopalan/java/java_tutorial.html Application Servers download information . Most of them are either free or have a 60 day trial version For JBOSS Open Source go to http://www.jboss.org/downloads/index http://www.kevinboone.com/jboss_tut_1.html SUNs downloads and examples
http://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 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 WebSphere downloads and examples http://www-306.ibm.com/software/webservers/appserv/doc/v20dcadv/doc/howto/ep001.html REDHAT Application Server and Examples http://www.redhat.com/docs/manuals/rhaps/jonas-guide/
Copyright 2004 Kanti Prasad All rights reserved