Download
module 5 n.
Skip this Video
Loading SlideShow in 5 Seconds..
Module 5 PowerPoint Presentation

Module 5

251 Views Download Presentation
Download Presentation

Module 5

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Module 5 Session Beans

  2. Session Beans Topics to be Covered: • Purpose and Types of Session Beans • Stateless Session Beans • Stateful Session Beans • Session Bean Design • Deployment Descriptor Structure

  3. Session Beans Purpose and Types of Session Beans

  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

  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

  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

  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

  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

  9. Session Beans Stateless Session Bean

  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

  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

  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

  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; }

  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 { }

  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; } }

  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; } }

  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

  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

  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”;

  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); } }

  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())); } }

  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; }

  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

  24. Stateless Session Bean Example • Injection – Accessing Environment Properties <ejb-jar xmlns=http://java.sun.com/xml/ns/javaee xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance xsi:schemaLocation=“http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd” version=“3.0”> <enterprise-beans> <session> <ejb-name>ProcessPaymentBean</ejb-name> <env-entry> <env-entry-name>min</env-entry-name> <env-entry-type>java.lang.Integer</env-entry-type> <env-entry-value>250</env-entry-value> </env-entry> </session> </enterprise-beans> </ejb-jar>

  25. SessionContext • Provides a view into the EJB container’s 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 ); … } }

  26. Stateless Session Bean Lifecycle Does Not Exist Method-Ready Pool

  27. Stateless Session Bean Lifecycle Does Not Exist Class.newInstance() injections @PostConstruct Method-Ready Pool

  28. Stateless Session Bean Lifecycle Does Not Exist @PreDestroy Method-Ready Pool

  29. Stateless Session Bean Lifecycle Method-Ready Pool Business Methods

  30. Session Beans Stateful Session Bean

  31. A Loyal Bean • Dedicated to one client • Not swapped or pooled remote interface EJB object stub remote interface EJB object Stateful Session Bean Container Client

  32. An Attentive Bean • Maintains conversational state • Methods can be interdependent • State predictable from one call to the next • Not persistent • Not used concurrently

  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

  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; }

  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);} }

  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 }

  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

  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;

  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; }

  40. Stateful Session Bean Example • TravelAgentBean public void updateAddress(Address addr) { this.customer.setAddress(addr); this.customer = entityManager.merge(customer); }

  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”); }

  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); } }

  43. Stateful Session Bean Lifecycle Does Not Exist Method-Ready Passive

  44. Stateful Session Bean Lifecycle Does Not Exist Class.newInstance() injections @PostConstruct Method-Ready

  45. Stateful Session Bean Lifecycle Does Not Exist @PreDestroy Method-Ready

  46. Stateful Session Bean Lifecycle @PrePassivate Method-Ready Passive

  47. Stateful Session Bean Lifecycle @PostActivate Method-Ready Passive

  48. Stateful Session Bean Lifecycle Method-Ready Business Methods

  49. Stateful Session Bean Lifecycle Does Not Exist Timeout! Method-Ready Passive

  50. Stateful Session Bean Lifecycle Does Not Exist instance throws system exception! Method-Ready Business Methods