Home >Documents >Module 5 Session Beans. Topics to be Covered: Purpose and Types of Session Beans Stateless Session...

Module 5 Session Beans. Topics to be Covered: Purpose and Types of Session Beans Stateless Session...

Date post:21-Dec-2015
Category:
View:217 times
Download:2 times
Share this document with a friend
Transcript:
  • Slide 1
  • Module 5 Session Beans
  • Slide 2
  • Topics to be Covered: Purpose and Types of Session Beans Stateless Session Beans Stateful Session Beans Session Bean Design Deployment Descriptor Structure
  • Slide 3
  • Session Beans Purpose and Types of Session Beans
  • Slide 4
  • Entities vs. Session Beans Entities Object-Oriented interface for data access Define business logic around a concept Encourages reuse Session Beans Describe workflow by managing interactions among other beans Implement tasks Perform data access directly or through entities
  • Slide 5
  • Data Access and Workflow Data Access Span concepts Read only Workflow Combines the representative concepts defined by entities Booking a room in a hotel Renting a video
  • Slide 6
  • Stateless and Stateful Session Beans Stateless Session Bean Collection of related services (methods) No state preserved between method invocations General purpose and reusable Stateful Session Bean Extension of the client Maintains conversational state Both types of Session Beans are NOT persistent
  • Slide 7
  • Stateful Session Beans Conversational state is shared among all methods in the beans Specific to one scenario Represent process logic Could have a timeout Can be removed Bean instance is destroyed EJB object is invalidated
  • Slide 8
  • Stateless Session Beans Not dedicated to one client Participate in an instance pool Can be reassigned to another EJB object Does not distinguish between clients Could have a timeout Can be removed Bean instance is NOT destroyed EJB object is invalidated
  • Slide 9
  • Session Beans Stateless Session Bean
  • Slide 10
  • A Wandering Bean Lightweight and fast Efficient Easy to develop Swapped freely between EJB objects Overhead of swapping reduced Does not require passivation or activation
  • Slide 11
  • A Forgetful Bean Provides one-shot services (methods) Generic and reusable Not interdependent All information passed in method parameters Traditional transaction processing application Procedure executes No state retained Possible uses include Report generation Stock quotes Validating Credit Cards
  • Slide 12
  • An Unreliable Bean Internal state may be maintained Number of times bean is called Debugging information Reference to a live resource Internal state NOT visible from client Different instances may service different requests Values will change randomly
  • Slide 13
  • Stateless Session Bean Example Business interface: ProcessPayment package edu.weber.processpayment; import edu.weber.domain.Customer; public interface ProcessPayment { public boolean byCheck(Customer customer, CheckDO check, double amount) throws PaymentException; public boolean byCash(Customer customer, double amount) throws PaymentException; public boolean byCredit(Customer customer, CheckCardDO card, double amount) throws PaymentException; }
  • Slide 14
  • Stateless Session Bean Example Remote Interface package edu.weber.processpayment; import javax.ejb.Remote; @Remote public interface ProcessPaymentRemote extends ProcessPayment { } Local Interface package edu.weber.processpayment; import javax.ejb.Local; @Local public interface ProcessPaymentLocal extends ProcessPayment { }
  • Slide 15
  • Stateless Session Bean Example Credit Card Domain Object package edu.weber.processpayment; import java.util.Date; public class CreditCardDO implements java.io.Serializable { final static public String MASTER_CARD = MASTER_CARD; final static public String VISA = VISA; public String number; public Date expiration; public String type; public CreditCardDO(String numbr, Date exp, String typ) { number = numbr; expiration = exp; type = typ; }
  • Slide 16
  • Stateless Session Bean Example Check Domain Object package edu.weber.processpayment; public class CheckDO implements java.io.Serializable { public String checkBarCode; public int checkNumber public CheckDO(String barCode, int number) { checkBarCode = barCode; checkNumber = number; }
  • Slide 17
  • Stateless Session Bean Example Application Exceptions Should describe a business logic problem Should be meaningful to the client Problem is possibly recoverable Do not cause a transaction rollback EJB container treats any exception that does not extend RuntimeException as an application exception Propagated to the calling client as-is Instance variables of the exception should be serializable
  • Slide 18
  • Stateless Session Bean Example EJBException Extends RuntimeException (Unchecked) Implies an unrecoverable problem Non-application exceptions are always wrapped in an EJBException by the EJB container Subsystem checked exceptions like NamingException and SQLException should typically be caught and wrapped in an EJBException All exceptions thrown by Java Persistence interfaces are RuntimeExceptions
  • Slide 19
  • Stateless Session Bean Example ProcessPaymentBean package edu.weber.processpayment; import edu.weber.domain.*; import java.sql.*; import javax.ejb.*; import javax.annotation.Resource; import javax.sql.DataSource; import javax.ejb.EJBException; @Stateless public class ProcessPaymentBean implements ProcessPaymentRemote, ProcessPaymentLocal { final public static String CASH = CASH; final public static String CREDIT = CREDIT; final public static String CHECK = CHECK;
  • Slide 20
  • Stateless Session Bean Example ProcessPaymentBean @Resource(mappedName=java:/DefaultDS) DataSource dataSource; @Resource(name=min) int minCheckNumber; public boolean byCash(Customer customer, double amount) throws PaymentException { return process(customer.getId(), amount, CASH, null, -1, null, null); } public boolean byCheck(Customer customer, CheckDO check, double amount) throws PaymentException { if(check.checkNumber > minCheckNumber) { return process(customer.getId(), amount, CHECK, check.checkBarCode, check.checkNumber, null, null); } else { throw new PaymentException(Check number is too low. Must be at least + minCheckNumber); }
  • Slide 21
  • Stateless Session Bean Example ProcessPaymentBean public boolean byCredit(Customer customer, CreditCardDO card, double amount) throws PaymentException { if(card.expiration.before(new java.util.Date())) { throw new PaymentException(Expiration data has passed); } else { return process(customer.getId(), amount, CREDIT, null -1, card.number, new java.sql.Date(card.expiration.getTime())); }
  • Slide 22
  • Stateless Session Bean Example ProcessPaymentBean public boolean process(int customerID, double amount, String type, String checkBarCode, int checkNumber, String creditNumber, java.sql.Date creditExpDate) throws PaymentException { Connection con = null; PreparedStatement ps = null; try { con = dataSource.getConnection(); ps = con.prepareStatement (INSERT INTO payment (customer_id,amount,type, + check_bar_code,check_number,credit_number,+ credit_exp_date) VALUES(?,?,?,?,?,?,?)); ps.setInt(1,customerID); ps.setDouble(2,amount); ps.setString(3,type); ps.setString(4,checkBarCode); ps.setInt(5,checkNumber); ps.setString(6,creditNumber); ps.setDate(7,creditExpDate); int retVal = ps.executeUpdate(); if(retVal != 1) { throw new EJBException(Payment insert failed); } return true; }
  • Slide 23
  • Stateless Session Bean Example ProcessPaymentBean catch(SQLException sql) { throw new EJBException(sql); } finally { try { if(ps != null) ps.close(); if(con != null) con.close(); }catch(SQLException se) { se.printStackTrace(); } } // finally } // process method } // ProcessPaymentBean class
  • Slide 24
  • Stateless Session Bean Example Injection Accessing Environment Properties ProcessPaymentBean min java.lang.Integer 250
  • Slide 25
  • SessionContext Provides a view into the EJB containers environment Extends javax.ejb.EJBContext @Stateless public class A_Bean implements A_BeanRemote { @Resource private SessionContext context; public void someMethod() { B_BeanRemote b = // Get a remote reference to B_Bean A_BeanRemote mySelf = context.getBusinessObject(A_BeanRemote.class); b.aMethod( mySelf ); }
  • Slide 26
  • Stateless Session Bean Lifecycle Does Not Exist Method-Ready Pool
  • Slide 27
  • Stateless Session Bean Lifecycle Does Not Exist Method-Ready Pool Class.newInstance() injections @PostConstruct
  • Slide 28
  • Stateless Session Bean Lifecycle Does Not Exist Method-Ready Pool @PreDestroy
  • Slide 29
  • Stateless Session Bean Lifecycle Method-Ready Pool Business Methods
  • Slide 30
  • Session Beans Stateful Session Bean
  • Slide 31
  • A Loyal Bean Dedicated to one client Not swapped or pooled Stateful Session Bean remote interface EJB objectremote interface EJB object stub Client Container
  • Slide 32
  • An Attentive Bean Maintains conversational state Methods can be interdependent State predictable from one call to the next Not persistent Not used concurrently
  • Slide 33
  • A Representative Bean Agent for the client Off loads logic on to the server Provides for thin client Encapsulates and Manages processes and workflow Presents a simplified interface to the client Minimizes network traffic Minimizes number of connections
  • Slide 34
  • Stateful Session Bean Example Remote interface: TravelAgentRemote package edu.weber.travelagent; import edu.weber.processpayment.CreditCardDO; import javax.ejb.Remote; import edu.weber.domain.Customer; @Remote public interface TravelAgentRemote { public Customer findOrCreateCustomer(String first, String last); public void updateAddress(Address addr); public void setFlightID(int flight); public void setSeatID(int seat); public TicketDO bookFlight(CreditCardDO card, double price) throws IncompleteConversationalState; }
  • Slide 35
  • Stateful Session Bean Example Application Exception: IncompleteConversationalState package edu.weber.travelagent; public class IncompleteConversationalState extends java.lang.Exception { public IncompleteConversationalState() { super(); } public IncompleteConversationalState(String msg) {super(msg);} }
  • Slide 36
  • Stateful Session Bean Example Domain Object: TicketDO package edu.weber.travelagent; public class TicketDO implements java.io.Serializable { // Packages Customer, FlightID, SeatID, price, and description // as a POJO }
  • Slide 37
  • Stateful Session Bean Example Ensure Session Bean interface can satisfy a typical client scenario: Look up TravelAgent EJB Locate an existing customer or create a new customer Get address changes or information Gather flight and seat information Collect credit card information Determine price Complete reservation by Booking the Flight
  • Slide 38
  • Stateful Session Bean Example TravelAgentBean package edu.weber.travelagent; import edu.weber.processpayment.*; import edu.weber.domain.*; import javax.ejb.*; import javax.persistence.*; import javax.annotation.EJB; import java.util.Date; @Stateful public class TravelAgentBean implements TravelAgentRemote { @PersistenceContext(unitName=titan) private EntityManager entityManager; @EJB private ProcessPaymentLocal processPayment;
  • Slide 39
  • Stateful Session Bean Example TravelAgentBean private Customer customer; private Flight flight; private Seat seat; public Customer findOrCreateCustomer(String first, String last) { try { Query q = entityManager.createQuery(select c + from Customer c + where c.firstName = :first and c.lastName = :last); q.setParameter(first, first); q.setParameter(last, last); this.customer = (Customer)q.getSingleResult(); } catch (NoResultException notFound) { this.customer = new Customer(); this.customer.setFirstName(first); this.customer.setLastName(last); entityManager.persist(this.customer); } return this.customer; }
  • Slide 40
  • Stateful Session Bean Example TravelAgentBean public void updateAddress(Address addr) { this.customer.setAddress(addr); this.customer = entityManager.merge(customer); }
  • Slide 41
  • Stateful Session Bean Example TravelAgentBean public void setSeatID (int seatID) { this.seat = entityManager.find(Seat.class, seatID); if(seat == null) throw new NoResultException(Seat not found); } public void setFlightID (int flightID) { this.flight = entityManager.find(Flight.class, flightID); if(flight == null) throw new NoResultException(Flight not found); }
  • Slide 42
  • Stateful Session Bean Example TravelAgentBean @Remove public TicketDO bookFlight (CreditCardDO card, double price) throws IncompleteConversationalState { if(customer == null || flight == null || seat == null) throw new IncompleteConversationalState(); try { Reservation reservation = new Reservation( customer, flight, seat, price, new Date()); entityManager.persist(reservation); process.byCredit(customer,card,price); TicketDO ticket = new TicketDO(customer, flight, seat, price); return ticket; } catch(Exception e) { throw new EJBException(e); }
  • Slide 43
  • Stateful Session Bean Lifecycle Does Not Exist Method-ReadyPassive
  • Slide 44
  • Stateful Session Bean Lifecycle Does Not Exist Method-Ready Class.newInstance() injections @PostConstruct
  • Slide 45
  • Stateful Session Bean Lifecycle Does Not Exist Method-Ready @PreDestroy
  • Slide 46
  • Stateful Session Bean Lifecycle Method-Ready Passive @PrePassivate
  • Slide 47
  • Stateful Session Bean Lifecycle Method-Ready Passive @PostActivate
  • Slide 48
  • Stateful Session Bean Lifecycle Method-Ready Business Methods
  • Slide 49
  • Stateful Session Bean Lifecycle Does Not Exist Method-ReadyPassive Timeout!
  • Slide 50
  • Stateful Session Bean Lifecycle Does Not Exist Method-Ready instance throws system exception! Business Methods
  • Slide 51
  • Stateful Session Beans and Extended Persistence Contexts Previous example used transaction-scoped Persistence Context Objects become detached at end of every method Extended Persistence Context Loaded entities remain managed across method calls Automatically registered with a transaction Only Stateful session beans can inject an EXTENDED persistence context Context is created and attached before @PostConstruct Context cleaned up when bean instance is removed
  • Slide 52
  • Stateful Session Beans and Extended Persistence Contexts import static javax.persistence.PersistentContextType.EXTENDED; @Stateful public class TravelAgentBean implements TravelAgentRemote { @PersistenceContext(unitName=titan, type=EXTENDED) private EntityManager entityManager; public void updateAddress(Address addr) { customer.setAddress(addr); } }
  • Slide 53
  • Session Beans Deployment Descriptor Structure
  • Slide 54
  • The Deployment Descriptor TravelAgentEJB com.relaxalot.TravelAgentHomeRemote com.relaxalot.TravelAgentRemote com.relaxalot.TravelAgentBean Stateless
  • Slide 55
  • The Document Header
  • Slide 56
  • The Descriptors Body Provide information about deployment descriptor (optional) Visual label used by deployment tools (optional) and 16x16 or 32x32 icons used by deployment tools (optional) Describes one or more enterprise beans (one required) Path of the client JAR (optional) Defines how the enterprise beans are used in an actual application (optional)
  • Slide 57
  • Enterprise Beans... Describe any number of session beans... Describe any number of entity beans...
  • Slide 58
  • Session Beans Name of component (one required) Fully qualified class name of remote home interface (one required) Fully qualified class name of remote interface (one required) Fully qualifed class name of bean class (one required) Declares a session bean to be stateful or stateless (one required) Declares Bean or Container managed transactions (one required) Declares security roles used by the EJB (zero or more) Resource references (zero or more)
  • Slide 59
  • Entity Beans Name of component (one required) Fully qualified class name of remote home interface (one required) Fully qualified class name of remote interface (one required) Fully qualifed class name of bean class (one required) Primary key field (optional) Primary key class (one required) Container or Bean (one required) Bean allows loopbacks: True or False (one required) Container managed persistence field (zero or more) Declares security roles used by the EJB (zero or more) Resource references (zero or more)
  • Slide 60
  • Environment Entries Declaring minCheckNumber java.lang.Integer 2000 Accessing InitialContext jndiContext = new InitialContext(); Integer minimumValue = (Integer) jndiContext.lookup(java:comp/env/minCheckNumber);
  • Slide 61
  • References to Other Beans Declaring ejb/RoomHomeRemote Entity com.relaxalot.RoomHomeRemote com.relaxalot.RoomRemote Accessing InitialContext jndiContext = new InitialContext(); Object ref = jndiContext.lookup(java:comp/env/ejb/RoomHomeRemote);
  • Slide 62
  • References to External Resources Declaring DataSource for RelaxInc database jdbc/RelaxInc javax.sql.DataSource Container Accessing InitialContext jndiContext = new InitialContext(); DataSource source = (DataSource) jndiContext.lookup(java:comp/env/jdbc/RelaxInc);
  • Slide 63
  • Describing Bean Assembly Declares transaction attributes per each method (zero or more) Declares security roles used when accessing a bean (zero or more) Declares which security roles are allowed to call one or more of the beans methods (zero or more)
  • Slide 64
  • Session Beans Topics to be Covered: Purpose and Types of Session Beans Stateless Session Beans Stateful Session Beans Session Bean Design Deployment Descriptor Structure
Popular Tags:
of 64/64
Module 5 Session Beans
Embed Size (px)
Recommended