Enterprise Java Bean       BY:   Sukesh Kumar
The Motivation… Component Based Development… Instead of reusing Java Classes, you get to  reuse a bigger chunk of functionality.
What does EJB give me? Lets you focus on the business logic and  The underlying services: Transaction Management Security Concurrency Networking Resource management Persistence Messaging Deploy-time customization to the EJB Server Vendor.
Portability Java Write once Run Anywhere Stops the force to work on single OS EJB  Write Once Deploy Anywhere Stops being at the mercy of Application Server Vendor
EJB Architecture It’s about infrastructure…
High Level View Client Object EJB Object B I Z I N T E R F A C E S e r v i c e s EJB Server DB ? ? ? How does a client get a reference to a different machine/JVM? How does the client communicate with the bean? How does the server step into client-bean call? Java references hold bits that don’t means anything outside the  Currently running JVM.
The RMI Remote Method Invocation…
What is RMI? Access to Remote Objects Java-to-Java  only - i.e., from JVM Your client gets to act like it’s making a remote method call, but what its doing is calling a method on a proxy object running on the same heap. The proxy is called  “stub”
Stubs Implement a given set of RMI interfaces, which are also implemented by a remote object. lives on client Have the same interface as the server object handles all the low level networking sockets and streams.
Skeletons lives on server receives requests from stub talks to true remote object delivers response to stub
RMI Layers TCP Java Virtual Machine Client Object Java Virtual Machine Stub Remote Object Skeleton Remote Reference Layer Transport Layer Remote Reference Layer Transport Layer
Remote Reference Layer Figures out which remote object is being referenced Could span multiple virtual machines Communicates via TCP/IP
Transport Layer Deals with communications Connection management Dispatching messages between stub and skeleton
RMI Flow Client Virtual Machine Client Server Virtual Machine Stub Remote Object Skeleton Registry Virtual Machine “ Team”   Server 1 2 1.   Server Creates Remote Object 2. Server Registers Remote Object 3. Client requests object from Registry 3 4. Registry returns remote reference (and stub gets created) 4 5. Client invokes stub method 5 6. Stub talks to skeleton 6 7. Skeleton invokes remote object method
Food for thought How does a local method call, passes an object reference? By Value: by copying the bits in the reference variable. The object Itself is never passed. How does it work with remote method call? That reference would Actually mean nothing on the other heap. An object copy is shipped, not the reference copy.  Actually sends Remote  Object’s stub.
Algorithm Marshalling (Serialization) Un-marshalling (De-Serialization) Java.io.OutputStream  and  java.io.InputStream  classes typically used by calling  WriteObject  on  OutputStream  and  ReadObject  on  InputStream .
Digging deep in to it Exploring the components and the architecture…
EJB Components Component Interface Extends EJBObject Business methods the client uses Home Object Extends EJBHome Hands out references of the component interface One deployed bean, one home Bean Class Let this be a secret for the time being.
How does it all happen? EJB S e r v i c e s The bean is deployed, and the server instantiates the Bean Home object and registers it with JNDI. The client does a JNDI lookup on the Home, using the registered name. The JNDI sends back a stub to the Remote Home object. The client asks the Home for a reference to the Component interface, by calling  create() The services kick in and the Bean is created. The EJBObject is created and stub returned to the client. The client can call the business method on the bean The client can get rid of Home stub if he doesn’t want access to more Beans of this type. Home Stub create() EJBObject EJBObject stub
Who does what? Container Implements Component Interface Creates stub to EJBObject Implements Home Interface Creates stub for it. You Create Component Interface Create Bean Class Create Home Interface
Getting specific Session Beans Client  request  share the Home, but never the bean One Home but different EJBObject and Bean. Entity Beans Clients share the Home, and may share the bean. If two clients are trying to access same ENTITY, then both have reference to same EJBObject.
Session Bean Creation Stateful: After the EJBObject creation, the bean is instantiated with call of  create() . Stateless The bean creation is on discretion of Container. The call of  create()  and actual creation of the bean are decoupled. A single bean can handle multiple client as long as only one client at a time is in the middle of the business method invocation.
Message Driven Beans Don’t have a client view. Don’t have Home or EJBOjbect The client sends message to a JMS messaging JMS delivers the message to the container The Container gets a MDB out of the pool The container delivers the message to the bean by calling the onMessage() MessageListener interface method.
The client view Bean exposed…
What client wants? A reference to Bean What it can get is reference to its bodyguard, the EJBObject To get even the EJBObject, it has to get the Home interface So…. It all starts with the lookup to the HOME interface.
How does he get it? The process…
JNDI Java Naming and Directory Interface Organizes things in to a virtual directory tree Each level of tree is either another virtual directory (called a context) or an object
The Client code…
PortableRemoteObject It’s not pure RMI with JRMP Where you know that what you get out of lookup is polymorphically something that IS-A home interface. It’s RMI with RMI-IIOP You might get back an IIOP stub that isn’t castable to the home interface. Narrow the object you got to the object you want.
The home interface Stateless  Session Bean Stateful Session Bean Rules: Declare a create() method that returns the component interface and throw CreateException and RemoteException Stateless Session beans have only one no-arg create and  Stateful can have multiple, overloaded create methods, throwing Exceptions Can also throw other checked exceptions The name of the create method must begin with create and arguments Must be RMI-IIOP compliant
EJBHome methods EJBMetaData getEJBMetaData() Get reflection like information of the bean. HomeHandle getHomeHandle() Serialize the home so that you can use it later void remove (Handle h) Done with the session bean, send  EJBObject handle void remove (Object key) Done with the Entity bean, delete row from DB. Pass Primary key.
The Component Interface Rules Declare one or more business methods. Arguments and return types must be RMI-IIOP compatible. You can have overloaded methods Each method must declare a RemoteException You can declare your own application exceptions but they must not be runtime exceptions
EJBObject Methods Object getPrimaryKey() Get the PK of an Entity bean EJBHome getEJBHome() Get the bean’s Home Handle getHandle() Save a reference to the EJBObject void remove() Tell the bean you are done with it (Session) boolean isIdentical() Compare two EJB object references to see if they reference the same bean. (See note)
Session Beans Being a Session Bean…
Lifecycle Stateless Bean  creation  (when container wants) Bean  use  (when client calls a method) Bean  removal  (when container decides there are too many beans in the pool) Stateful Bean  creation  (when the client wants a bean) Bean  use  (when the client calls a method) Bean  passivation  (bean is put to sleep to conserve resources) Bean  activation  (bean wakes up to service bus. method from the client) Bean  removal  (when the client is finished with the bean, or the bean times out)
Container callbacks Comes from two places ExampleHome create() ExampleBean setSessionContext(SessionContext sc) ejbActivate() ejbPassivate() ejbRemove() ejbCreate() printStuff() SessionBean setSessionContext(…) ejbActivate() ejbPassivate() ejbRemove() Your Home interface SessionBean interface For every create() in the home There must be a matching ejbCreate() in the bean Business method, not a container callback For Stateless session bean there will be exactly five container callbacks As has only one create(). Stateful beans will have arguments in create() to  pass the client-specific state to be stored.
State chart: stateful EJB EJB EJB 1. constructor 2. setSessionContext 3. ejbCreate() does not exist method ready passivated Timeout.  ejbRemove() not called ejbPassivate() ejbActivate() ejbRemove() or timeout Bean throws system exception (uncheked, uncaught) cannot be brought out of passivation, just to kill it.
Beanness A SessionContext Reference The bean’s special reference for getting info form container Get a reference to your home and EJB object Get security information about client Force transaction to rollback (CMT) Find out if a transaction has already been set to rollback (CMT) Get a transaction reference, and call methods on it (BMT) A special JNDI context A particular node on a JNDI virtual directory tree A reference to another bean A reference to a resource manager connection factory Deploy time constants for the bean, set by deployer A reference to administered object reference (JMS destination) Access to Another bean A resource manager (like a database)
When can you do what? Use you SessionContext to: Get a reference to your home Get a reference to your EJB object Get security information about the client Force a transaction to rollback (CMT) Find out if the transaction has already been set to rollback (CMT) Get a transaction reference, and call method on it (BMT) Access: Your special JNDI environment Another bean’s method A resource manager (like a database) constructor setSessionContext() ejbCreate() ejbActivate() ejbPassivate() Business methods ejbRemove()
Passivation: When/Why/How? Client doesn’t call any methods for a while, so container calls ejbPassivate() on the bean Then saves the bean to temporary storage (serialization) Client calls a business method, so container activates the bean (deserialization) You have to make sure that by the time ejbPassivate() completes, all the instance variable’s values are ready for passivation. (see note)
Implementing activate and passivate ejbPassivate() Make sure your instance variables are ready for passivation A JDBC connection is not Serializable, set it to null ejbActivate() Reacquire the non-Serializable resources, or do whatever it takes to restore your state for use Get the JDBC connection back
State chart: stateless EJB EJB 1. constructor 2. setSessionContext 3. ejbCreate() does not exist method ready ejbRemove() or timeout Bean throws system exception (uncheked, uncaught)
Rules for Home methods: bean class Every create method in home must have a matching ejbCreate in bean class ejbCreate must be public and not final or static You do not have to declare exceptions declared in home, unless you might actually throw it You must NOT declare any application exceptions that were not in create of home
Rules for business methods :Component interface Names must not begin with ejb. Arguments and Return types must be RMI-IIOP compliant. You must not expose the local home or component interface of a bean through a Remote component interface method
Rules for business methods:  bean class Business methods must be declared public and not static or final Method names must not begin with ejb Must not pass “this” as argument or return value Arguments and return types must be RMI-IIOP type. You do not have to declare exceptions declared, unless you might actually throw it You must NOT declare any application exceptions that were not in component interface
Entity Beans The persistence…
Entity Beans: Why? Entity bean is a realization of something that already exists in persistent store. By using it you take the advantage of  all the Container’s services Automatic synchronization of db and the bean You don’t have to map back and forth in your code You avoid all the SQL queries in your code
What you have to do? Add Call create() Container pulls the bean from the pool of this bean type Container inserts new row in database Get the EJB object stub after linking Update Call a  finder Container checks if the persistent store has the data get the EJB object stub, if the data exists Make changes
The code
create() and findByPrimaryKey() returns only one component interface reference There can be multiple entity finders, the client get a reference to each bean that matches the query  That means you have to make remote method calls on each to get the data you want Home business methods can return something other than EJB object references.  Perfect if client wants entity data and not reference You can write the getAll() kind of methods as Home business method
finders There can be one or more finder methods Returns either the Remote component interface (single-entity finder) or a Collection (multiple-entity finder) All finders must declare both the RemoteException and the FinderException.
ejbRemove() The Entity is deleted The Component interface stub for the object is deleted The Entity bean goes to the pool
? Who loves Stale things? Do they matter?
Entity Bean Synchronization Container’s job is to make sure that the entity and the bean stay in sync. Before the bean can run any business method, the bean has to be refreshed with the entity’s state Will the bean get stale between every business method call? When the client calls a business method, and that method starts a transaction, I tell the db to lock the entity. Still a Problem?
The Flow tx EJB updateCustomer() Client calls a business method Container intercepts the call,  Starts a transaction before getting the bean Container tells the db to lock the row Container loads the bean with the entity state from the db Bean runs multiple business methods in the same transaction Container ends the transaction  after updating the new state in bean which might have been cached on  behalf of the entity Container asks the db to release the lock some Sk 1 Address Name ID some Sk 1 Address Name ID
Activation/Passivation Passivation: ejbPassivate(): called when bean has finished the business method to release the resources and send back to the pool. Bean has no identity Bean is not serialized and saved Activation: ejbActivate() :is called to service a business method
Container callbacks EntityBean set Entity Context(EntityContext ec) ejbActivate() ejbPassivate() ejbRemove() unsetEntityContext() ejLoad() ejbStore() SessionBean set Session Context(…) ejbActivate() ejbPassivate() ejbRemove() When bean is reactivated, deserialization Container gives the bean a reference to its context When bean is taken out of the  pool to service a client’s buz method call When bean is about to be serialized To reduce pool size When bean is about to return to pool,  following a transaction Delete entity from database Container calls when Wants to reduce size of pool When bean has be refreshed with  data from persistent storage When container is about to update the db Both EntityContext and SessionContext extend EJBContext, but EJBContext adds One method getPrimaryKey(). This is different from EJBObject’s getPrimary key as This is only exposed to the entity beans and not to both Session bean and Entity bean
Container callbacks ExampleHome create() findByPrimaryKey(..) doAll() ExampleBean Your Home interface EntityBean interface For every create() in the home There must be two methods in the bean ejbCreate() and ejbPostCreate() EntityBean set Entity Context(EntityContext ec) ejbActivate() ejbPassivate() ejbRemove() unsetEntityContext() ejbLoad() ejbStore() set Entity Context(EntityContext ec) ejbActivate() ejbPassivate() ejbRemove() unsetEntityContext() ejbLoad() ejbStore() ejbCreate() ejbPostCreate() ejbFindByPrimaryKey(String key) ejbHomeDoAll() //business methods from  //component interface Bean also has the Virtual Persistent fields, which are for values that map to db. They represent entity’s persistent state. They exist as abstract getters and setters
State chart: Entity bean EJB EJB EJB 1. constructor 2. setEntityContext does not exist pooled method ready Timeout.  ejbRemove() not called ejbPassivate() ejbActivate() unsetEntityContext() Bean throws system exception (uncheked, uncaught) ejbFind<method>() ejbSelect<method>() ejbHome<method>() ejbFind<method>() ejbHome<method> Biz method (Component interface) ejbSelect<method>() From business method
A reference to EJB object Client calls a finder on the home Client calls create on the home Client calls a home business method that returns a reference to the bean’s component interface ?
Why ejbPostCreate? Can I initialize my EJB object without the primary key or knowing the state changes? ejbCreate() Put your entity initialization code, values for your persistent fields Bean instance gets instantiated in setEntityContext(), here you initialize it, doesn’t have EJB object Return type must be Primary Key ejbPostCreate() Finish your initialization code here You have the EJB object reference Accessing your Container Managed Relationships Return type must be void
finders Container implements Your bean class must not even mention the finder methods Container implements using the home interface and your deployment descriptor to figure out what to do Container returns the EJB object, but the bean stays in the pool  to avoid loading of the stale data
 
Message Driven Beans Asynchronous communication…
MDB: Overview Client (Producer) sends a message to the messaging service Message is delivered to the Container. Client is doing other things Container acknowledges the message to the services, and pulls a bean out of the pool to process the message. Container invokes the beans onMessage() method, with the message as argument The bean’s transaction commits, and is sent back to pool If the bean’s transaction in onMessage had rolled back, the Container would have told the messaging service to put the message back on the queue.
MDBs are asynchronous Multiple beans of same type can process messages concurrently Container makes sure that each bean is thread safe
State chart: MDB EJB EJB 1. constructor 2. setMessageDrivenContext 3. ejbCreate() does not exist method ready ejbRemove() or timeout Bean throws system exception (uncheked, uncaught) onMessage()
MDB class
JMS destination What is JMS Destination? Where did you specify the JMS destination in the code?
Flavors of Messaging Topics  Uses Publish and Subscribe method. One bean per pool gets a copy. Types are: Durable Subscription Consumer sees all the messages, even if offline Non-Durable Subscription Consumer must be online to view the message Queues FIFO. Only one bean gets the message. Producer sends the message for single consumer
What if something goes wrong? What if the bean getting the message dies or throws an exception? Handled using  acknowledgement:  Container tells the Messaging service that everything is fine if message delivered Tells to put message back in queue if something bad happens
How is it tracked? The transaction status Is tied to whether the transaction commits or rolls back. You get this behavior for beans that uses CMT The method completion Is tied to whether the message completes successfully. You get this behavior for beans that use BMT
EJB Transactions The ACID test…
Exceptions in EJB Handle the bad…
Security in EJB The secrets…
 
Deployment Prepare the environment…
 
 
 
 
 
 
 
 
 

Ejb 2.0

  • 1.
    Enterprise Java Bean BY: Sukesh Kumar
  • 2.
    The Motivation… ComponentBased Development… Instead of reusing Java Classes, you get to reuse a bigger chunk of functionality.
  • 3.
    What does EJBgive me? Lets you focus on the business logic and The underlying services: Transaction Management Security Concurrency Networking Resource management Persistence Messaging Deploy-time customization to the EJB Server Vendor.
  • 4.
    Portability Java Writeonce Run Anywhere Stops the force to work on single OS EJB Write Once Deploy Anywhere Stops being at the mercy of Application Server Vendor
  • 5.
    EJB Architecture It’sabout infrastructure…
  • 6.
    High Level ViewClient Object EJB Object B I Z I N T E R F A C E S e r v i c e s EJB Server DB ? ? ? How does a client get a reference to a different machine/JVM? How does the client communicate with the bean? How does the server step into client-bean call? Java references hold bits that don’t means anything outside the Currently running JVM.
  • 7.
    The RMI RemoteMethod Invocation…
  • 8.
    What is RMI?Access to Remote Objects Java-to-Java only - i.e., from JVM Your client gets to act like it’s making a remote method call, but what its doing is calling a method on a proxy object running on the same heap. The proxy is called “stub”
  • 9.
    Stubs Implement agiven set of RMI interfaces, which are also implemented by a remote object. lives on client Have the same interface as the server object handles all the low level networking sockets and streams.
  • 10.
    Skeletons lives onserver receives requests from stub talks to true remote object delivers response to stub
  • 11.
    RMI Layers TCPJava Virtual Machine Client Object Java Virtual Machine Stub Remote Object Skeleton Remote Reference Layer Transport Layer Remote Reference Layer Transport Layer
  • 12.
    Remote Reference LayerFigures out which remote object is being referenced Could span multiple virtual machines Communicates via TCP/IP
  • 13.
    Transport Layer Dealswith communications Connection management Dispatching messages between stub and skeleton
  • 14.
    RMI Flow ClientVirtual Machine Client Server Virtual Machine Stub Remote Object Skeleton Registry Virtual Machine “ Team” Server 1 2 1. Server Creates Remote Object 2. Server Registers Remote Object 3. Client requests object from Registry 3 4. Registry returns remote reference (and stub gets created) 4 5. Client invokes stub method 5 6. Stub talks to skeleton 6 7. Skeleton invokes remote object method
  • 15.
    Food for thoughtHow does a local method call, passes an object reference? By Value: by copying the bits in the reference variable. The object Itself is never passed. How does it work with remote method call? That reference would Actually mean nothing on the other heap. An object copy is shipped, not the reference copy. Actually sends Remote Object’s stub.
  • 16.
    Algorithm Marshalling (Serialization)Un-marshalling (De-Serialization) Java.io.OutputStream and java.io.InputStream classes typically used by calling WriteObject on OutputStream and ReadObject on InputStream .
  • 17.
    Digging deep into it Exploring the components and the architecture…
  • 18.
    EJB Components ComponentInterface Extends EJBObject Business methods the client uses Home Object Extends EJBHome Hands out references of the component interface One deployed bean, one home Bean Class Let this be a secret for the time being.
  • 19.
    How does itall happen? EJB S e r v i c e s The bean is deployed, and the server instantiates the Bean Home object and registers it with JNDI. The client does a JNDI lookup on the Home, using the registered name. The JNDI sends back a stub to the Remote Home object. The client asks the Home for a reference to the Component interface, by calling create() The services kick in and the Bean is created. The EJBObject is created and stub returned to the client. The client can call the business method on the bean The client can get rid of Home stub if he doesn’t want access to more Beans of this type. Home Stub create() EJBObject EJBObject stub
  • 20.
    Who does what?Container Implements Component Interface Creates stub to EJBObject Implements Home Interface Creates stub for it. You Create Component Interface Create Bean Class Create Home Interface
  • 21.
    Getting specific SessionBeans Client request share the Home, but never the bean One Home but different EJBObject and Bean. Entity Beans Clients share the Home, and may share the bean. If two clients are trying to access same ENTITY, then both have reference to same EJBObject.
  • 22.
    Session Bean CreationStateful: After the EJBObject creation, the bean is instantiated with call of create() . Stateless The bean creation is on discretion of Container. The call of create() and actual creation of the bean are decoupled. A single bean can handle multiple client as long as only one client at a time is in the middle of the business method invocation.
  • 23.
    Message Driven BeansDon’t have a client view. Don’t have Home or EJBOjbect The client sends message to a JMS messaging JMS delivers the message to the container The Container gets a MDB out of the pool The container delivers the message to the bean by calling the onMessage() MessageListener interface method.
  • 24.
    The client viewBean exposed…
  • 25.
    What client wants?A reference to Bean What it can get is reference to its bodyguard, the EJBObject To get even the EJBObject, it has to get the Home interface So…. It all starts with the lookup to the HOME interface.
  • 26.
    How does heget it? The process…
  • 27.
    JNDI Java Namingand Directory Interface Organizes things in to a virtual directory tree Each level of tree is either another virtual directory (called a context) or an object
  • 28.
  • 29.
    PortableRemoteObject It’s notpure RMI with JRMP Where you know that what you get out of lookup is polymorphically something that IS-A home interface. It’s RMI with RMI-IIOP You might get back an IIOP stub that isn’t castable to the home interface. Narrow the object you got to the object you want.
  • 30.
    The home interfaceStateless Session Bean Stateful Session Bean Rules: Declare a create() method that returns the component interface and throw CreateException and RemoteException Stateless Session beans have only one no-arg create and Stateful can have multiple, overloaded create methods, throwing Exceptions Can also throw other checked exceptions The name of the create method must begin with create and arguments Must be RMI-IIOP compliant
  • 31.
    EJBHome methods EJBMetaDatagetEJBMetaData() Get reflection like information of the bean. HomeHandle getHomeHandle() Serialize the home so that you can use it later void remove (Handle h) Done with the session bean, send EJBObject handle void remove (Object key) Done with the Entity bean, delete row from DB. Pass Primary key.
  • 32.
    The Component InterfaceRules Declare one or more business methods. Arguments and return types must be RMI-IIOP compatible. You can have overloaded methods Each method must declare a RemoteException You can declare your own application exceptions but they must not be runtime exceptions
  • 33.
    EJBObject Methods ObjectgetPrimaryKey() Get the PK of an Entity bean EJBHome getEJBHome() Get the bean’s Home Handle getHandle() Save a reference to the EJBObject void remove() Tell the bean you are done with it (Session) boolean isIdentical() Compare two EJB object references to see if they reference the same bean. (See note)
  • 34.
    Session Beans Beinga Session Bean…
  • 35.
    Lifecycle Stateless Bean creation (when container wants) Bean use (when client calls a method) Bean removal (when container decides there are too many beans in the pool) Stateful Bean creation (when the client wants a bean) Bean use (when the client calls a method) Bean passivation (bean is put to sleep to conserve resources) Bean activation (bean wakes up to service bus. method from the client) Bean removal (when the client is finished with the bean, or the bean times out)
  • 36.
    Container callbacks Comesfrom two places ExampleHome create() ExampleBean setSessionContext(SessionContext sc) ejbActivate() ejbPassivate() ejbRemove() ejbCreate() printStuff() SessionBean setSessionContext(…) ejbActivate() ejbPassivate() ejbRemove() Your Home interface SessionBean interface For every create() in the home There must be a matching ejbCreate() in the bean Business method, not a container callback For Stateless session bean there will be exactly five container callbacks As has only one create(). Stateful beans will have arguments in create() to pass the client-specific state to be stored.
  • 37.
    State chart: statefulEJB EJB EJB 1. constructor 2. setSessionContext 3. ejbCreate() does not exist method ready passivated Timeout. ejbRemove() not called ejbPassivate() ejbActivate() ejbRemove() or timeout Bean throws system exception (uncheked, uncaught) cannot be brought out of passivation, just to kill it.
  • 38.
    Beanness A SessionContextReference The bean’s special reference for getting info form container Get a reference to your home and EJB object Get security information about client Force transaction to rollback (CMT) Find out if a transaction has already been set to rollback (CMT) Get a transaction reference, and call methods on it (BMT) A special JNDI context A particular node on a JNDI virtual directory tree A reference to another bean A reference to a resource manager connection factory Deploy time constants for the bean, set by deployer A reference to administered object reference (JMS destination) Access to Another bean A resource manager (like a database)
  • 39.
    When can youdo what? Use you SessionContext to: Get a reference to your home Get a reference to your EJB object Get security information about the client Force a transaction to rollback (CMT) Find out if the transaction has already been set to rollback (CMT) Get a transaction reference, and call method on it (BMT) Access: Your special JNDI environment Another bean’s method A resource manager (like a database) constructor setSessionContext() ejbCreate() ejbActivate() ejbPassivate() Business methods ejbRemove()
  • 40.
    Passivation: When/Why/How? Clientdoesn’t call any methods for a while, so container calls ejbPassivate() on the bean Then saves the bean to temporary storage (serialization) Client calls a business method, so container activates the bean (deserialization) You have to make sure that by the time ejbPassivate() completes, all the instance variable’s values are ready for passivation. (see note)
  • 41.
    Implementing activate andpassivate ejbPassivate() Make sure your instance variables are ready for passivation A JDBC connection is not Serializable, set it to null ejbActivate() Reacquire the non-Serializable resources, or do whatever it takes to restore your state for use Get the JDBC connection back
  • 42.
    State chart: statelessEJB EJB 1. constructor 2. setSessionContext 3. ejbCreate() does not exist method ready ejbRemove() or timeout Bean throws system exception (uncheked, uncaught)
  • 43.
    Rules for Homemethods: bean class Every create method in home must have a matching ejbCreate in bean class ejbCreate must be public and not final or static You do not have to declare exceptions declared in home, unless you might actually throw it You must NOT declare any application exceptions that were not in create of home
  • 44.
    Rules for businessmethods :Component interface Names must not begin with ejb. Arguments and Return types must be RMI-IIOP compliant. You must not expose the local home or component interface of a bean through a Remote component interface method
  • 45.
    Rules for businessmethods: bean class Business methods must be declared public and not static or final Method names must not begin with ejb Must not pass “this” as argument or return value Arguments and return types must be RMI-IIOP type. You do not have to declare exceptions declared, unless you might actually throw it You must NOT declare any application exceptions that were not in component interface
  • 46.
    Entity Beans Thepersistence…
  • 47.
    Entity Beans: Why?Entity bean is a realization of something that already exists in persistent store. By using it you take the advantage of all the Container’s services Automatic synchronization of db and the bean You don’t have to map back and forth in your code You avoid all the SQL queries in your code
  • 48.
    What you haveto do? Add Call create() Container pulls the bean from the pool of this bean type Container inserts new row in database Get the EJB object stub after linking Update Call a finder Container checks if the persistent store has the data get the EJB object stub, if the data exists Make changes
  • 49.
  • 50.
    create() and findByPrimaryKey()returns only one component interface reference There can be multiple entity finders, the client get a reference to each bean that matches the query That means you have to make remote method calls on each to get the data you want Home business methods can return something other than EJB object references. Perfect if client wants entity data and not reference You can write the getAll() kind of methods as Home business method
  • 51.
    finders There canbe one or more finder methods Returns either the Remote component interface (single-entity finder) or a Collection (multiple-entity finder) All finders must declare both the RemoteException and the FinderException.
  • 52.
    ejbRemove() The Entityis deleted The Component interface stub for the object is deleted The Entity bean goes to the pool
  • 53.
    ? Who lovesStale things? Do they matter?
  • 54.
    Entity Bean SynchronizationContainer’s job is to make sure that the entity and the bean stay in sync. Before the bean can run any business method, the bean has to be refreshed with the entity’s state Will the bean get stale between every business method call? When the client calls a business method, and that method starts a transaction, I tell the db to lock the entity. Still a Problem?
  • 55.
    The Flow txEJB updateCustomer() Client calls a business method Container intercepts the call, Starts a transaction before getting the bean Container tells the db to lock the row Container loads the bean with the entity state from the db Bean runs multiple business methods in the same transaction Container ends the transaction after updating the new state in bean which might have been cached on behalf of the entity Container asks the db to release the lock some Sk 1 Address Name ID some Sk 1 Address Name ID
  • 56.
    Activation/Passivation Passivation: ejbPassivate():called when bean has finished the business method to release the resources and send back to the pool. Bean has no identity Bean is not serialized and saved Activation: ejbActivate() :is called to service a business method
  • 57.
    Container callbacks EntityBeanset Entity Context(EntityContext ec) ejbActivate() ejbPassivate() ejbRemove() unsetEntityContext() ejLoad() ejbStore() SessionBean set Session Context(…) ejbActivate() ejbPassivate() ejbRemove() When bean is reactivated, deserialization Container gives the bean a reference to its context When bean is taken out of the pool to service a client’s buz method call When bean is about to be serialized To reduce pool size When bean is about to return to pool, following a transaction Delete entity from database Container calls when Wants to reduce size of pool When bean has be refreshed with data from persistent storage When container is about to update the db Both EntityContext and SessionContext extend EJBContext, but EJBContext adds One method getPrimaryKey(). This is different from EJBObject’s getPrimary key as This is only exposed to the entity beans and not to both Session bean and Entity bean
  • 58.
    Container callbacks ExampleHomecreate() findByPrimaryKey(..) doAll() ExampleBean Your Home interface EntityBean interface For every create() in the home There must be two methods in the bean ejbCreate() and ejbPostCreate() EntityBean set Entity Context(EntityContext ec) ejbActivate() ejbPassivate() ejbRemove() unsetEntityContext() ejbLoad() ejbStore() set Entity Context(EntityContext ec) ejbActivate() ejbPassivate() ejbRemove() unsetEntityContext() ejbLoad() ejbStore() ejbCreate() ejbPostCreate() ejbFindByPrimaryKey(String key) ejbHomeDoAll() //business methods from //component interface Bean also has the Virtual Persistent fields, which are for values that map to db. They represent entity’s persistent state. They exist as abstract getters and setters
  • 59.
    State chart: Entitybean EJB EJB EJB 1. constructor 2. setEntityContext does not exist pooled method ready Timeout. ejbRemove() not called ejbPassivate() ejbActivate() unsetEntityContext() Bean throws system exception (uncheked, uncaught) ejbFind<method>() ejbSelect<method>() ejbHome<method>() ejbFind<method>() ejbHome<method> Biz method (Component interface) ejbSelect<method>() From business method
  • 60.
    A reference toEJB object Client calls a finder on the home Client calls create on the home Client calls a home business method that returns a reference to the bean’s component interface ?
  • 61.
    Why ejbPostCreate? CanI initialize my EJB object without the primary key or knowing the state changes? ejbCreate() Put your entity initialization code, values for your persistent fields Bean instance gets instantiated in setEntityContext(), here you initialize it, doesn’t have EJB object Return type must be Primary Key ejbPostCreate() Finish your initialization code here You have the EJB object reference Accessing your Container Managed Relationships Return type must be void
  • 62.
    finders Container implementsYour bean class must not even mention the finder methods Container implements using the home interface and your deployment descriptor to figure out what to do Container returns the EJB object, but the bean stays in the pool to avoid loading of the stale data
  • 63.
  • 64.
    Message Driven BeansAsynchronous communication…
  • 65.
    MDB: Overview Client(Producer) sends a message to the messaging service Message is delivered to the Container. Client is doing other things Container acknowledges the message to the services, and pulls a bean out of the pool to process the message. Container invokes the beans onMessage() method, with the message as argument The bean’s transaction commits, and is sent back to pool If the bean’s transaction in onMessage had rolled back, the Container would have told the messaging service to put the message back on the queue.
  • 66.
    MDBs are asynchronousMultiple beans of same type can process messages concurrently Container makes sure that each bean is thread safe
  • 67.
    State chart: MDBEJB EJB 1. constructor 2. setMessageDrivenContext 3. ejbCreate() does not exist method ready ejbRemove() or timeout Bean throws system exception (uncheked, uncaught) onMessage()
  • 68.
  • 69.
    JMS destination Whatis JMS Destination? Where did you specify the JMS destination in the code?
  • 70.
    Flavors of MessagingTopics Uses Publish and Subscribe method. One bean per pool gets a copy. Types are: Durable Subscription Consumer sees all the messages, even if offline Non-Durable Subscription Consumer must be online to view the message Queues FIFO. Only one bean gets the message. Producer sends the message for single consumer
  • 71.
    What if somethinggoes wrong? What if the bean getting the message dies or throws an exception? Handled using acknowledgement: Container tells the Messaging service that everything is fine if message delivered Tells to put message back in queue if something bad happens
  • 72.
    How is ittracked? The transaction status Is tied to whether the transaction commits or rolls back. You get this behavior for beans that uses CMT The method completion Is tied to whether the message completes successfully. You get this behavior for beans that use BMT
  • 73.
  • 74.
    Exceptions in EJBHandle the bad…
  • 75.
    Security in EJBThe secrets…
  • 76.
  • 77.
    Deployment Prepare theenvironment…
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.

Editor's Notes

  • #5 In Older days, each app server vendor had its own proprietary API. You learn it then work with it. If you need a new feature, its totally vendor dependent.
  • #7 If you are an object and you have a reference to another object, that object must be in the same heap with you.
  • #30 JRMP is Java Remote Method Protocol and is only Java to Java. Here you can be sure that the object that you get is the one you asked for.
  • #33 RMI-IIOP compatible arguments are : Serializable, primitive types, Remote, or array or a collections of any of those. Application exceptions or compiler checked exceptions extends Exception class and runtime exceptions are a subclass of RuntimeExceptions.
  • #34 isIdentical(): Stateless Session Bean: True, if both references come from same Home, even if stubs are referring to two different Remote EJB Objects Stateful Session Bean: False no matter what, for any two unique stubs, even if for same home Entity Beans: True if the stubs refer to two entities with the same Primary Key. How are the three remove() methods different?
  • #41 When ejbPassivate() completes, every non-transient instance variable must be a reference to one of the following: A serializable object A null value A bean’s remote component or home interface, even if the stub class is not serializable A bean’s local component or home interface, even if the stub class is not serializable A SessionContext object, even if its not serializable A bean’s special JNDI context,or any of its sub-context The UserTransaction interface A resource manager connection factory (like DataSource)
  • #57 Is different from Stateless Session bean which calls the ejbActivate() and ejbPassivate(), and hence has to serialize and save the state.