IS2103 - AY2425S1 - Lecture 05 (1).pdf

Full Transcript

Lecture 5 Jakarta Enterprise Beans (II) IS2103 – Enterprise Systems Server-side Design and Development AY 2024/25 Semester 1 Lecturer: A/P TAN Wee Kek...

Lecture 5 Jakarta Enterprise Beans (II) IS2103 – Enterprise Systems Server-side Design and Development AY 2024/25 Semester 1 Lecturer: A/P TAN Wee Kek Email: [email protected] :: Tel: 6516 6731 :: Office: COM3-02-35 Consultation: Tuesday, 12 pm to 2 pm. Additional consultations by appointment are welcome. Quick Recap…  In the previous lecture, we learnt various basic concepts of developing with the EJB technology:  Enterprise beans are components in Jakarta EE that implement the EJB technology.  There are two types of enterprise Enterprise Systems Security beans, i.e., session bean and Enterprise Systems Testing Message-Driven Bean. Enterprise Systems Configuration Management  Session beans are method Advanced Development Distributed Computing Jakarta Persistence (II) Jakarta Persistence (I) Jakarta Enterprise Jakarta Enterprise invocation components. Web Services Beans (II) Concepts Beans (I)  Message-Driven Beans are message sending components. Enterprise Systems Architecture Introduction to Enterprise Systems 1 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Quick Recap… (cont.)  There are three types of session beans, i.e., stateful, stateless and singleton, each with different characteristics and used for different purposes.  Session beans may be invoked by both local and/or remote clients depending on scenarios for maximum flexibility and optimal performance. Enterprise Systems Security Enterprise Systems Testing  This lecture continues our Enterprise Systems Configuration Management journey to learn the advanced Advanced Development Distributed Computing Jakarta Persistence (II) Jakarta Persistence (I) Jakarta Enterprise Jakarta Enterprise concepts of developing with the Web Services Beans (II) Concepts Beans (I) EJB technology. Enterprise Systems Architecture Introduction to Enterprise Systems 2 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Learning Objectives  At the end of this lecture, you should understand:  Roles of session beans in a typical business application.  Lifecycles of session beans.  Asynchronous method invocation in session beans.  The basics of developing Enterprise Systems Security Message-Driven Beans. Enterprise Systems Testing  Lifecycles of Message-Driven Beans. Enterprise Systems Configuration Management Advanced Development Distributed Computing Jakarta Persistence (II) Jakarta Persistence (I) Jakarta Enterprise Jakarta Enterprise Web Services Beans (II) Concepts Beans (I) Enterprise Systems Architecture Introduction to Enterprise Systems 3 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Readings  Required readings:  Java EE 8 Tutorial:  Chapter 35 – Enterprise Beans – https://javaee.github.io/tutorial/ejb- intro.html  Chapter 39 – Using Asynchronous Method Invocation in Session Beans – https://javaee.github.io/tutorial/ejb-async.html  Suggested readings:  None. 4 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Roles of Session Beans  Recall that a session bean is designed to perform a task for a client in the business tier or logic tier.  We can broadly classify session beans into three main roles in a typical business application: Role Type of Logic Extent of Reuse Relation to Encapsulated within Logic Tier Enterprise Domain Entity Service Model business entity. High – Agnostic to Business-centric Functional boundary and business processes. entities. context restricted to a single business entity. Task Service Model business Low Business processes. tasks/processes. Utility Service Model infrastructural Very High Non-business centric. services, not business logic. 5 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Roles of Session Beans (cont.)  Examples of entity services in an e-commerce system:  Customer session bean:  Create new customer.  Retrieve customer.  Update customer.  Delete customer.  Export customer data.  Product session bean:  Create new product.  Retrieve product.  Update product.  Delete product.  Import product catalog data. 6 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Roles of Session Beans (cont.)  Examples of task services in an e-commerce system:  Customer Profile Management session bean:  Register new customer.  Customer login.  Change customer profile.  Change password.  Checkout session bean:  Add item to shopping cart.  Remove item from shopping cart.  Update item in shopping cart.  Empty shopping cart.  Checkout shopping cart. 7 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Roles of Session Beans (cont.)  Payment Processing session bean:  Perform credit card payment processing:  Visa, MasterCard, Amex, etc.  Perform other non-credit card payment processing.  Examples of utility services in an e-commerce system:  Data Import and Export session bean:  Import and export CSV/Excel format.  Data Encryption session bean:  Hash data.  Encrypt and decrypt data.  Communication session bean:  Send email.  Send SMS message. 8 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Component Reusability of Session Beans within Logic Tier Role Example Reusability Entity Service Customer session bean High Reused by: Customer Profile Management session bean Checkout session bean Task Service Customer Profile Low Management session bean Not reused by other components Directly used by presentation tier Utility Service Data Import and Export Very High session bean Reused by: Customer session bean Product session bean Any other components that require data import and export. 9 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Mapping Session Bean Roles to Types  Which types of session bean should be used to implement the various roles? Role of Session Session Bean Note Bean Type Entity Service Stateless Each stateless session bean can be pooled to optimise performance. Task Service Stateless Each stateless session bean can be pooled to optimise performance. Stateful When conversational state need to be retained for one unique user, e.g., Checkout session bean. Utility Service Stateless Each stateless session bean can be pooled to optimise performance. Singleton When conversational state need to be shared among all users, e.g., Foreign Currency Conversion session bean. 10 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Lifecycles of Session Beans  A session bean goes through various stages during its lifetime, or lifecycle:  Understanding lifecycles helps us to program a session bean to do the right thing at the right time.  Each type of session bean has a different lifecycle:  Stateful session beans have a more complex lifecycle.  Stateful session beans need to maintain conversational state throughout the duration of the client/bean session.  The lifecycle of stateful session beans need to take into consideration the preservation of the conversational state.  Stateless and singleton session beans follow a same and simpler lifecycle. 11 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Lifecycle of Stateful Session Beans  Does Not Exist:  Client initiates the lifecycle by obtaining a reference to a stateful session bean. 1  EJB container creates a new instance (invokes constructor) of the bean and returns reference to client. 12 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Lifecycle of Stateful Session Beans (cont.) 2  Container performs dependency injection if there is any:  E.g., obtaining references to other session beans or container resource (e.g., database or transaction related). 3  Container invokes the method annotated with @PostConstruct if there is any.  Access to dependencies can only be made from this point onwards.  Ready:  The bean is now ready to have its business methods invoked by the client.  While in the ready stage, EJB container may deactivate, or passivate, the bean by moving it from memory to secondary storage. 13 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Lifecycle of Stateful Session Beans (cont.)  EJB container typically uses a least-recently-used algorithm to select a bean for passivation.  Passive:  EJB container invokes the method annotated with @PrePassivate immediately before passivating it if there is any.  If client invokes a business method while the bean is in the passive stage, the EJB container activates the bean.  The method annotated @PostActivate is invoked if there is any.  The bean is moved to the ready stage. 14 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Lifecycle of Stateful Session Beans (cont.)  Why do we need to worry about passivation, i.e., entering and leaving the passive state?  A client or user that is selected for passivation is likely to have been idling for a long time or might even have terminated the interaction.  Some business logic might be time sensitive and/or involve finite resources such as booking cinema or plane seats.  During pre-passivate:  Temporarily release the resources to optimise sale window.  During post-activate:  Check whether the previously released resources are still available.  If yes, re-acquire the resources.  If no, inform client or user gracefully. 15 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Lifecycle of Stateful Session Beans (cont.)  End of the lifecycle: 1  Client invokes a method annotated @Remove to signal to the container that the bean instance may be removed 2  EJB container calls the method annotated @PreDestroy if there is any.  The bean’s instance is then ready for garbage collection:  Container determines when a bean instance is actually removed.  Explicit removal of a stateful session bean allows timely recovery of resources:  If the @Remove method is not explicitly called, it might take a while before the container’s removal policies are triggered to remove the bean instance. 16 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Lifecycle of Stateless Session Beans  The lifecycle of a stateless session bean consist of only two stages as it is never passivated.  Does Not Exist:  EJB container creates and maintains a pool of bean instances at deployment time, and whenever necessary.  This begins the stateless session bean’s lifecycle. 1  EJB container performs any dependency injection. 2  The method annotated @PostConstruct is invoked if there is any. 17 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Lifecycle of Stateless Session Beans (cont.)  Ready:  The bean is now ready to have its business methods invoked by the client.  Any pooled instances can be assigned to a client request.  End of the lifecycle:  Removal of pool instances is determined by the EJB container based on default or preconfigured policies.  EJB container calls the method annotated @PreDestroy if there is any.  The specific bean instance is then ready for garbage collection. 18 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Lifecycle of Singleton Session Beans  A singleton session bean is never passivated and has only two stages:  Non-existent and ready.  Similar to a stateless session bean.  Does Not Exist:  EJB container initiates the singleton session bean lifecycle by creating the singleton instance when client obtains a reference.  Initiation can also occur upon application deployment if the singleton is annotated with the @Startup annotation. 1 2  EJB container performs any dependency injection and then invokes the method annotated @PostConstruct if there is any. 19 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Lifecycle of Singleton Session Beans (cont.)  Ready:  The bean is now ready to have its business methods invoked by the client.  End of the lifecycle:  Removal occurs upon application undeployment.  EJB container calls the method annotated @PreDestroy if there is any.  The bean’s instance is then ready for garbage collection. 20 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Lifecycle Methods and Interceptors  Lifecycle methods are automatically invoked by the container before/after a session bean lifecycle activity:  @PostConstruct  @PrePassivate  @PostActivate  @Remove  @PreDestroy  Interceptors are methods that are automatically invoked by the container when the business methods of a session bean are invoked:  @AroundConstruct – When constructor is invoked.  @AroundInvoke – When a business method is invoked. 21 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Lifecycle Methods and Interceptors (cont.)  Lifecycle methods and interceptors can be defined within the bean class or an external class:  @Remove can only be defined in bean class.  When using an external class:  The interceptor class is annotated with @Interceptor.  The target bean class is annotated with @Interceptors, which allow multiple target bean classes to be defined.  Each method must take in an InvocationContext object as its argument:  The @AroundInvoke method returns InvocationContext.proceed() to proceed to the next interceptor in the interceptor chain, if any. 22 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Lifecycle Methods and Interceptors (cont.)  The invocation of the last interceptor method in the chain causes the invocation of the target class method.  Combined effect of lifecycle methods and interceptors: @PostConstruct Method @PreDestroy Invocation Order Constructor @AroundInvoke @Remove (Interceptor Interceptor 1) Interceptor nn @AroundConstruct @AroundInvoke Interceptor n (Interceptor 1) Interceptor Interceptor nn Interceptor n Lifecycle Stages Stateful Only 23 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Beyond Synchronous Method Invocation in Session Beans  Thus far, we have been focusing on session beans involving synchronous method invocation:  This is the default component communication mode.  The client expects a result and needs the result to continue processing.  It is often useful to go beyond synchronous method invocation:  The client expects a result but does not need the result to continue processing – Asynchronous method invocation in session bean.  The client does not expect a result – Asynchronous message sending in Message-Driven Bean. 24 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Beyond Synchronous Method Invocation in Session Beans (cont.) Client SB Client SB Client MDB Synchronous method Asynchronous method Asynchronous message invocation in session bean (SB) invocation in session bean (SB) sending in MDB 25 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Asynchronous Method Invocation in Session Beans  Session beans can implement asynchronous methods:  Control is returned to the client before the method is invoked on the session bean instance.  Clients may then use the Java SE concurrency API to:  Retrieve the result.  Cancel the invocation.  Check for exception. 26 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Asynchronous Method Invocation in Session Beans (cont.)  Asynchronous methods are typically used to:  Improve application response time if the method invocation result is not required immediately.  Increase application throughput.  With respect to presentation tier frontend application.  Asynchronous methods are useful for:  Long-running operations:  Distributed search operation involving multiple sources:  Search for plane seats from multiple airlines.  Distributed transaction involving confirmation by multiple destinations:  Book a flight ticket for a plane seat via a global distribution system. 27 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Asynchronous Method Invocation in Session Beans (cont.)  Processor-intensive tasks:  Processing involves complex algorithms.  Background tasks:  Sending an email or SMS.  With respect to logic tier backend. 28 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Creating an Asynchronous Business Method  Two ways to create asynchronous business method:  Annotate a business method with @Asynchronous to mark that method as an asynchronous method.  Apply @Asynchronous at the class level to mark all the business methods of a session bean as asynchronous methods.  Returning value to client:  Asynchronous methods must return either void or an implementation of the Future interface.  Can only declare application exceptions if the asynchronous method returns Future 29 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Creating an Asynchronous Business Method (cont.)  AsyncResult class is a concrete implementation of the Future interface provided as a helper class for returning asynchronous results.  AsyncResult has a constructor with the result as a parameter, making it easy to create Future implementations. 30 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Creating an Asynchronous Business Method (cont.)  The result is returned to the EJB container and not directly to the client.  EJB container makes the result available to the client.  The session bean can check whether the client has requested that the invocation be cancelled by calling the javax.ejb.SessionContext.wasCancelled method. Some long-running operations After long-running operations have completed, check whether client has attempted to cancel processing. 31 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Creating an Asynchronous Business Method (cont.)  A more accurate view of asynchronous method invocation in session bean: Client SB Client SB Container Result returned to container Future.get 32 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Calling Asynchronous Methods from Clients  Session bean clients call asynchronous methods just like non-asynchronous business methods.  If the asynchronous method returns a result, the client receives a Future instance as soon as the method is invoked.  The Future instance can be used to:  Check whether invocation has completed.  Retrieve final result.  Check whether invocation was cancelled (on the logic tier).  Cancel invocation (from the presentation tier).  Check whether any exception was thrown during processing. 33 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Calling Asynchronous Methods from Clients (cont.)  Retrieving the final result:  Use one of the Future.get methods.  Calling a get method will block client until the invocation completes.  The Future.isDone method can be used to determine if processing has completed before calling a get method. Future.get Future.isDone OR Create child thread Client 34 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Calling Asynchronous Methods from Clients (cont.)  Cancelling an asynchronous invocation:  On the client side, the Future.isCancelled method can be used to check whether the method invocation was cancelled from the server side.  The cancel(boolean mayInterruptIfRunning) method on the Future instance can be called to attempt to cancel the method invocation from the client side.  The cancel method returns true if the cancellation was successful and false if the method invocation cannot be cancelled. 35 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Calling Asynchronous Methods from Clients (cont.)  When the invocation cannot be cancelled:  The mayInterruptIfRunning parameter is used to alert the session bean instance on which the method invocation is running that the client attempted to cancel the invocation:  mayInterruptIfRunning set to true  SessionContext.wasCancelled return true.  mayInterruptIfRunning set to false  SessionContext.wasCancelled return false. Future.cancel(true|false) Invocation is cancelled OR Client check Session bean check Future.isDone SessionContext.wasCancelled() AND Future.isCancelled Client Session Bean 36 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Recap on Message-Driven Bean (MDB)  Acts as a listener for a particular messaging type, such as the Jakarta Messaging API (JMS).  Execution is triggered by sending messages instead of by method invocations.  Facilitates event-driven processing:  Similar to an event listener but receives JMS messages instead of events.  JMS messages can be sent by any Jakarta EE component, a JMS application or a system that does not use Jakarta EE technology.  Process messages asynchronously. 37 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) More about MDB  Characteristics of MDB:  An MDB executes upon receipt of a single client message.  A single MDB can process messages from multiple clients.  A MDB instance does not maintain conversational state for a specific client, i.e., MDB is stateless.  EJB container can pool multiple instances of a MDB to allow streams of messages to be processed concurrently.  All instances of a MDB are equivalent and EJB container can assign a message to any MDB instance.  Can invoke session beans and access/update database. 38 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) More about MDB (cont.)  Similar to a stateless session bean, we can configure a MDB properties:  steady-pool-size:  Specifies the initial and minimum number of beans maintained in the pool.  The default is 0.  max-pool-size:  Specifies the maximum number of beans that can be created to satisfy client requests.  The default is 32.  resize-quantity:  Specifies the number of beans to be created if a request arrives when the pool is empty. 39 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) More about MDB (cont.)  Or the number of beans to remove if idle for more than the idle timeout (subject to the initial and minimum pool size).  The default is 8.  pool-idle-timeout-in-seconds:  Specifies the maximum time in seconds that a bean can remain idle in the pool.  After this amount of time, the bean is destroyed.  The default is 600 (10 minutes).  A value of 0 means a bean can remain idle indefinitely.  MDB is stateless and its variables are mainly used to hold resources across handling of client messages:  An object reference to a session bean object.  An open database resource. 40 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) More about MDB (cont.)  When a message arrives:  The message is actually sent to the EJB container.  EJB container calls the MDB’s onMessage method to process the message.  The onMessage method handles it in accordance with the application’s business logic.  The message is typically casted to one of the five JMS message types for processing. 41 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) More about MDB (cont.)  A more accurate view of asynchronous message sending in MDB: Client MDB Client Container MDB send() onMessage(message) 42 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Message Types  JMS API defines various different types of messages.  Each message type corresponds to a different message body to allow sending and receiving of data in different formats.  Three of the most common message types: Message Type Body Contains TextMessage A java.lang.String object (e.g., the contents of an XML file). MapMessage A set of name-value pairs, with names as String objects and values as Java primitive types. The entries can be accessed sequentially by enumerator or randomly by name. The order of the entries is undefined ObjectMessage A Serializable Java object. 43 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Message Domains  Point-to-Point:  One-to-one model – one producer send a message to one consumer through a virtual channel called queue.  If we configure a queue MDB with steady-pool-size of 1, max- pool-size of 1 and pool-idle-timeout-in-seconds of 0, we will get a FIFO (First-In, First-Out) queue. 44 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Message Domains (cont.)  Publish-and-Subscribe:  One-to-many model – one producer send a message to many consumers through a virtual channel called topic.  Choice of message domains depends on business requirements. 45 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Message Domains (cont.)  A more accurate view of asynchronous message sending in MDB via queue and topic: Container MDB 1 Queue Client Client MDB 2 Client Client MDB 3 Topic … MDB n Producers The container acts The MDBs are considered clients too as the JMS server with respect to the container as the server. But they are known as consumers or subscribers. 46 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Message Domains (cont.)  Recall that MDB is different from software service:  Software service is request-response:  In EJB, web service is implemented with session bean.  MDB is publish-subscribe. Container SB Request Client Client Client Response Client Publish Queue/Topic MDB Subscribe Enterprise Beans 47 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Lifecycle of Message-Driven Beans  A MDB is never passivated and has only two stages:  Nonexistent and ready to receive messages.  Similar to a stateless session bean. 48 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Lifecycle of Message-Driven Beans (cont.)  Does Not Exist:  EJB container creates a pool of MDB instances.  For each instance, the EJB container performs the following two tasks: 1  If MDB uses dependency injection, the container injects these references before instantiating the instance.  The container calls the method annotated @PostConstruct if 2 there is any.  Ready:  The MDB is now ready to receive messages that are sent by the client.  End of the lifecycle:  Similar to stateless session bean. 49 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Summary  Each session bean type has its own lifecycle.  Lifecycle methods may be used to respond to changes in the lifecycle stages of a session bean.  A session bean method may be invoked asynchronously to avoid blocking a client when processing requires an extended period of time.  A MDB provides a more loosely-coupled approach to perform asynchronous processing in a Jakarta EE application using JMS. 50 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Q&A 51 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II) Next Lecture…  Learn about:  Persisting data using Jakarta Persistence.  The object-relational mapping (ORM) concept.  Creating entity classes and managing relationships and inheritance. Enterprise Systems Security  Working with the Enterprise Systems Testing container-managed entity manager. Enterprise Systems Configuration Management Lifecycle of entity instance. Advanced Development Distributed Computing  Jakarta Persistence (II) Jakarta Persistence (I) Jakarta Enterprise Jakarta Enterprise Web Services Beans (II) Concepts Beans (I) Enterprise Systems Architecture Introduction to Enterprise Systems 52 IS2103 (AY 24/25 S1) Lecture 5 – Jakarta Enterprise Beans (II)

Use Quizgecko on...
Browser
Browser