Enterprise Java Beans 3 - Business Logic


Published on

Enterprise Java Beans 3 - Business Logic

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Enterprise Java Beans 3 - Business Logic

  1. 1. Setting Business Logic with EJB
  2. 2. Concurrency and thread safety: The containeremploys concurrency or thread safety.Remoting and web services: RMI and SOAPWebservices.Transaction and security management: Sessionbeans use pure configuration-basedtransactions, authorization, and authentication.Timer services and interceptors: Interceptors areEJB’s version of AOP, Timer services is nothingbut schedulers.
  3. 3. EJB3:Provides robust support for accessing remote components or theability to seamlessly expose your business logic as web services.Provides instance pooling, automated session state maintenance,and passivation/activation.It is an integral part of the Java EE standard.It provides portability, standardization, and vendor support.Spring:Provides elegant utilities such as JdbcTemplate and JmsTemplate.It has has great DI which only works for container components inEJB 3Spring AOP or AspectJ is a much more feature-rich choice than EJB3 interceptors.
  4. 4. Each session bean implementation has two distinctparts—one or more bean interfaces and a beanimplementation class.Interface-based programming is the practice of notusing implementation classes directly wheneverpossible promoting loose coupling.An interface through which a client invokes the bean iscalled a business interface.A business interface can be remote or even webservice-accessible.A single EJB can have multiple interfaces i.e. EJBimplementation classes can be polymorphic, meaningthat different clients using different interfaces coulduse them in completely different ways.
  5. 5. Each interface that the bean intends to support mustbe explicitly included in the bean implementationclass.Session bean implementation classes can never beabstract, which means that all methods mandated bydeclared business interfaces must be implemented inthe class.The EJB implementation classes can have nonprivatemethods that are not accessible through any interfaceuseful for creating clever unit-testing frameworks.An EJB bean class can make use of OO inheritanceputting commonly used logic in a parent POJO class.
  6. 6. A session bean must have at least one business interface.The session bean class must be concrete and cannot be defined aseither final or abstract since the container needs to manipulate it.There must be a no-argument constructor in the bean class as it isinvoked by the container to instantiate the bean.A session bean class can subclass another session bean or any otherPOJO.The business methods and lifecycle callback methods may be definedeither in the bean class or in a superclass.Annotation inheritance is supported with several limitations with EJB 3session beans. (e.g. @Stateless or @Stateful defined in parent class isignored in child class but not for resource injection annotations.)Business method names must not start with “ejb.” because it mayinterfere with EJB infrastructure processing.Define all business methods as public, but not final or static.The arguments and the return type of the method implement thejava.io.Serializable interface when method is exposed in remotebusiness interface.
  7. 7. A particular business process may involve morethan one session bean method call during whichit can maintain a conversational state.A bean that maintains conversational state“remembers” the results of previous exchanges,and is a stateful session bean.Stateful session beans tend to model multistepworkflows, while stateless session beans tend tomodel generalpurpose, utility services used bythe client.
  8. 8. The container manages almost every aspect ofsession beans which enables it to provideabstractions including DI, automatedtransaction management, AOP, transparentsecurity management.
  9. 9. The lifecycle for a session bean starts when a bean instance iscreated.The creation happens when a client receives a reference to thebean either by doing a JNDI lookup or by using dependencyinjection.Steps involved in initializing a Bean: The container invokes the newInstance method on the beanobject, which essentially translates to a constructor invocationon the bean implementation class. If the bean uses DI, all dependencies on resources, otherbeans, and environment components are injected into thenewly created bean instance.After the container determines that an instance is no longerneeded, the instance is destroyed.The callbacks allow the bean to be notified when some of itslifecycle transitions happen.
  10. 10. Lifecycle callbacks are bean methods (not exposed by a businessinterface) that the container calls to notify the bean about alifecycle transition, or event.When the event occurs, the container invokes the correspondingcallback method, and which can be used to perform business logicor operations such as initialization and cleanup of resources.A PostConstruct callback is invoked just after a bean instance iscreated and dependencies are injected.A PreDestroy callback is invoked just before the bean is destroyedand is helpful for cleaning up resources used by the bean.The process in which the container decides to deactivate a statefulbean instance temporarily when not in use is called passivation.The process in which the container activates the bean instanceagain when the client needs it called activation.The @PrePassivate and @PostActivate annotations apply to thepassivation and activation lifecycle events.A lifecycle callback method either in the bean class or in a separateinterceptor class.
  11. 11. Callback Annotation Type of EJB Typically Used For...javax.annotation.PostConstructStateless, stateful,MDBInvoked after a beaninstance is created anddependencyinjection is complete.javax.annotation.PreDestroyStateless, stateful,MDBinvoked priorto a bean instance beingdestroyed.javax.ejb.PrePassivateStateful invoked priorto a bean instance beingpassivated.javax.ejb.PostActivateStateful invoked aftera bean instance isactivated
  12. 12. Stateless session beans don’t maintainconversational state and are the mostperformance efficient.The stateless beans are pooled i.e. for eachmanaged bean, the container keeps a certainnumber of instances handy in a pool.For each client request, an instance from thepool is quickly assigned to the client.When the client request finishes, the instance isreturned to the pool for reuse.
  13. 13. @Target(TYPE) @Retention(RUNTIME)public @interface Stateless {String name() default "";String mappedName() default "";String description() default "";}Name specifies the name of the bean and is also used to bindthe EJB to the global JNDI tree (server’s managed resourceregistry).If the name parameter is omitted, the container assigns thename of the class to the bean.MappedName is a vendor-specific name that can be assignedto the EJB.
  14. 14. Local interface: It is designed for clients with the beanscollocated in the same container (JVM) instance.An interface can be designated as a local business interface byusing the @Local annotation.Remote interface: It is designed for clients with beans residingoutside the EJB container’s JVM instance.EJB 3 enables a stateless bean to be made accessible via RMIthrough the @Remote annotation.A remote business interface may extend java.rmi.Remote.All parameters and return types of remote business interfacemethods must be Serializable.Web service endpoint interface: It is the ability to expose astateless session bean as a SOAP-based web service.The @WebService annotation doesn’t place any specialrestrictions on either the interface or the implementing bean.
  15. 15. We cannot mark the same interface with more thanone access type annotation.A business interface can extend another interface, andcan remove code duplication by creating a businessinterface that has common methods and businessinterfaces that extend the common “parent” interface.To apply the @Local, @Remote, or @WebServiceannotation in the bean class without having toimplement the business interface as follows:@Remote(BidManager.class)@Statelesspublic class BidManagerBean { ... }
  16. 16. Creates bean instances using the default constructor asneeded.Injects resources such as database connections.Puts instances in a managed pool.Pulls an idle bean out of the pool when an invocationrequest is received from the client (the container mayhave to increase the pool size at this point).Executes the requested business method invokedthrough the business interface by the client.When the business method finishes executing, pushesthe bean back into the “method-ready” pool.As needed, retires (a.k.a. destroys) beans from thepool.
  17. 17. There are two types of stateless session bean lifecyclecallback methods:Callbacks that are invoked when the PostConstructevent occurs immediately after a bean instance iscreated and set up, and all the resources are injected.Callbacks that are invoked when the PreDestroy eventoccurs, right before the bean instance is retired andremoved from the pool.There can be multiple PostConstruct and PreDestroycallbacks for a given bean in a class or in a separateinterceptor class.The lifecycle callback methods embedded in the beani.e. initialize and cleanup methods cannot throwchecked exceptions.
  18. 18. Unlike with stateless beans, the container makes surethat subsequent method invocations by the sameclient are handled by the same stateful bean instance.The one-to-one mapping between a client and a beaninstance makes saving bean conversational state.Bean instances cannot be readily returned to the pooland reused while a client session is still active.The Bean instance waits for the next request from theclient owning the session.The stateful session bean instances held by a largenumber of concurrent clients can have a significantmemory footprint.
  19. 19. Stateful bean instance variables used to storeconversational state must be Java primitives orSerializable objects.Since stateful session beans cannot be pooled andreused, they should be a way to destroy when toomany of them are accumulated.Business method must be defined for removing thebean instance by the client using the @Removeannotation.Stateful session beans have the PrePassivate (beforepassivation of bean instance) and PostActivate (after abean instance is bought back to memory) lifecyclecallback methods.
  20. 20. Stateful session beans support local andremote invocation through the @Local and@Remote annotations.A stateful session bean cannot have a webservice endpoint interface because SOAP-based web services are inherently statelessin nature.There should be at least one @Removeannotated method in your stateful bean’sbusiness interface.
  21. 21. Always creates new bean instances using the default constructorwhenever a new client session is started.Injects resources.Stores the instance in memory.Executes the requested business method invoked through thebusiness interface by the client.Waits for and executes subsequent client requests.If the client remains idle for a period of time, the containerpassivates the bean instance. Essentially, passivation means that thebean is moved out of active memory, serialized, and stored intemporary storage.If the client invokes a passivated bean, it is activated (brought backinto memory from temporary storage).If the client does not invoke a passivated bean instance for a periodof time, it is destroyed.If the client requests the removal of a bean instance, it is firstactivated if necessary and then destroyed.
  22. 22. If clients don’t invoke a bean for a long enough time,the bean is not kept in memory to avoid out ofmemory issues. Such technique is called passivation.Passivation means saving a bean instance into diskinstead of holding it in memory by serializing the entirebean instance and moving it into permanent storage.Activation is the opposite of passivation and is done byretrieving the bean instance from permanent storage,deserializing it, and moving it back into memory.The point of the PrePassivate callback is to give thebean a chance to prepare for serialization.The point of the PostActivate callback is getting hold ofresources that either are not instantiated or were lostduring the serialization/deserialization process.
  23. 23. Calling business methods marked with the@Remove annotation signifies a desire by theclient to end the session by immediate beandestruction.It is critical to remove the stateful beaninstances when the client is finished with itswork instead of relying on the container todestroy them when they time out.
  24. 24. Features Stateless StatefulConversational state No YesPooling Yes NoPerformance problems Unlikely PossibleLifecycle events PostConstruct,PreDestroyPostConstruct, PreDestroy,PrePassivate, PostActivateTimer Yes NoSessionSynchronizationfor transactionsNo YesWeb services Yes NoExtendedPersistenceContextNo Yes
  25. 25. The client obtains a reference to the sessionbeans directly or indirectly from JNDI.All session bean invocations are made throughan interface appropriate for the access type.The client makes as many method calls as arenecessary to complete the business task athand.In case of a stateful session bean, the last clientinvocation should be a remove method.
  26. 26. The @EJB annotation is specifically intended for injecting sessionbeans into client codeThe injection is only possible within managed environments in coderunning inside an application-client container or in componentsregistered with the web container.@Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME)public @interface EJB {String name() default "";Class beanInterface() default Object.class;String beanName() default "";}The name element suggests the JNDI name that is used to bind theinjected EJB in the environment-naming context. It is derived fromthe interface name if the JNDI name is absent.The beanInterface specifies the business interface to be used toaccess the EJB.The beanName element allows us to distinguish among EJBs ifmultiple EJBs implement the same business interface.
  27. 27. A stateful session can be injected intoanother stateful session bean instance.A stateful session bean should not beinjected into a stateless object, such that astateless session bean or servlet may beshared by multiple concurrent clients.Injecting an instance of a stateless sessionbean into a stateful session bean isperfectly legal.
  28. 28. EJB 3 adds extended persistence contextsspecifically geared toward stateful sessionbeans.Application servers provide high availability byclustering EJB containers running the samestateful bean.A clustered EJB container replicates sessionstate across container instances.It is routed to another container instanceseamlessly on crash of clustered containerinstance without losing state.
  29. 29. The data stored in the conversation state should beexamined to have a minimal total memory footprintfor the stateful bean.The conversational state is replicated betweendifferent instances of the EJB container.Improper use of passivation policies causesperformance problems.Explicitly removing the outdated bean instancesrather than depending on the container to time themout solving the potential memory problems.Annotating a method using @Remove annotationsignals the container to remove the bean instance.
  30. 30. Replacing stateful beans with a combination ofpersistence and stateless processing, by moving stateinformation from memory to the database on everyrequest.Building a mechanism at the client side to maintain state,such as storing the state as an object in client memory orin a file.Both approaches don’t guarantee high availability of theapplication, automated passivation and robust,transparent state maintenance.Session state can be maintained in the web containerusing HttpSession object of Servlet API, but too much datain HttpSession could decrease performance of the servletcontainer and is not applicable for thick or Java SE clients.
  31. 31. Choose bean type carefully: Examine if application needs statefulsession beans.Examine interface types for session beans: Remote interfacesinvolve network access slowing down the application and must beavoided for local interface for client using same JVM.In DI, a stateful session bean should not be injected into astateless session bean or servlet.Separate crosscutting concerns such as logging and auditing usingbusiness interceptors.Closely examine the kind of data being stored in the conversationstate: Use small, primitive instance variables in a stateful beanwhenever possible as opposed to large nested composite objects.Don’t forget to define remove methods in a stateful session bean.Tune passivation and timeout configurations to find the optimalvalues for your application.
  32. 32. Point to Point Messaging: A single message travels from asingle producer (point A) to a single consumer (point B).PTP message destinations are called queues.PTP doesn’t guarantee that messages are delivered in anyparticular order.If more than one potential receiver exists for a message, arandom receiver is chosen.A single producer produces a message that is received by anynumber of consumers who happen to be connected to thedestination at the time.The message destination in this model is called a topic and aconsumer is called a subscriber.Pub-sub messaging works particularly well in broadcastinginformation across systems
  33. 33. A third kind of model called request-reply givesthe message receiver enough information sothat they might “call us back.” typicallyimplemented on top of either the PTP or pub-sub models.
  34. 34. @Resource(name="jms/QueueConnectionFactory")private ConnectionFactory connectionFactory;@Resource(name="jms/ShippingRequestQueue")private Destination destination;Connection connection = connectionFactory.createConnection();Session session = connection.createSession(true,Session.AUTO_ACKNOWLEDGE);MessageProducer producer = session.createProducer(destination);ObjectMessage message = session.createObjectMessage();ShippingRequest shippingRequest = new ShippingRequest();shippingRequest.setItem(item);message.setObject(shippingRequest);producer.send(message);session.close();connection.close();
  35. 35. Administrative Objects are resources that are created andconfigured outside the code and stored in JNDI.JMS has two administrative objects:javax.jms.ConnectionFactory and javax.jms.Destination.Connection factory retrieved using dependency injection withthe @Resource annotation which contains all the configurationinformation needed to connect to MOM.createConnection method creates a live MOM connectionwhich is thread-safe and designed to be sharable.JMS session provides a single-threaded, task-oriented contextfor sending and receiving messages.The first parameter of the createSession method specifieswhether the session is transactional, i.e. messages won’t berealized until either the session is closed or commited.MessageProducer is used to send messages using the sendmethod to the shipping request queue.
  36. 36. The Message interface standardizes what is exchangedacross JMS and is an extremely robust data encapsulationmechanism.JMS message has the following parts: the message header,message properties, and the message body.Headers are name-value pairs common to all messages.Message properties are similar to headers, but areexplicitly created by the application instead of beingstandard across messages.A property can be a boolean, byte, double, float, int, long,short, String, or Object.The message body contains the contents of the envelope; itis the payload of the message.
  37. 37. Message-driven beans are EJB componentsdesigned to consume the asynchronousmessages.
  38. 38. MDBs can receive messages from any enterprise informationsystem (EIS) using the Java EE Connector Architecture (JCA).Messages can be sent to an MDB by implementing a JCA-compliant adapter/connector that includes support for messageinflow contract.Once JCA resource adapter or connector is deployed to a Java EEcontainer, the message inflow contract can be used to have anasynchronous message delivered to an endpoint inside thecontainer.A JCA endpoint is essentially the same as a JMS destination—itacts as a server proxy to an MDB (a message consumer/listener inJMS terms).As soon as a message arrives at the endpoint, the containertriggers any registered MDBs listening to the endpoint anddelivers the message to it.The MDB implements a listener interface that is appropriate tothe JCA connector/message type and passes activationconfiguration parameters to the JCA connector and registers as alistener to the JCA connector.
  39. 39. Multithreading: Provides multithreadedmessage consumers that can process messagesconcurrently by managing incoming messagesamong multiple instances of beans.As soon as a new message reaches thedestination, an MDB instance is retrieved fromthe pool to handle the message.
  40. 40. Simplified messaging code: MDBs relievesfrom coding the mechanical aspects ofprocessing messages by using sensible defaultsfor common circumstances or, by using simpleannotations or deployment descriptor forcustom configuration.Starting message consumption: Invocation ofthe appropriate method to start picking upmessages from the shipping request queue.
  41. 41. The MDB class must directly (using the implements keyword inclass declaration) or indirectly (through annotations ordescriptors) implement a message listener interface.The MDB class must be concrete and cannot be either a final oran abstract class.The MDB must be a POJO class and not a subclass of anotherMDB.The MDB class must be declared public.The bean class must have a no-argument constructor (defaultconstructor).A finalize method cannot be defined in the bean class. ThePreDestroy method should be defined for any cleanup code ifnecessary.The methods defined in the message listener interface must beimpemented and should be public and cannot be static or final.The javax.rmi.RemoteException or any runtime exceptionsshould not be thrown for any method. If a RuntimeException isthrown, the MDB instance is terminated.
  42. 42. @MessageDriven(name="ShippingRequestProcessor",activationConfig = {@ActivationConfigProperty(propertyName="destinationType",propertyValue="javax.jms.Queue"),@ActivationConfigProperty(propertyName="destinationName",propertyValue="jms/ShippingRequestQueue")})
  43. 43. public class ShippingRequestProcessorMDB implements MessageListener {private java.sql.Connection connection;private DataSource dataSource;@Resourceprivate MessageDrivenContext context;@Resource(name="jdbc/TurtleDS")public void setDataSource(DataSource dataSource) {this.dataSource = dataSource; }@PostConstructpublic void initialize() {try { connection = dataSource.getConnection(); } catch (SQLException) { .. }}@PreDestroypublic void cleanup() {try { connection.close(); connection = null; } catch (SQLException) {..}}public void onMessage(Message message) {try {ObjectMessage objectMessage = (ObjectMessage)message;processShippingRequest((ShippingRequest)objectMessage.getObject());} catch (JMSException jmse) { jmse.printStackTrace(); context.setRollBackOnly(); }}
  44. 44. @Target(TYPE)@Retention(RUNTIME)public @interface MessageDriven {String name() default "";Class messageListenerInterface default Object.class;ActivationConfigProperty[] activationConfig() default {};String mappedName();String description();}The name parameter specifies the name of the MDB.If the name element is omitted, the code uses the name of the class.The messageListenerInterface specifies which message listener the MDBimplements.The last parameter, activationConfig, is used to specify listener-specificconfiguration properties.
  45. 45. The container uses the MessageListener interface toregister the MDB with the message provider and topass incoming messages by invoking implementedmessage listener methods.@MessageDriven(name="ShippingRequestJMSProcessor",messageListenerInterface="javax.jms.MessageListener")public class ShippingRequestProcessorMDB { .. }public class ShippingRequestProcessorMDBimplements MessageListener { .. }
  46. 46. The activationConfig property of the @MessageDriven annotationallows to provide messaging system–specific configuration informationthrough an array of ActivationConfigProperty instances.public @interface ActivationConfigProperty {String propertyName();String propertyValue();}Each activation property is essentially a name-value pair that theunderlying messaging provider understands and uses to set up theMDB.Most common JMS activation configuration properties: destinationType,connectionFactoryJndiName, and destinationName.The destinationType property tells the container this JMS MDB islistening to a javax.jms.Queue or javax.jms.Topic.The connectionFactoryJndiName specifies the JNDI name of theconnection factory that should be used to create JMS connections forthe MDB.The destinationName parameter specifies that we are listening formessages arriving at a destination with the JNDI name ofjms/ShippingRequestQueue.
  47. 47. Messages are not actually removed from thequeue until the consumer acknowledges them.(default is AUTO_ACKNOWLEDGE).We could change the acknowledge mode toDUPS_OK_ACKNOWLEDGE as follows:@ActivationConfigProperty(propertyName="acknowledgeMode",propertyValue="DUPS_OK_ACKNOWLEDGE")
  48. 48. Acknowledgment Mode Description Supported withMDBAUTO_ACKNOWLEDGE The session automatically acknowledgesreceipt after a message has been receivedor is successfully processed.YESCLIENT_ACKNOWLEDGE Have to manually acknowledge thereceipt of the message by calling theacknowledge method on the message.NODUPS_OK_ACKNOWLEDGEThe session can lazily acknowledgereceipt of the message. This is similar toAUTO_ACKNOWLEDGE but usefulwhen the application can handle deliveryof duplicate messages and rigorousacknowledgment is not a requirement.YESSESSION_TRANSACTED This is returned for transacted sessions ifthe Session.getAcknowledgeModeNO
  49. 49. Specifies whether the topic subscription is durable ornondurable for an MDB listening on a topic.Durable subscription on a topic provides guaranteed deliveryto the consumer for all the messages sent to the topic.If the durable subscriber is not connected to a topic when amessage is received, MOM retains a copy of the message untilthe subscriber connects and delivers the message.@ActivationConfigProperty(propertyName="destinationType",propertyValue="javax.jms.Topic"),@ActivationConfigProperty(propertyName="subscriptionDurability",propertyValue="Durable")
  50. 50. The messageSelector property is the MDB parallel to applying aselector for a JMS consumer.Messages retrieved can be filtered by using a message selector,a criterion applied to the headers and properties of messagesspecifying which messages the consumer wants to receive.The selector syntax is identical to the WHERE clause in SQL, butit uses message header and property names instead of columnnames.Selector expressions include literals, identifiers, whitespace,expressions, standard brackets, logical and comparisonoperators, arithmetic operators, and null comparisons.@ActivationConfigProperty(propertyName="messageSelector",propertyValue="Fragile IS TRUE")
  51. 51. Type Description ExampleLiterals Can be strings, exact or approximatenumeric values, or booleans.BidManagerMDB100 TRUEIdentifiers Can be a message property or headername; case sensitive.RECIPIENTNumOfBids FragileJMSTimestampWhitespace Same as defined in the Java languagespecification: space, tab, form feed, andline terminator.ComparisonoperatorsComparison operators, such as =, >, >=,<=, <>.RECIPIENT=BidManagerMDB‘ NumOfBids>=100LogicaloperatorsAll three types of logical operators—NOT, AND, OR—are supported.RECIPIENT=BidManagerMDB‘ ANDNumOfBids>=100Null comparison IS NULL and IS NOT NULL comparisons. FirstName IS NOT NULLTrue/falsecomparisonIS [NOT] TRUE and IS [NOT] FALSEcomparisons.Fragile IS TRUEFragile IS FALSE
  52. 52. Creates MDB instances and sets them upInjects resources, including the message-drivencontextPlaces instances in a managed poolPulls an idle bean out of the pool when a messagearrives (the container may have to increase the poolsize at this point)Executes the message listener method; e.g., theonMessage methodWhen the onMessage method finishes executing,pushes the idle bean back into the “method-ready”poolAs needed, retires (or destroys) beans out of the pool
  53. 53. The queue and the connection factory are injected by using the @Resourceannotation:@Resource(name="jms/ShippingErrorQueue")private javax.jms.Destination errorQueue;@Resource(name="jms/QueueConnectionFactory")private javax.jms.ConnectionFactory connectionFactory;Then create and destroy a shared javax.jms.Connection instance usinglifecycle callbacks.@PostConstructpublic void initialize() { connectionFactory.createConnection(); }@PreDestroypublic void cleanup() { … }Finally, the business method that sends the error message.private void sendErrorMessage(ShippingError error) { … }
  54. 54. Choose the messaging models carefully: PTP or pub-subRemember modularization: Business logic should be decoupled andmodularized away from messaging-specific concerns.Make good use of message filters: Multi purpose use of singlemessaging destination.Choose message types carefully: Using XML strings for messaging topromote loose coupling between systems or using binary streams todecrease the size of the message.Be wary of poison messages: On runtime failure message processing,the container is forced to roll back the transaction and put themessage back on the queue instead of acknowledging it, which arecalled poison messages. It is avoided by setting up redelivery countand dead message queue for the shipping poison messages as therequest destination,Configure MDB pool size: Specifies the maximum number ofinstances of a particular MDB the container can create.