650 likes | 932 Views
Module 5. Session Beans. Session Beans. Topics to be Covered: Purpose and Types of Session Beans Stateless Session Beans Stateful Session Beans Session Bean Design Deployment Descriptor Structure. Session Beans. Purpose and Types of Session Beans.
E N D
Module 5 Session Beans
Session Beans Topics to be Covered: • Purpose and Types of Session Beans • Stateless Session Beans • Stateful Session Beans • Session Bean Design • Deployment Descriptor Structure
Session Beans Purpose and Types of Session Beans
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
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
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
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
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
Session Beans Stateless Session Bean
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
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
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
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; }
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 { }
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; } }
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; } }
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
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
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”;
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); } }
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())); } }
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; }
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
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>
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 ); … } }
Stateless Session Bean Lifecycle Does Not Exist Method-Ready Pool
Stateless Session Bean Lifecycle Does Not Exist Class.newInstance() injections @PostConstruct Method-Ready Pool
Stateless Session Bean Lifecycle Does Not Exist @PreDestroy Method-Ready Pool
Stateless Session Bean Lifecycle Method-Ready Pool Business Methods
Session Beans Stateful Session Bean
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
An Attentive Bean • Maintains conversational state • Methods can be interdependent • State predictable from one call to the next • Not persistent • Not used concurrently
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
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; }
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);} }
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 }
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
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;
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; }
Stateful Session Bean Example • TravelAgentBean public void updateAddress(Address addr) { this.customer.setAddress(addr); this.customer = entityManager.merge(customer); }
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”); }
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); } }
Stateful Session Bean Lifecycle Does Not Exist Method-Ready Passive
Stateful Session Bean Lifecycle Does Not Exist Class.newInstance() injections @PostConstruct Method-Ready
Stateful Session Bean Lifecycle Does Not Exist @PreDestroy Method-Ready
Stateful Session Bean Lifecycle @PrePassivate Method-Ready Passive
Stateful Session Bean Lifecycle @PostActivate Method-Ready Passive
Stateful Session Bean Lifecycle Method-Ready Business Methods
Stateful Session Bean Lifecycle Does Not Exist Timeout! Method-Ready Passive
Stateful Session Bean Lifecycle Does Not Exist instance throws system exception! Method-Ready Business Methods