j2ee ejb

112
1/112 5/8/2022 SCBCD FOR J2EE 1.3 (CX-310-090) - CONTENTS INTRODUCTION.......................................................... 3 SOA and Web Services..................................................................................................................... 3 EJB Ecosystem.................................................................................................................................. 3 J2EE Technologies............................................................................................................................ 4 Java RMI-IIOP................................................................................................................................... 4 JNDI................................................................................................................................................... 6 Integrating RMI-IIOP and JNDI...................................................................................................... 8 EJB Fundamentals........................................................................................................................... 8 Middleware...................................................................................................................................... 8 EJB Object......................................................................................................................................... 8 Remote Interface............................................................................................................................. 9 Home Interface and Object............................................................................................................ 9 Local Interface............................................................................................................................... 10 Deployement Descriptor............................................................................................................... 11 SESSION BEANS........................................................ 11 Lifecycle.......................................................................................................................................... 11 Stateful Session Beans.................................................................................................................. 13 Stateless Session Beans................................................................................................................ 13 Comparing Stateful and Stateless Session Beans...................................................................... 13 Remote Interface:.......................................................................................................................... 14 Local Interface:.............................................................................................................................. 14 Home Interface:............................................................................................................................. 15 Local Home Interface.................................................................................................................... 16 Session Bean Class........................................................................................................................ 16 EJB Context..................................................................................................................................... 16 Deployement Descriptor............................................................................................................... 17 EJB Jar file....................................................................................................................................... 18 Client code..................................................................................................................................... 18 To Remember….............................................................................................................................. 20 WEBSERVICES USING STATELESS SESSION BEANS............................20 WSDL.............................................................................................................................................. 21 ENTITY BEANS......................................................... 24 Load and Store.............................................................................................................................. 25 Types.............................................................................................................................................. 25 Create and Remove....................................................................................................................... 25 Entity Context................................................................................................................................ 26 getPrimaryKey() :........................................................................................................................... 26 Finder methods:............................................................................................................................ 26 BEAN MANAGED PERSISTENT (BMP) ENTITY BEANS...........................27 BMP ENTITY BEAN WITH LOCAL INTERFACE.....................................28 Local interface............................................................................................................................... 28 © 2006, Watsh Rajneesh. All Rights Reserved.

Upload: watsh-rajneesh

Post on 14-Oct-2014

2.386 views

Category:

Documents


2 download

DESCRIPTION

EJB 2.1 Notes

TRANSCRIPT

1/86

2/9/2008

SCBCD FOR J2EE 1.3 (CX-310-090) - CONTENTS INTRODUCTION..........................................................................................................................................3 SOA and Web Services............................................................................................................................3 EJB Ecosystem........................................................................................................................................3 J2EE Technologies..................................................................................................................................4 Java RMI-IIOP.......................................................................................................................................5 JNDI........................................................................................................................................................6 Integrating RMI-IIOP and JNDI............................................................................................................8 EJB Fundamentals..................................................................................................................................8 Middleware.............................................................................................................................................8 EJB Object..............................................................................................................................................9 Remote Interface.....................................................................................................................................9 Home Interface and Object.....................................................................................................................9 Local Interface......................................................................................................................................10 Deployement Descriptor.......................................................................................................................11 SESSION BEANS.........................................................................................................................................11 Lifecycle................................................................................................................................................11 Stateful Session Beans..........................................................................................................................13 Stateless Session Beans.........................................................................................................................13 Comparing Stateful and Stateless Session Beans.................................................................................13 Remote Interface:..................................................................................................................................14 Local Interface:....................................................................................................................................14 Home Interface:....................................................................................................................................15 Local Home Interface ..........................................................................................................................16 Session Bean Class...............................................................................................................................16 EJB Context..........................................................................................................................................17 Deployement Descriptor.......................................................................................................................17 EJB Jar file...........................................................................................................................................18 Client code............................................................................................................................................19 To Remember.....................................................................................................................................20 WEBSERVICES USING STATELESS SESSION BEANS......................................................................20 WSDL....................................................................................................................................................21 ENTITY BEANS...........................................................................................................................................24 Load and Store......................................................................................................................................25 Types ....................................................................................................................................................25 Create and Remove...............................................................................................................................25 Entity Context ......................................................................................................................................26 getPrimaryKey() : ................................................................................................................................26 Finder methods:....................................................................................................................................26 BEAN MANAGED PERSISTENT (BMP) ENTITY BEANS..................................................................27 BMP ENTITY BEAN WITH LOCAL INTERFACE.......................................................................................................28 Local interface......................................................................................................................................28 Local Home Interface...........................................................................................................................29 Primary Key class.................................................................................................................................29 Custom Exception (Application Level).................................................................................................30 Entity Bean Class..................................................................................................................................30 Deployment Descriptor.........................................................................................................................36 Client Code...........................................................................................................................................38 CONTAINER MANAGED PERSISTENT (CMP) ENTITY BEANS.....................................................41

2006, Watsh Rajneesh. All Rights Reserved.

2/86

2/9/2008

Abstract Persistence Schema................................................................................................................42 EJB QL .................................................................................................................................................42 ejbSelect() only in CMP.....................................................................................................................42 Bean Class Code...................................................................................................................................44 Deployment Descriptor.........................................................................................................................47 MESSAGE DRIVEN BEAN........................................................................................................................48 Java Messaging Service (JMS).............................................................................................................49 Messaging Domains..............................................................................................................................49 JMS Programming Model.....................................................................................................................50 Bean class.............................................................................................................................................52 Client (Message Producer)...................................................................................................................53 Deployment Descriptor.........................................................................................................................55 EJB ENVIRONMENT & BEST PRACTICES..........................................................................................60 EJB References.....................................................................................................................................61 Resource Factories...............................................................................................................................62 Environment Properties........................................................................................................................63 EJB Object Handles..............................................................................................................................63 Home Handles......................................................................................................................................64 TRANSACTIONS.........................................................................................................................................66 Transaction Jargons.............................................................................................................................67 Transactional Models...........................................................................................................................67 Transaction Attributes...........................................................................................................................69 Java Transaction API (JTA)..................................................................................................................72 Transaction Isolation............................................................................................................................74 Durability and Two phase commit protocol..........................................................................................75 SECURITY....................................................................................................................................................76 EJB TIMER SERVICE................................................................................................................................77 RELATIONSHIP BETWEEN ENTITY BEANS......................................................................................77 Cardinality............................................................................................................................................77 Directionality........................................................................................................................................83 Aggregation vs Composition and Cascading Deletes...........................................................................84 EJB INTEGRATION (JCA)........................................................................................................................85 EJB PERFORMANCE TUNING...............................................................................................................85 CLUSTERING..............................................................................................................................................86 SAMPLE APPLICATION...........................................................................................................................86

Revision # 0.1

Date 16th May, 2006

Changes Initial Version.

Disclaimer: This document is my notes taken from the book Mastering EJB 3rd Edn. by Ed Roman et al and Head First EJB by Kathy Sierra and Bert Bates. This document covers more than the syllabus for the SCBDC exam and is well suited for revising the concepts of EJB 2.0 and 2.1.

2006, Watsh Rajneesh. All Rights Reserved.

3/86

2/9/2008

IntroductionEJB is about rapid application development for the server side; you can quickly and easily construct server-side components in Java by leveraging a prewritten distributed infrastructure provided by the industry. EJB is designed to support application portability and reusability across any vendors enterprise middleware services.

SOA and Web ServicesA service-oriented architecture (SOA) thus is a paradigm focusing on development of services rather than piecemeal components such that these services provide a higher level of abstraction from a functional standpoint. Of course, there are more properties to SOA than mere coarsegranularity. One such characteristic property of SOA is that they are autonomous in nature. These independent entities can interact with others in spite of differences in the way they have been implemented or the platform they have been deployed on. The notion of putting together (integrating) such autonomous and loosely coupled services to address the changing business needs has a huge value proposition and it is well on its way to realization with the emergence of various choreography, orchestration and collaboration technologies such as WS-BPEL, EbXML BPSS, and WS Choreography. SOA is a paradigm. There are many possible ways of building software so that it implements salient features of SOA, mainly coarse granularity and loose coupling. One such way is Web services. Simple Object Access Protocol (SOAP) is an XML-based application-level protocol intended for exchanging information in a distributed network. SOAP supports both the models of distributed computing: RPC as well as document style messaging. RPC style SOAP allows remote invocation of operations. Parameters and return in/out values of these operations are serialized in XML. Whereas, in document-style SOAP because an operations input and output are XML, serialization of parameters and return value to XML is not needed. Web Service Description Language (WSDL) is an XML-based metadata standard that is used to describe the service interfacein terms of the operations it supports, the parameters that the operations accept, and their return values in case of SOAP RPC, the XML schema that the input and output messages to the operations in case of document-style SOAPas well as service binding information in terms of the communication protocols, ports, service URL, and so on. SOA is not a replacement for component architecture; rather it neatly complements the component architecture. While component architectures enhance reusability at a finer grain level, SOA can enhance reusability at a coarser grained level. Hence, from an implementation standpoint, a given service might very well be developed using well-defined component frameworks such as EJB. The latest EJB standard, therefore, has in-built support for Web Services, the most popular stack for building SOA.

EJB EcosystemBean Provider (Internal department providing EJBs to other departments Developers writing the EJBs.

2006, Watsh Rajneesh. All Rights Reserved.

4/86

2/9/2008

or third party vendor). Application Assembler (System integrators, a consulting firm or inhouse programmer.)

Assemble the beans to make an application. Supply a UI (standalone or web based) or webservice. Write new EJB to solve application specific problem. Code that conncets the EJBs provided by bean providers with the application code.

EJB Deployer (a staff person, a vendor or consultant).

System Administrator

Server Provider (BEA, IBM, JBoss(now Redhat)). Tools Vendor (BEA Weblogic Provide IDEs to build/debug EJBs. Workshop, IBM Websphere Application Studio, Eclipse, Netbeans, IntelliJ IDEA). Bean provider, application assembler and deployer could be the same person for small companies.

Securing deployement within h/w or s/w firewall. Integrating with enterprise security and policy repositories, which oftentimes is an LDAP server Choosing h/w to host the application. Providing redundant h/w for clustering. Performance tuning the system (by modifying the deployement descriptors). Oversee the stability of operational system. Upkeep and monitoring of deployed system making use of management tools that the EJB server provides (JMX console of JBoss) or Weblogic AS provides SNMP manageability. Provides EJB container (Application Server).

J2EE TechnologiesEJB 2.1 JAX-RPC RMI-IIOP JNDI JTA & JTS JMS Defines how server side components are written and provides a standard contract between components and application server (container). Support for developing Webservices. Defines two webservices endpoint models: one based on servlet and other based on stateless session EJB. Extension of RMI for CORBA integration. Used to access naming and directory systems such as Microsoft Exchange or Lotus Notes. Allow for components to be bolstered with transaction support. Allows for J2EE deployement to communicate using messaging within and outside the J2EE system. You can connect to existing MOM (message oriented middleware IBM MQSeries or MS MQ). Messaging is an alternative to RMI-IIOP. Enable J2EE systems to access existing EIS such as mainframe systems running high-end transactions (like IBM CICS, BEA TUXEDO), ERP systems or prorietary systems. ISVs such as SAP, Siebel, PeopleSoft (now Oracle) who want their software to be accessible from within J2EE application servers can write standard J2EE connectors which will act similar to JDBC service provider jars. API for parsing XML documents. Is implementation neutral interface to XMP parsing technologies such as DOM and SAX. So you can plugin a DOM/SAX parser implementation like Xerces for Java and use Xerces from JAXP APIs.

JCA

JAXP

2006, Watsh Rajneesh. All Rights Reserved.

5/86

2/9/2008

JAAS

Standard API for performing security related operations.

Java RMI-IIOPRMI-IIOP is special version of RMI that is compliant with CORBA and uses both java.rmi and javax.rmi. RMI-IIOP lacks some features present in RMI like: Distributed garbage collection. Object activation. Downloadable class files. RMI-IIOP supports both pass-by-reference and pass-by-value models. Following are the steps to build an RMI-IIOP application: 1. When using RMI-IIOP you must build a custom interface called Remote Interface which extends java.rmi.Remote.import java.rmi.Remote; import java.rmi.RemoteException; /** * The remote interface for the remote object. Clients use this * remote interface to perform any operations on the remote object. */ public interface IPKGenerator extends Remote { public long generate() throws RemoteException; }

2.

To make your object available as a remote object and allow remote hosts to invoke its methods, your remote class must either a. extend the javax.rmi.PortableRemoteObject class or b. in case your class already extends some other class then you can manually export your object so that it is available to be invoked on by remote hosts by calling javax.rmi.PortalRemoteObject.exportObject().import java.rmi.RemoteException; import javax.rmi.PortableRemoteObject; /** * The remote object which generates primary keys */ public class PKGenerator extends PortableRemoteObject implements IPKGenerator { /* * Our remote objects constructor */ public PKGenerator() throws Exception, RemoteException { /* * Since we extend PortableRemoteObject, the super * class will export our remote object here. */ super(); } /* * Generates a unique primary key */ public synchronized long generate() throws RemoteException { return i++; } private static long i = System.currentTimeMillis();

}

The remote object can be made unavailable for remote method invocation by calling javax.rmi.PortableRemoteObject.unexportObject().

2006, Watsh Rajneesh. All Rights Reserved.

6/86

2/9/2008

2. rmic compiler can be used to generate the stub and skeleton which are proxys responsible for3. 4. delegating the calls made to remote methods to their implementations. Passing parameters by value for object type requires the object type to be serializable. Passing object type parameters by reference is achieved when parameter object is itself a remote object. So when the client makes a remote method call on the server and passes a remote object reference of a remote object living on the client machine then the stub to that remote object reference is serialized (and not the whole object). So the server can connect to the remote object living on client machine and invoke methods on that. Java RMI-IIOP thus simulates the pass-byreference by passing serializable stub, rather than serializing the original object. So, by making your parameters remote objects, you can effectively avoid the network lag in passing large objects. Note: the Java RMI-IIOP stubs are serializable always. In summary, following are the rules for passing objects using Java RMI-IIOP: All Java primitives are passed by value when calling methods remotely. If you want to pass an object by value, it must implement java.lang.Serializable interface. Anything referenced from within the object must also be serializable. 3. If you want to pass an object by reference, it must be a remote object, and it must implement java.rmi.Remote interface. A stub for the remote object is serialized and passed to the remote host. A way to publish the server and have client locate the server is called bootstrapping and is achieved by JNDI. 1. 2.

JNDIJNDI provides standard inteface for locating users, machines, networks, objects and services by name. Example, locating a printer on the network by name, locating java object or locating a datasource to connect to a database. In J2EE the uses of JNDI are: 1. acquire a reference to the Java Transaction API (JTA) UserTransaction interface 2. connect to resource factories such as, JDBC drivers or JMS drivers. 3. for beans to lookup other beans. Naming service: Associates names with objects (binding names to objects). Provides a facility to find an object by name (resolving a name to an object reference). Example, filesystem (file name to file handle), DNS (machine name to IP address). A directory object is a special type of object stored with the naming service which can be used to store attributes. Eg. You can use a directory object to represent a user storing information about user, like user loginid, password, email, phone etc as its attributes. So your application can lookup the user credentials stored in the directory object of the naming service to authenticate the user. A directory service is a naming service enhanced to provide directory object operations for manipulating attributes. Eg, (MS Active Directory Service, Netscape Directory Server). Directory is a system of directory objects that are all connected in a hierarchical tree structure with a root representing your company as shown below:

2006, Watsh Rajneesh. All Rights Reserved.

7/86

2/9/2008

Most directories are implemented by a database behind the scene to store the hierarchical directory objects. There are several directory protocols for accessing a directory service eg. LDAP (Light weight directory access protocol) or Novells Network Directory System (NDS) or Network Information System (NIS). IBMs Lotus Notes and Microsoft Active Directory are both LDAP based. But not all directory services are LDAP based. JNDI is a bridge over naming and directory services providing common interface to disparate directories. Similar to JDBC, JNDI has two halves: 1. API allows clients to code to a single unified interface 2. SPI allows naming and directory service vendors to fit their particular proprietary protocols into the system. Like the database vendors provide JDBC drivers, directory service vendors provide JNDI service providers to access their specific directories. The providers are aware of specific directory protocols and they plugin to the JNDI SPI. LDAP service provider would know how to map JNDI client API to an LDAP operation. Service providers exist for LDAP, NIS, NDS, SLP, CORBA NS, File System, RMI-IIOP tnameserv, and many more. Application servers also ship JNDI naming service implementation.

Binding: associating name with an object. Context: set of zero or more bindings. Subcontext: is a full fledged context in its own right and can contain more name bindings. Naming system: is a connected set of contexts that use the same name syntax. (eg branch of LDAP tree or a folder tree in file system). Namespace: set of names contained within a naming system.

2006, Watsh Rajneesh. All Rights Reserved.

8/86

2/9/2008

Composite name: name that spans multiple naming systems. http://java.sun.com/products/ejb/index.jsp is composed of namespaces: o http: url scheme id namespace. o java.sun.com uses DNS to resolve to ip address o products/ejb/index.jsp: are from filesystem namespace on webserver. Initial Context: is starting point of exploring a namespace. (root node of the naming system).

Eg.

To acquire an initial context in JNDI, we use an initial context factory (implemented by JNDI service provider) which returns the initial context for the naming system. To get an initial context for a certain naming system you need to provide the following information about the naming system: o IP address of the naming system o Port number at which the naming service is listening o Starting location within the JNDI tree o User name and passwd for authenticating to the naming service (if applicable). Note: Naming graphs needed not be trees. They may have more than one root. Subcontexts can be bound in more than one context, so a single subcontext may be known under more than one name.

Integrating RMI-IIOP and JNDI1. 2. Binding RMI-IIOP Server to JNDI Looking up an RMI-IIOP server with JNDI

EJB FundamentalsSession Beans Entity Beans Message driven Beans Model business processes. Model business data. Can be called only implicitly by sending messages to those beans. Eg. Stock trade messages, credit card authorization messages, workflow messages.

MiddlewareWhen distributed system grows larger, we need to employ middleware services for transaction, security, persistence, etc. Explicit Middleware: involves purchasing a middleware off the shelf and writing code that calls the middlewares API. More like Bean managed transaction/persistence/security. Business logic gets intwined with the logic to call these middleware APIs. Example of such systems are: traditional CICS or TUXEDO based mainframe systems, CORBA, DCOM or RMI. Implicit/Declarative Middleware: New component based technologies like EJB, .NET and CORBA Component Model enable you to harness the complex middleware in enterprise applications without writing to the middleware APIs. More like Container Managed transaction/persistence/security. You just do the following: 1. Write distributed object business logic only. 2. Declare middleware services that your distributed object needs in separate descriptor files. 3. The application server will generate the request interceptor from the configuration obtained from the descriptor files. 4. Request interceptor will intercept requests from client, perform middleware services that your distributed object needs and then delegates the call to the distributed object.

2006, Watsh Rajneesh. All Rights Reserved.

9/86

2/9/2008

EJB ObjectEJB is not full fledged remote object. Clients never invoke the business method directly on actual bean instance. Rather, the EJB container intercepts the request, performs the implicit middleware and delegates to the bean instance. EJB container handles networking for you by wrapping your bean in a network enabled object. Middleware services at the point of interception include: 1. Transaction service 2. Security service 3. Resource management: for resources like threads, database connections etc. 4. Lifecycle management of the beans: pooling the beans, activating/passivating etc. 5. Persistence service 6. Handle concurrent requests either by allowing serial access to the bean instance or allowing other bean instances in the pool to service the request. Thus, EJB container acts as a layer of indirection between client and the bean by providing a network aware wrapper object called EJB Object. EJB Object is the request interceptor. They have container specific code inside them (each container handles middleware differently). EJB Object class file is generated automatically by the container.public interface javax.ejb.EJBObject extends java.rmi.Remote { public javax.ejb.EJBHome getEJBHome() throws java.rmi.RemoteException; public java.lang.Object getPrimaryKey() throws java.rmi.RemoteException; public void remove() throws java.rmi.RemoteException, javax.ejb.RemoveException; public javax.ejb.Handle getHandle() throws java.rmi.RemoteException; public boolean isIdentical(javax.ejb.EJBObject) throws java.rmi.RemoteException; }

Remote InterfaceFor the container to know what business methods have to made remote you will need to provide a Remote interface which mentions all business methods that bean class exposes. Your remote interface extends the javax.ejb.EJBObject interface mentioning all business methods of your bean. When a client invokes any of these business methods, the EJBObject delegates the method to its corresponding implementation, which resides in the bean itself. So the container provided EJBObject concrete implementation implements the Remote interface we create and provides an implementation for the methods in the javax.ejb.EJBObject interface plus implementation of the business methods which simply call the business method implementation in your bean class. java.rmi.Remote extended by javax.ejb.EJBObject extended by Remote Container generated concrete class might look like this: class EJBObjectImpl implements Remote { // override all methods in javax.ejb.EJBObject // override all methods in Remote // provide middleware services based on confign. in deployement descriptor implicit middleware // delegate the call to methods. }

Home Interface and ObjectTo acquire a reference to an EJB object, your client code asks for an EJB object from an EJB object factory. This factory is resposible for instatiating and destroying EJB objects. This factory is the Home object.

2006, Watsh Rajneesh. All Rights Reserved.

10/86

2/9/2008

Home object is generated by the container and implements the Home interface where you provide information to the container about how your bean instance has to be initialized while instantiating. Even instantiation of the bean will be done via the EJB object instance.public interface javax.ejb.EJBHome extends java.rmi.Remote { public EJBMetaData getEJBMetaData() throws java.rmi.RemoteException; public javax.ejb.HomeHandle getHomeHandle() throws java.rmi.RemoteException; public void remove(javax.ejb.Handle handle) throws java.rmi.RemoteException, javax.ejb.RemoveException; public void remove(Object primaryKey) throws java.rmi.RemoteException, javax.ejb.RemoveException; }

java.rmi.Remote extended by javax.ejb.EJBHome extended by Home Container generated Home object concrete implementation will be: class HomeImpl implements Home { // override methods in javax.ejb.EJBHome interface // override methods in Home interface // delegating calls for create/find/remove to corresponding EJB object // EJB object in turn delegates to bean instance // if create invokes the bean constructor or picks one bean from the instance pool // if find invokes the corresponding entity beans finder method // if remove reinits the state of bean and returns it to instance pool } Note: Most containers will have a 1:N relationship between home objects and bean instances. This means that all clients use the same home object instance to create EJB objects. So a home object will be implemented by container to be thread safe code as it has to service multiple clients. Your beans will always be single threaded (ie only one thread at a time will execute methods of a certain bean instance). Relationship between EJB objects and bean instances may be 1:N (as home objects) or M:N. In the former case, the EJB object will be single and so will be thread safe. In the later case, there will be as many EJB objects as there are active client connections (so EJB objects will be single threaded).

Local InterfaceLocal objects implement local interfaces. Avoids the networking overhead.public interface javax.ejb.EJBLocalObject { public javax.ejb.EJBLocalHome getEJBLocalHome() throws javax.ejb.EJBException; public Object getPrimaryKey() throws javax.ejb.EJBException; public boolean isIdentical(javax.ejb.EJBLocalObject) throws javax.ejb.EJBException; public void remove() throws javax.ejb.RemoveException, javax.ejb.EJBException; } public interface javax.ejb.EJBLocalHome { public void remove(java.lang.Object) throws javax.ejb.RemoveException, javax.ejb.EJBException; }

javax.ejb.EJBLocalObject extended by Local and

2006, Watsh Rajneesh. All Rights Reserved.

11/86

2/9/2008

javax.ejb.EJBLocalHome extended by LocalHome Note: Local interface always marshall parameters by reference.

Deployement DescriptorThis is the key to implicit middleware. It is used to inform the container about your middleware needs, you as a bean provider must declare your components middleware service requirements in this file. Bean Management and How container should manage your beans. lifecycle requirements o name of bean class o type of bean (Session, Entity or MDB) o home interface that generates the beans o local or remote Persistence requirements Whether bean or container managed persistence. (Entity beans only) Transaction requirements Requirements for running in transactions Transaction must start whenever anyone calls a bean (Required New) Transaction may start whenever there is no running transaction (Required) etc Security requirements Access control entries Who is allowed to use which beans Who is allowed to use each method on a particular bean Vendor Specific files can be used to configure load balancing, clustering, monitoring, pool sizes etc. EJB-jar file = bean classes + home interfaces + remote interfaces + deployement descriptor.

Session BeansSession beans are business process objects that implement business logic and workflows. Eg. Price quoting, order entry, video compression, banking transactions, stock tradesm database operations, complex calculations etc.

LifecycleLifetime is equivalent of a client session. Session bean instances are not shared between clients. EJB container may destroy the session bean if client times out. Session beans are non persistent (not saved to database). Stateless bean lifecycle: 1. Bean instance does not exist 2. container decides it wants to instantiate a new bean (depends on containers policy for pooling beans) 3. container instantiates your bean : container calls class.newInstance(HelloBean.class) on your session bean class. 4. container calls setSessionContext() : associating a bean with context which enables it to make callbacks to container. 5. container calls ejbCreate() : initializes your bean. 6. container can call business methods on your bean : container can dynamically reassign beans to client requests at the per-method level. 7. container calls ejbRemove().

2006, Watsh Rajneesh. All Rights Reserved.

12/86

2/9/2008

Lifecycle of stateful session bean is similar to that of stateless session bean, except: 1. there is no pool of equivalent instances because each instance contains state. 2. there are transitions for passivating and activating conversational state.

2006, Watsh Rajneesh. All Rights Reserved.

13/86

2/9/2008

Stateful Session BeansDesigned to service business processes that span multiple method requests or transactions. They retain the state on behalf of an individual client. Eg. E-commerce web store and shopping cart. To limit the number of stateful session bean instances in memory, the container can swap out a stateful bean, saving its conversational state to a hard disk (passivation). At passivation time the container uses object serialization to save state of bean (javax.ejb.EnterpriseBean interface extends java.io.Serializable interface so every enterprise bean implements this interface). When the original client invokes a method, the passivated conversational state is swapped in to a bean (activation) which then resumes conversation with the original client. The bean that receives the activated state may not be the original bean instance that was passivated. Containers may choose to passivate a bean that has been used least recently (LRU). Passivation can occur anytime if the bean is not involved in a method call or is not a part of a transaction. Beans are activated on-demand (as client request comes in). Thus, using passivation/activation, the EJB container provides effect of instance pooling stateful session beans. ejbPassivate() relinquish held resources like database connections, open sockets, open files. ejbActivate() restore the open resources it released during ejbPassivate(). Note: in most cases you leave these methods empty. But you may implement them if you do have transient resources which you donot want to save like socket connections, open files, database connections etc which you have stored in private member instance variables but that does not make sense to serialize everytime with the object state.

Stateless Session BeansDesigned to service business processes that span a single method call. The client must pass all client data that the bean needs as parameters to business logic methods. Eg. High-performance engine that solves complex mathematical operations in a given input, such as compression of audio/video data (client passing the buffer of uncompressed data and a compression factor) or a credit card verification component (where client passes the card number, expiry date, holders name and amount to debit as input parameters). Note: 1. Stateless session beans can contain state that is not specific to any one client, such as database connection factory that all clients would use. Any stateless bean can service any client request because they are all exactly same. So stateless session beans can be pooled and reused. Passivation/activation are not required as there isnt any state to save. Stateless session beans can also be webservice endpoints.

2.3.

Comparing Stateful and Stateless Session BeansMethod setSessionContext() ejbCreate() Stateful implementation Stateless Implementation Store the context away in a member variable so that context can be queried later. Perform any initialization your bean needs Perform any initialization. such as setting member variables to the argument values passed in. You can only define an empty You can define several overloaded ejbCreate() method (with no ejbCreate() methods, each taking a different parameters). If it had params and argument. Atleast one ejbCreate() method the bean initialized itself to those MUST be provided. params the bean would never remember what it initialized itself to upon subsequent calls, since its stateless!

2006, Watsh Rajneesh. All Rights Reserved.

14/86

2/9/2008

ejbPassivate() ejbActivate() ejbRemove()

Release resource which are transient or you Not Applicable. dont want serialized on passivation. Acquire resources release while passivation. Not Applicable. Prepare for destruction by releasing resources if any.

Remote Interface:/** * This is the HelloBean remote interface. * * This interface is what clients operate on when * they interact with EJB objects. The container * vendor will implement this interface; the * implemented object is the EJB object, which * delegates invocations to the actual bean. */ public interface Hello extends javax.ejb.EJBObject { /** * The one method - hello - returns a greeting to the client. */ public String hello() throws java.rmi.RemoteException; }

Local Interface:/** * This is the HelloBean local interface. * * This interface is what local clients operate * on when they interact with EJB local objects.

2006, Watsh Rajneesh. All Rights Reserved.

15/86

2/9/2008

* The container vendor will implement this * interface; the implemented object is the * EJB local object, which delegates invocations * to the actual bean. */ public interface HelloLocal extends javax.ejb.EJBLocalObject { /** * The one method - hello - returns a greeting to the client. */ public String hello(); }

Home Interface:/** * This is the home interface for HelloBean. This interface * is implemented by the EJB Servers tools - the * implemented object is called the Home Object, and serves * as a factory for EJB Objects. * * One create() method is in this Home Interface, which * corresponds to the ejbCreate() method in HelloBean. */ public interface HelloHome extends javax.ejb.EJBHome { /* * This method creates the EJB Object. * * @return The newly created EJB Object. */ Hello create() throws java.rmi.RemoteException, javax.ejb.CreateException; }

create() is the factory method that clients use to get a reference to the EJB Object and it initializes the bean. Since a remove() method is already there in the EJBHome interface so we donot need to provide that in our home interface. Note: create() and remove() are for creation and destruction of an EJB object. The bean instance may not be destroyed on a remove() or may not be created on create() (rather be dequed from the pool on create() and returned to the instance pool on remove). Types of Exceptions thrown by bean: A remote exception indicates a special error condition a network failure, machine failure etc. 1. System level exception critical failure eg database malfunction 2. Application level exception routine exception eg bad parameter passed to remote method, warning of an insufficient bank account balance to make withdrawl etc. EJB container can intercept exceptions and decide whether a client should be shown the exception. If a bean fails it may be possible to salvage the clients invocation and redirect to another bean transparent fail over. 1. A system level exception is thus intercepted by container and may not be shown to the client. 2. If the failure is fatal then the container can alert the system admin via a monitoring system like sending an snmp trap/ jmx event which system admin can observe in his monitoring application. 3. EJB object is also responsible for catching all unchecked exceptions that your bean may throw (such as NullPointerException) which are typically not handled in the bean code. EJB object then may throw such an unchecked exception back to the client as a remote exception. In summary, 1. Application level exceptions are always thrown back to client. This includes any exception that bean defines and javax.ejb.CreateException or javax.ejb.FindException. 2. For system level exceptions, EJB container can handle the exception and

2006, Watsh Rajneesh. All Rights Reserved.

16/86

2/9/2008

3.4.

a. Inform the system admin with an alert b. Send an email to third party c. Throw exception back to client. Your bean can throw a system level exception as either a java.rmi.RemoteException or an unchecked RuntimeException. If container throws this exception back to client then its always thrown as a RemoteException or a subclass of it. Exceptions also impact transactions.

Local Home Interface/** * This is the local home interface for HelloBean. * This interface is implemented by the EJB Servers * tools - the implemented object is called the * local home object, and serves as a factory for * EJB local objects. */ public interface HelloLocalHome extends javax.ejb.EJBLocalHome { /* * This method creates the EJB Object. * * @return The newly created EJB Object. */ HelloLocal create() throws javax.ejb.CreateException; }

Session Bean Class/** * Demonstration stateless session bean. */ public class HelloBean implements javax.ejb.SessionBean { private SessionContext ctx; // // EJB-required methods // 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; } // // Business methods // public String hello() { System.out.println(hello()); return Hello, World!; }

}

2006, Watsh Rajneesh. All Rights Reserved.

17/86

2/9/2008

EJB ContextInside the bean you may want to access the security credential of the user currently calling your beans method. Container holds all this information in an EJB Context object. So a context represents a way for a bean to perform callbacks to the container. EJB Context encapsulates the beans domain. The container is responsible for changing the context to reflect any status change, such as bean being involved in a new transaction. Context object state will dynamically change over time. The container associates your bean with a context by calling your setSessionContext() (or setEntityContext(), setMessageDrivenContext()). When you define each of these methods, you should store the context away in a member variable so that the context can be queried later.public interface javax.ejb.EJBContext { /* * Call these from within your bean to access * your own home object or local home object. * * You can use them to create, destroy, or * find EJB objects and EJB local objects * of your own bean class type. */ public javax.ejb.EJBHome getEJBHome(); public javax.ejb.EJBLocalHome getEJBLocalHome(); /* * These are transaction methods */ public boolean getRollbackOnly(); public void setRollbackOnly(); public javax.transaction.UserTransaction getUserTransaction(); /* * These are security methods */ public boolean isCallerInRole(java.lang.String); public java.security.Principal getCallerPrincipal();

}

public interface javax.ejb.SessionContext extends javax.ejb.EJBContext { public javax.ejb.EJBLocalObject getEJBLocalObject(); public javax.ejb.EJBObject getEJBObject(); }

Deployement Descriptorejb-jar.xml standard ejb deployement descriptor. HelloWorld HelloWorld HelloWorld examples.HelloHome examples.Hello examples.HelloBean Stateless

2006, Watsh Rajneesh. All Rights Reserved.

18/86

2/9/2008

Container

sun-ejb-jar.xml vendor specific file. 1 HelloWorld HelloHome

EJB Jar filejar cf HelloWorld.jar * The contents of jar file will look like this:

* examples is the package. You can generate the EJB Client jar file from the deploytool which includes classes that must be deployed for any clients of a particular EJB jar file. Start the Sun AS 8.1 PE as follows: asadmin start-domain domain1 Then browse to the url: http://localhost:4848 and login to the admin console. From there you can deploy the EJB jar file in EJB Modules section.

2006, Watsh Rajneesh. All Rights Reserved.

19/86

2/9/2008

Client codeimport javax.naming.Context; import javax.naming.InitialContext; import java.util.Properties; /** * This class is an example of client code that invokes * methods on a simple stateless session bean. */ public class HelloClient { public static void main(String[] args) throws Exception { /* * Setup properties for JNDI initialization. * * These properties will be read-in from * the command-line. */ Properties props = System.getProperties(); /* * Obtain the JNDI initial context. * * The initial context is a starting point for * connecting to a JNDI tree. We choose our JNDI * driver, the network location of the server, etc. * by passing in the environment properties. */ Context ctx = new InitialContext(props); /* * Get a reference to the home object - the * factory for Hello EJB Objects */ Object obj = ctx.lookup(HelloHome); /* * Home objects are RMI-IIOP objects, and so * they must be cast into RMI-IIOP objects * using a special RMI-IIOP cast. * */ HelloHome home = (HelloHome) javax.rmi.PortableRemoteObject.narrow( obj, HelloHome.class); /* * Use the factory to create the Hello EJB Object */ Hello hello = home.create(); /* * Call the hello() method on the EJB object. The * EJB object will delegate the call to the bean, * receive the result, and return it to us. * * We then print the result to the screen. */ System.out.println(hello.hello()); /* * Done with EJB Object, so remove it. * The container will destroy the EJB object. */ hello.remove();

}

}

To run the client: $ java -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory

2006, Watsh Rajneesh. All Rights Reserved.

20/86

2/9/2008

-Djava.naming.provider.url=corbaloc::localhost:3700/NameService examples.HelloClient Hello, World! We need to identify the initial context factory class in the naming service provider we use and the url for the root of the naming service.

To RememberIf your bean calls another beans method and wants to pass its referecence as a parameter, then you must pass a reference to your beans EJB object, rather than a reference to your bean ie passing this wont work rather use the context object and call sessionCtx.getEJBObject() to get a reference to your EJB object and pass that as a reference, where sessionCtx is the priavate variable where you stored the session context object in the body of setSessionContext(). Also to allow for compile time checks for your bean class whether it implements all the business methods or not, pull out the business methods into a separate interface which can be extends by your remote and local interfaces and that your bean class will implement.// Business interface public interface HelloBusinessMethods { public String hello() throws java.rmi.RemoteException; } // EJB remote interface public interface HelloRemote extends javax.ejb.EJBObject, HelloBusinessMethods { } // EJB local interface public interface HelloLocal extends javax.ejb.EJBLocalObject, HelloBusinessMethods { } // Bean implementation now checked at compile time for compliance with the business methods interface public class HelloBean implements SessionBean, HelloBusinessMethods { public String hello() { return Hello, World!; } }

Webservices using Stateless Session BeansWeb Services are a way of building a Service-Oriented Architecture (SOA). SOA is an architectural approach to structuring large-scale, distributed applications that integrate heterogeneous applications behind service interfaces. A service provider creates an abstract service definition that it publishes in a service registry. With Web Services, the description is a Web Services Definition Language (WSDL) file, and the registry follows the Universal Description, Discovery, and Integration (UDDI) standard. A service requestor can find the service description, possibly using a set of selection criteria to query the registry. If a suitable description is found, the requestor can bind to the service. SOAs emphasize modularity through standardized interfaces, flexibility through looser coupling, and extensibility through using XML. All of this is important in the B2B scenarios, which are the primary targets of Web Services.

2006, Watsh Rajneesh. All Rights Reserved.

21/86

2/9/2008

Web Services = WSDL + SOAP + UDDI

WSDLwscompile tool to generate WSDL from Java interface. Webservices are managed by container. JSR921 defines the programming model for webservices. It defines a port component for the server-side view of a web service. It is a portable java implementation of a service interface (port) and comprises java mapping of the service interface and the implementation bean. Writing web service using EJB requires creating one or more port components as stateless session beans. After exposing the bean as a web service only repackaging and redeploying is required, which now contains a port component. The EJB container will know how to dispatch incoming SOAP messages to our bean implementation and how to map the incoming XML data types to Java. The way to implement the service endpoint in an existing bean is to define the business methods interface separately and have the remote intrerface and the bean class implement this interface (as described earlier to provide compile time checking of business methods being implemented in the bean class): package examples; /** * This is the Hello remote interface. * */ public interface HelloInterface extends java.rmi.Remote { /** * The one method - hello - returns a greeting to the client. */ public String hello() throws java.rmi.RemoteException; } The extends java.rmi.Remote is added to the new definition of Hello interface. Remember that this interface is extended by Hello remote interface (which also extends javax.ejb.EJBObject). This interface is also called the Service Endpoint Interface (SEI).

2006, Watsh Rajneesh. All Rights Reserved.

22/86

2/9/2008

Note: The bean class may not implement this interface explicitly but the business methods in the SEI must anyhow be implemented by the bean class. JAX/RPC defines a mapping between a set of supported Java types and WSDL/XML types. Java primitive types are directly supported by JAX/RPC. Some non primitive types supported are: Wrappers (Boolean, Integer, Character, etc), java.net.URI, java.util.Calendar, java.util.Date and java.lang.String. Generate a JAX-RPC mapping file and WSDL: $ wscompile.bat -classpath ./classes -define ./assemble/mapping.xml src/config.xml -d ./assemble -nd ./assemble mapping

Where, Config.xml: Config.xml defines the name of the service, the target namespace to use in the WSDL xml schema, the name of the SEI. Usage: wscompile [options] configuration_file -classpath -define -d -nd -mapping Specifies where to find input class files. Define a service Specifies where to place generated output files Specifies where to place non-class generated files Write the 109 mapping file to the given file

Following is the generated mapping file: examples urn:examples examples.HelloWorldWS serviceNS:HelloWorldWS HelloInterfacePort HelloInterfacePort

2006, Watsh Rajneesh. All Rights Reserved.

23/86

2/9/2008

examples.HelloInterface portTypeNS:HelloInterface bindingNS:HelloInterfaceBinding hello hello java.lang.String wsdlMsgNS:HelloInterface_helloResponse result Generate the client stub classes: $ wscompile.bat -classpath ./classes -gen:client -keep -d ./src/generated -nd ./classes src/config.xml warning: You have specified : -gen:both or -gen:client with a SEI. The use of these modes are recommended with WSDL only. Where, -keep Keep generated files -gen:client Generate client artifacts (stubs, etc). Create a webservices.xml Deployment descriptor: HelloService HelloWS META-INF/wsdl/HelloWorldWS.wsdl META-INF/wsdl/mapping.xml HelloWS HelloWS wsdl-port_ns__:HelloInterfacePort examples.HelloInterface HelloBean And package everything together in the ejb jar file as shown below:

2006, Watsh Rajneesh. All Rights Reserved.

24/86

2/9/2008

Deploy this jar in the usual way and access it at url ??. (This part will be completed after I have read the J2EE Webservices book).

Entity BeansEntity beans are persistent objects.public interface javax.ejb.EntityBean extends javax.ejb.EnterpriseBean { public void setEntityContext(javax.ejb.EntityContext); public void unsetEntityContext(); public void ejbRemove(); public void ejbActivate(); public void ejbPassivate(); public void ejbLoad(); public void ejbStore(); }

Object-Relational Mapping : Mapping of objects to relational databases. Eg of ORM products are Hibernate, Oracle TopLink, JDO etc. Entity beans can persist themselves in many ways, including Java serialization, O/R mapping, or even an object database persistence. O/R mappings are the most frequently used mechanism in practice. Two files constitute an entity bean: 1. entity bean class: maps to the entity definition in a database schema. 2. primary key class: is an object that may contain any number of attributes (like composite primary key). This could be any data necessary to identify uniquely an entity bean data instance. It must be serializable. Entity beans lifetime depends on how long the data sits in the database. Entity beans are generally accessed by other beans that run-in process (typically with a session faade in which case a session bean will access the entity bean). Clients (servlets/jsp/applets) invoke a method on the session faade and the session bean in turn calls the entity bean. Since the session and entity beans will be

2006, Watsh Rajneesh. All Rights Reserved.

25/86

2/9/2008

colocated in the same JVM process so the entity beans only expose local interface in production (and not remote).

Load and StoreejbLoad() : reads the data in from the persistent storage into the entity beans in-memory fields. ejbStore() : saves your bean instances current fields to the underlying data storage. The container automatically synchronizes the in-memory entity bean instance with the database record they represent by calling ejbLoad() and ejbStore() callbacks. There can be multiple in-memory entity bean instances which represent the same underlying data. The data corruption is prevented in such circumstances by synchronizing the beans with the underlying storage. The frequency of such synchronizations is determined by the transaction isolation level associated with the bean. If it is read-commited then two clients accessing the entity bean instances mapped to same data can read the data only when the modification to it has been saved/committed to the storage. An uncommitted data change will not be read. The container may pool and reuse the entity bean instances to represent different instances of the same type of data in the database (eg. Entity bean instance to represent different bank account records). Reassigning the entity bean instance to represent a different data record requires having to let the bean know to release any resource it held while mapping to the older data record. For this, entity bean class will need to implement ejbActivate() and ejbPassivate(). The container invokes ejbStore() before passivating the bean and invokes ejbLoad() after activating the bean.

TypesBean Managed Persistent entity beans require you to write code to translate your in-memory fields into an underlying data store. You need to provide implementations for ejbCreate(), ejbLoad(), ejbStore(), ejbFindXXX() and ejbRemove() methods using JDBC API. Container Managed Persistent entity beans requires you to provide the entity bean O/R mapping in the deployment descriptor and container generates the data access code.

Create and RemoveWhen an entity bean is initialized in memory during ejbCreate(), a new data record is inserted to the underlying database that correlates with the in-memory instance. ejbRemove() should then delete the data record from the database. Bean return a primary key to the container so that the container can identify the bean uniquely, upon ejbCreate() being called. On ejbRemove(), the database data associated with the bean is deleted and the bean is made inaccessible to the client. Client can call remove() method of either EJBObject or Home object.In bean class: public AccountPK ejbCreate(String accountID, String owner) throws... In home interface: public Account create(String accountID, String owner) throws ...

Home interface exposes finder methods in addition to create and remove methods. If you directly create/modify/delete the data by directly touching the database, the in-memory entity beans will be created (by just calling findByPrimaryKey() method on the home object for your bean), modified (upon automatic synchronization) and deleted. So its not necessary for an entity bean to have an ejbCreate() method as they can be created by directly touching the database.

2006, Watsh Rajneesh. All Rights Reserved.

26/86

2/9/2008

Entity ContextAn entity bean has a context object (which implements javax.ejb.EntityContext) via which it can query the container for its own transaction state and security information.public interface javax.ejb.EJBContext { public javax.ejb.EJBHome getEJBHome(); public javax.ejb.EJBLocalHome getEJBLocalHome(); public java.security.Principal getCallerPrincipal(); public boolean isCallerInRole(java.lang.String); public void setRollbackOnly(); public boolean getRollbackOnly(); } public interface javax.ejb.EntityContext extends javax.ejb.EJBContext { public javax.ejb.EJBLocalObject getEJBLocalObject(); public javax.ejb.EJBObject getEJBObject(); public java.lang.Object getPrimaryKey(); // new in entity context }

getPrimaryKey() :You call it whenever you want to figure out with which database data your instance is associated. Your entity bean must perform a getPrimaryKey() callback to the entity context to figure out what data it is dealing with. (Remember: entity beans can be pooled and reused to cater to different data records). In case of BMP, you will need to use it for the following method implementations: 1. ejbLoad() : when ejbStore() is called the bean has the knowledge of what data it holds but when the container calls its ejbLoad() it should first use getPrimaryKey() to know what data to be fetched from the database. 2. ejbRemove() : when ejbCreate() is called the bean knows what data to create as it has been passed to it in parameters to ejbCreate(). But while removing the data, you must call the getPrimaryKey() to find out what data to remove.

Finder methods:Are defined on local/remote home interfaces and implemented by your bean implementations to find one or more existing entity bean in storage. You must define atleast one finder method ejbFindByPrimaryKey(). For eg. You might perform a query as SELECT id FROM accounts WHERE balance > 10000 and return the primary keys for the resultset data back to the container by creating one or more primary key object instances. Container will then create EJB objects for the client to invoke on and possibly associate some entity bean instances with those EJB objects. public Collection ejbFindBigAccounts() throws FinderException { // } Collection is collection of primary keys. Container then creates a collection of EJB Objects one for each primary key in the collection, and returns those EJB Objects in its own collection to the client. 1. All finder methods must being with ejbFind. 2. Must have atleast one finder method ejbFindByPrimaryKey(). public AccountPK ejbFindByPrimaryKey(AccountPK key) throws FinderException { // } Note: You define finder methods only in case of BMP. For CMP, these method implementations are generated by container.

2006, Watsh Rajneesh. All Rights Reserved.

27/86

2/9/2008

Clients invoke finder methods on home objects. Entity bean instance returns a primary key to the container, whereas the home object returns an EJB Object to the client.

Bean Managed Persistent (BMP) Entity BeansYou are responsible to provide the implementation to map your entity bean instances to and from storage. To do this you either use: 3. JDBC API or 4. ORM framework Hibernate or Oracle TopLink. Steps to follow: 5. setEntityContext() store the entity context in a member varible. After this method executes, bean does not hold a data yet but is available in pool. 6. ejbFindXXX() as explained earlier. 7. ejbHomeXXX() methods on an entity bean that are not specific to any data record. Eg. Counting the total number of records in a table. They are special business methods, as they are called from bean in pool before the bean is associated with any data. Clients call home methods from local/remote home objects. 8. ejbCreate() you may not write any ejbCreate if you dont want EJB clients to be able to create new database data. These methods are responsible for creating new data record and initializing your bean. For BMP, you can use INSERT SQL statement to create new data and return an instance of primary key for the data to the container. 9. ejbPostCreate() must define one ejbPostCreate() for each ejbCreate() and both should take the same parameters. 1. You can do any post initialization work here and/or 2. pass the reference to your beans EJB Object to other beans and/or 3. reset certain transaction related parameteres. ejbActivate() acquire any resource (such as socket conncetions) if needed. ejbLoad() Call getPrimaryKey() on entity context to know what data to load and then read the data (SQL SELECT) into your bean. ejbStore() write your member fields out to disk through SQL UPDATE. ejbPassivate() release any resource if needed. ejbRemove() Call getPrimaryKey() on entity context to know what data to delete from the database then delete (SQL DELETE) the data. unsetEntityContext() release any resource aquired in setEntityContext() and get ready to be garbage collected. Called when entity bean instance is to be destroyed by container when it wants to reduce its pool size.

2006, Watsh Rajneesh. All Rights Reserved.

28/86

2/9/2008

BMP Entity bean with local interface

We are not showing the code for the remote interface below but for testing we use the remote interface itself. Though in practice, we will use a session faade to interface remotely with the client and use the entity beans locally but to test the entity bean individually without writing a session faade we use the remote interface.

Local interfacepackage examples.bmp; import javax.ejb.*; /** * This is the local interface for AccountBean. * * Local clients interact with beans through this interface. The container will * implement this interface; the implemented object is called the local object, * which delegates invocations to the actual bean. */ public interface AccountLocal extends EJBLocalObject { /** * Deposits amt into account. */ public void deposit(double amt) throws AccountException; /** * Withdraws amt from bank account. * @throw AccountException thrown if amt > available balance */ public void withdraw(double amt) throws AccountException; // Getter/setter methods on Entity Bean fields public double getBalance(); public String getOwnerName(); public void setOwnerName(String name); public String getAccountID(); public void setAccountID(String id);

2006, Watsh Rajneesh. All Rights Reserved.

29/86

2/9/2008

}

Local Home Interfacepackage examples.bmp; import javax.ejb.*; import java.util.Collection; /** * This is the local home interface for Account. This * interface is implemented by the EJB containers tools - the * implemented object is called the local home object, which * is a factory for local EJB objects. */ public interface AccountLocalHome extends EJBLocalHome { /** * We define a single create() method in this home interface, * which corresponds to the ejbCreate() method in AccountBean. * This method creates the local EJB object. * * Notice that the local home interface returns a * local interface, whereas the bean returns a PK. * * Notice we dont throw RemoteExceptions because we are local not remote. * * @param accountID The number of the account (unique) * @param ownerName The name of the person who owns the account * @return The newly created local object. */ public AccountLocal create(String accountID, String ownerName) throws CreateException; /** * Finds an Account by its primary Key (Account ID) */ public AccountLocal findByPrimaryKey(AccountPK key) throws FinderException; /** * Finds all Accounts under an owners name */ public Collection findByOwnerName(String name) throws FinderException; /** * This home business method is independent of any particular * account instance. It returns the total of all the bank * accounts in the bank. */ public double getTotalBankValue() throws AccountException;

}

Primary Key classpackage examples.bmp; /** * Primary Key class for Account. */ public class AccountPK implements java.io.Serializable { public String accountID; public AccountPK(String id) { this.accountID = id; } public AccountPK() { } public String toString() { return accountID; } public int hashCode() { return accountID.hashCode(); } public boolean equals(Object account) {

2006, Watsh Rajneesh. All Rights Reserved.

30/86

2/9/2008

}

}

if (!(account instanceof AccountPK)) return false; return ((AccountPK)account).accountID.equals(accountID);

Primary key contains a simple string but its possible for an entity bean to map to more than one table in the database and may have primary key class that have several field inside them, each representing a primary key of a table in the database. hashCode() and equals() should be overridden to allow the container to be able to compare two primary key instances by value when stored in a HashMap.

Custom Exception (Application Level)package examples.bmp; /** * Exceptions thrown by Accounts */ public class AccountException extends Exception { public AccountException() { super(); } public AccountException(Exception e) { super(e.toString()); } public AccountException(String s) { super(s); } }

Entity Bean Classcreate table accounts (id varchar(64), ownername varchar(64), balance numeric(18) ); is the table schema to which the entity bean class maps. package examples.bmp; import java.sql.*; import javax.naming.*; import javax.ejb.*; import java.util.*; /** * Demonstration Bean-Managed Persistent Entity Bean. This Entity Bean * represents a Bank Account. */ public class AccountBean implements EntityBean { protected EntityContext ctx; // // Bean-managed state fields // private String accountID; // PK private String ownerName; private double balance; public AccountBean() { System.out.println(New Bank Account Entity Bean Java Object created by EJB Container.); } // // Business Logic Methods // /** * Deposits amt into account. */ public void deposit(double amt) throws AccountException { System.out.println(deposit( + amt + ) called.); balance += amt; }

2006, Watsh Rajneesh. All Rights Reserved.

31/86

2/9/2008

/** * Withdraws amt from bank account. * @throw AccountException thrown if amt > available balance */ public void withdraw(double amt) throws AccountException { System.out.println(withdraw( + amt + ) called.); if (amt > balance) { throw new AccountException(Your balance is + balance + ! You cannot withdraw + amt + !); } balance -= amt; } // Getter/setter methods on Entity Bean fields public double getBalance() { System.out.println(getBalance() called.); return balance; } public void setOwnerName(String name) { System.out.println(setOwnerName() called.); ownerName = name; } public String getOwnerName() { System.out.println(getOwnerName() called.); return ownerName; } public String getAccountID() { System.out.println(getAccountID() called.); return accountID; } public void setAccountID(String id) { System.out.println(setAccountID() called.); this.accountID = id; } /** * This home business method is independent of any * particular account instance. It returns the total * of all the bank accounts in the bank. */ public double ejbHomeGetTotalBankValue() throws AccountException { PreparedStatement pstmt = null; Connection conn = null; try { System.out.println(ejbHomeGetTotalBankValue()); /* Acquire DB connection */ conn = getConnection(); /* Get the total of all accounts */ pstmt = conn.prepareStatement(select sum(balance) as total from accounts); ResultSet rs = pstmt.executeQuery(); /* Return the sum */ if (rs.next()) { return rs.getDouble(total); } } catch (Exception e) { e.printStackTrace(); throw new AccountException(e); } finally { /* * Release DB Connection for other beans */ try { if (pstmt != null) pstmt.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } } throw new AccountException(Error!); }

2006, Watsh Rajneesh. All Rights Reserved.

32/86

2/9/2008

/** * Gets JDBC connection from the connection pool. * * @return The JDBC connection */ public Connection getConnection() throws Exception { try { Context ctx = new InitialContext(); javax.sql.DataSource ds = (javax.sql.DataSource)ctx.lookup(java:comp/env/jdbc/ejbPool); return ds.getConnection(); } catch (Exception e) { System.err.println(Couldnt get datasource!); e.printStackTrace(); throw e; } } // // EJB-required methods // /** * Called by Container. Implementation can acquire * needed resources. */ public void ejbActivate() { System.out.println(ejbActivate() called.); } /** * Removes entity bean data from the database. * Corresponds to when client calls home.remove(). */ public void ejbRemove() throws RemoveException { System.out.println(ejbRemove() called.); /* * Remember that an entity bean class can be used to * represent different data instances. So how does * this method know which instance in the database * to delete? * * The answer is to query the container by calling * the entity context object. By retrieving the * primary key from the entity context, we know * which data instance, keyed by the PK, that we * should delete from the DB. */ AccountPK pk = (AccountPK) ctx.getPrimaryKey(); String id = pk.accountID; PreparedStatement pstmt = null; Connection conn = null; try { /* * 1) Acquire a new JDBC Connection */ conn = getConnection(); /* * 2) Remove account from the DB */ pstmt = conn.prepareStatement(delete from accounts where id = ?); pstmt.setString(1, id); /* * 3) Throw a system-level exception if something * bad happened. */ if (pstmt.executeUpdate() == 0) { throw new RemoveException( Account + pk + failed to be removed from the database); } } catch (Exception ex) {

2006, Watsh Rajneesh. All Rights Reserved.

33/86

2/9/2008

} finally {

throw new EJBException(ex.toString()); /* * 4) Release the DB Connection */ try { if (pstmt != null) pstmt.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } }

} /** * Called by Container. Releases held resources for * passivation. */ public void ejbPassivate() { System.out.println(ejbPassivate () called.); } /** * Called by the container. Updates the in-memory entity * bean object to reflect the current value stored in * the database. */ public void ejbLoad() { System.out.println(ejbLoad() called.); /* * Again, query the Entity Context to get the current * Primary Key, so we know which instance to load. */ AccountPK pk = (AccountPK) ctx.getPrimaryKey(); String id = pk.accountID; PreparedStatement pstmt = null; Connection conn = null; try { /* * 1) Acquire a new DB Connection */ conn = getConnection(); /* * 2) Get account from the DB, querying * by account ID */ pstmt = conn.prepareStatement(select ownerName, balance from accounts + where id = ?); pstmt.setString(1, id); ResultSet rs = pstmt.executeQuery(); rs.next(); ownerName = rs.getString(ownerName); balance = rs.getDouble(balance); } catch (Exception ex) { throw new EJBException( Account + pk + failed to load from database, ex); } finally { /* * 3) Release the DB Connection */ try { if (pstmt != null) pstmt.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } } } /** * Called from the Container. Updates the database * to reflect the current values of this in-memory

2006, Watsh Rajneesh. All Rights Reserved.

34/86

2/9/2008

* entity bean instance. */ public void ejbStore() { System.out.println(ejbStore() called.); PreparedStatement pstmt = null; Connection conn = null; try { /* * 1) Acquire a new DB Connection */ conn = getConnection(); /* * 2) Store account in DB */ pstmt = conn.prepareStatement( update accounts set ownerName = ?, balance = ? + where id = ?); pstmt.setString(1, ownerName); pstmt.setDouble(2, balance); pstmt.setString(3, accountID); pstmt.executeUpdate(); } catch (Exception ex) { throw new EJBException(Account + accountID + failed to save to database, ex); } finally { /* * 3) Release the DB Connection */ try { if (pstmt != null) pstmt.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } } } /** * Called by the container. Associates this bean * instance with a particular context. We can query * the bean properties that customize the bean here. */ public void setEntityContext(EntityContext ctx) { System.out.println(setEntityContext called); this.ctx = ctx; } /** * Called by Container. Disassociates this bean * instance with a particular context environment. */ public void unsetEntityContext() { System.out.println(unsetEntityContext called); this.ctx = null; } /** * Called after ejbCreate(). Now, the Bean can retrieve * its EJBObject from its context, and pass it as * a this argument. */ public void ejbPostCreate(String accountID, String ownerName) { } /** * This is the initialization method that corresponds to the * create() method in the Home Interface. * * When the client calls the Home Objects create() method, * the Home Object then calls this ejbCreate() method. * * @return The primary key for this account */ public AccountPK ejbCreate(String accountID, String ownerName) throws CreateException {

2006, Watsh Rajneesh. All Rights Reserved.

35/86

2/9/2008

} /** * Finds a Account by its primary Key */ public AccountPK ejbFindByPrimaryKey(AccountPK key) throws FinderException { PreparedStatement pstmt = null; Connection conn = null; try { System.out.println(ejbFindByPrimaryKey(+ key + ) called); /* * Acquire DB connection */ conn = getConnection(); /* * Find the Entity in the DB */ pstmt = conn.prepareStatement(select id from accounts where id = ?); pstmt.setString(1, key.toString()); ResultSet rs = pstmt.executeQuery(); rs.next(); /* * No errors occurred, so return the Primary Key */ return key; } catch (Exception e) { throw new FinderException(e.toString()); } finally { /* * Release DB Connection for other beans

PreparedStatement pstmt = null; Connection conn = null; try { System.out.println(ejbCreate() called.); this.accountID = accountID; this.ownerName = ownerName; this.balance = 0; /* * Acquire DB connection */ conn = getConnection(); /* * Insert the account into the database */ pstmt = conn.prepareStatement( insert into accounts (id, ownerName, balance) + values (?, ?, ?)); pstmt.setString(1, accountID); pstmt.setString(2, ownerName); pstmt.setDouble(3, balance); pstmt.executeUpdate(); /* * Generate the Primary Key and return it */ return new AccountPK(accountID); } catch (Exception e) { throw new CreateException(e.toString()); } finally { /* * Release DB Connection for other beans */ try { if (pstmt != null) pstmt.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } }

2006, Watsh Rajneesh. All Rights Reserved.

36/86

2/9/2008

}

} } /** * Finds Accounts by name */ public Collection ejbFindByOwnerName(String name) throws FinderException { PreparedStatement pstmt = null; Connection conn = null; Vector v = new Vector(); try { System.out.println(ejbFindByOwnerName( + name + ) called); /* * Acquire DB connection */ conn = getConnection(); /* * Find the primary keys in the DB */ pstmt = conn.prepareStatement( select id from accounts where ownerName = ?); pstmt.setString(1, name); ResultSet rs = pstmt.executeQuery(); /* * Insert every primary key found into a vector */ while (rs.next()) { String id = rs.getString(id); v.addElement(new AccountPK(id)); } /* * Return the vector of primary keys */ return v; } catch (Exception e) { throw new FinderException(e.toString()); } finally { /* * Release DB Connection for other beans */ try { if (pstmt != null) pstmt.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } } }

*/ try { if (pstmt != null) pstmt.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { }

Deployment Descriptor AccountJAR AccountEJB examples.bmp.AccountHome examples.bmp.Account examples.bmp.AccountBean Bean

2006, Watsh Rajneesh. All Rights Reserved.

37/86

2/9/2008

examples.bmp.AccountPK false jdbc/bmp-account javax.sql.DataSource Container Shareable AccountEJB Remote * AccountEJB Local * Required

Persistence-type Prim-key-class Reentrant Resource-ref Assembly-descriptor

Bean/Container Primary key class Whether our bean can call itself through another bean. A given bean A is reentrant if it calls bean B which calls back on bean A. Sets up our jdbc driver at jndi location Associates transactions with out bean.

You will also need the AppServer specific deployement descriptor where you can configure the remote and local home interface and the JDBC driver with JNDI locations. BMPEntityEjb.jar 0 AccountEJB AccountHome jdbc/bmp-account jdbc/bmp-account 0

2006, Watsh Rajneesh. All Rights Reserved.

38/86

2/9/2008

Create the accounts table in the database using the sql file provided. This step is database specific. Create EJB jar to deploy: >mkdir assemble\ejbjar Put the ejb-jar.xml and sun-ejb-jar.xml in the meta-inf folder in classes. >jar cvf BMPEntityEJB.jar C classes . >move BMPEntityEJB.jar assemble\ejbjar

Client Codepackage examples.bmp; import javax.ejb.*; import javax.naming.*; import java.rmi.*; import javax.rmi.*; import java.util.*; /** * Sample client code that manipulates a Bank Account Entity Bean. */ public class AccountClient { public static void main(String[] args) throws Exception { Account account = null; try { /* * Get a reference to the Account Home Object - the * factory for Account EJB Objects */ Context ctx = new InitialContext(System.getProperties()); Object obj = ctx.lookup(AccountHome); AccountHome home = (AccountHome)PortableRemoteObject.narrow(obj, AccountHome.class); System.err.println(Total of all accounts in bank initially = + home.getTotalBankValue()); /* Use the factory to create the Account EJB Object */

2006, Watsh Rajneesh. All Rights Reserved.

39/86

2/9/2008

}

}

} catch (Exception e) { System.out.println(Caught exception!); e.printStackTrace(); } finally { /* * Destroy the Entity permanently */ try { System.out.println(Destroying account..); if (account != null) { account.remove(); } } catch (Exception e) { e.printStackTrace(); } }

home.create(123-456-7890, John Smith); /* Find an account */ Iterator i = home.findByOwnerName(John Smith).iterator(); if (i.hasNext()) { account =(Account)javax.rmi.PortableRemoteObject.narrow(i.next(), Account.class); } else { throw new Exception(Could not find account); } /* Call the balance() method, and print it */ System.out.println(Initial Balance = + account.getBalance()); /* Deposit $100 into the account */ account.deposit(100); /* Retrieve the resulting balance. */ System.out.println(After depositing 100, account balance = + account.getBalance()); System.out.println(Total of all accounts in bank now = + home.getTotalBankValue()); /* Retrieve the Primary Key from the EJB Object */ AccountPK pk = (AccountPK) account.getPrimaryKey(); /* * Release our old EJB Object reference. Now call * find() again, this time querying on Account ID * (i.e. the Primary Key). */ account = null; account = home.findByPrimaryKey(pk); /* Print out current balance */ System.out.println(Found account with ID + pk + . Balance = + account.getBalance()); /* Try to withdraw $150 */ System.out.println(Now trying to withdraw $150, which is more + than is currently available. This should + generate an exception..); account.withdraw(150);

Run the client: Generate the Client Jar: >rmic -classpath .\classes;d:\Sun\AppServer\lib\j2ee.jar;d:\Sun\AppServ\lib\appserv-ext.jar -iiop examples.bmp.Account >rmic -classpath .\classes;d:\Sun\AppServer\lib\j2ee.jar;d:\Sun\AppServ\lib\appserv-ext.jar -iiop examples.bmp.AccountHome >mkdir assemble\client

2006, Watsh Rajneesh. All Rights Reserved.

40/86

2/9/2008

>jar cvf BMPEntityClient.jar C classes . >move BMPEntityClient.jar .\assemble\client >java -cp .\assemble\client\BMPEntityClient.jar\;%CLASSPATH% -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory -Djava.naming.provider.url=corbaloc::localhost:3700/NameService examples.bmp.AccountClient

10. Container calls newInstance() on the bean class to create an instance of bean. This calls entitybeans default constructor. Container associates the bean instance with an entity context by calling setEntityContext() method of bean class. Now the bean is put in the instance pool for that entity bean type. In the pool, the bean instance can be used to find entity data in the database by servicing a finder method on behalf of client. It can also perform operations not dependent on a particular data instance by servicing ejbHome() method. Container can call the unsetEntityContext() when it wants to destroy the bean instance from pool (and the bean will be ready for garbage collection). When client wants to create some new database data then it calls the create() method on the home interface. Container grabs an entity bean from pool and calls its ejbCreate() method where the bean initializes itself to a specific data set passed in the params of the create() method by the client and, in case of BMP, this method will also create the corresponding data record in the database. Now the bean moves to ready state.

11.

12.

2006, Watsh Rajneesh. All Rights Reserved.

41/86

2/9/2008

13. In the ready state, your bean is tied to a specific data and hence a specific EJB Object. Containermay occassionally need to synchronize your bean instance with the database by calling ejbLoad() and ejbStore(). So ejbLoad() and ejbStore() will be responsible for loading and saving the data in the database, in case of BMP. If the client calls remove() on the home object or EJB object then container will call the ejbRemove() method which in case of BMP is supposed to delete the database data associated with this bean instance. If the container needs to reuse a bean instance in the ready state to service another client, then it will need to passivate the bean in which case it will call the ejbStore() method and then the ejbPassivate() method, where the bean can release any resource it held. Then the bean is returned back to pool for reuse. Container may want to reassign the bean to an existing EJB object, then it will call the ejbActivate() on the bean where the bean can reaquire the resouces it held earlier, and then the container calls the ejbLoad() where the bean can initialize itself to the specific data (by first learning about what primary key to use to retrieve that unique data record from the EJB object).

14. 15.

16.

Container Managed Persistent (CMP) Entity BeansWith CMP, you dont implement any persistence logic in the bean itself; rather the EJB container generates the required storage code by subclassing your entity bean class. Thus all CMP entity beans comprise of two classes: the superclass which you write (containing the entity bean business logic); and the subclass which the container generates (which contains the persistence logic). You dont define any persistent fields and the associated get/set methods in your bean. They are kept in the subclass (which the container generates). You will need to declare the get/set methods as abstract methods in your entity bean class (thus making it an abstract class). So if you need to provide a business method which works on more than one persistent field then you can define such a method in your entity bean class itself and use the abstract get/set methods in your implementation which will resolve to the subclasses implementation of those get/set methods at runtime. For example,// CMP superclass you write. public abstract class CartBean implements EntityBean { // no fields // abstract get/set methods public abstract float getSubTotal(); public abstract float getTaxes(); // other business methods public float getTotal() { return this.getSubtotal() + this.getTaxes(); } } // EJB required methods follow

// CMP subclass container generated. public class CartBeanSubClass extends CartBean { // fields public float subTotal; public float taxes; public float getSubTotal() { return subTotal; } public float getTaxes() { return taxes;

2006, Watsh Rajneesh. All Rights Reserved.

42/86

2/9/2008

}

} // other get/set method implementations

Abstract Persistence Schema... 2.x AccountBean accountID ownerName balance accountID ...

Abstract persistence sche