module 5 session beans. topics to be covered: purpose and types of session beans stateless session...
Post on 21-Dec-2015
220 views
TRANSCRIPT
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
StatelessSession 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;
@Remotepublic interface ProcessPaymentRemote extends ProcessPayment {}
• Local Interface
package edu.weber.processpayment;import javax.ejb.Local;
@Localpublic 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;
@Statelesspublic 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
• ProcessPaymentBeanpublic 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
@Statelesspublic class A_Bean implements A_BeanRemote {
@Resource private SessionContext context;
public void someMethod() {
B_BeanRemote b = …// Get a remote reference to B_BeanA_BeanRemote mySelf =
context.getBusinessObject(A_BeanRemote.class);
b.aMethod( mySelf );…
}}
Stateless Session Bean Lifecycle
Does Not Exist
Method-ReadyPool
Stateless Session Bean Lifecycle
Does Not Exist
Method-ReadyPool
Class.newInstance()injections
@PostConstruct
Stateless Session Bean Lifecycle
Does Not Exist
Method-ReadyPool
@PreDestroy
Stateless Session Bean Lifecycle
Method-ReadyPool
BusinessMethods
Session Beans
StatefulSession Bean
A Loyal Bean
• Dedicated to one client• Not swapped or pooled
StatefulSessionBean
remoteinterface
EJB objectremoteinterface
EJB objectstub
Client Container
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;
@Remotepublic 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;
@Statefulpublic 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
@Removepublic 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
Method-Ready
Class.newInstance()injections
@PostConstruct
Stateful Session Bean Lifecycle
Does Not Exist
Method-Ready
@PreDestroy
Stateful Session Bean Lifecycle
Method-Ready Passive
@PrePassivate
Stateful Session Bean Lifecycle
Method-Ready Passive
@PostActivate
Stateful Session Bean Lifecycle
Method-Ready BusinessMethods
Stateful Session Bean Lifecycle
Does Not Exist
Method-Ready Passive
Timeout!
Stateful Session Bean Lifecycle
Does Not Exist
Method-Ready
instance throwssystem exception!
BusinessMethods
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
Stateful Session Beans and Extended Persistence Contexts
import static javax.persistence.PersistentContextType.EXTENDED;
@Statefulpublic class TravelAgentBean implements TravelAgentRemote {
@PersistenceContext(unitName=“titan”, type=EXTENDED)private EntityManager entityManager;…public void updateAddress(Address addr) {
customer.setAddress(addr);}…
}
Session Beans
Deployment DescriptorStructure
The Deployment Descriptor
<?xml version="1.0"?><!DOCTYPE ejb-jar PUBLIC “-//Sun Microsystems,
Inc.//DTD EnterpriseJavaBeans 1.1//EN” “http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd”>
<ejb-jar> <enterprise-beans>
<session> <ejb-name>TravelAgentEJB</ejb-name> <home>com.relaxalot.TravelAgentHomeRemote</home> <remote>com.relaxalot.TravelAgentRemote</remote> <ejb-class>com.relaxalot.TravelAgentBean</ejb-class>
<session-type>Stateless</session-type></session>
</enterprise-beans></ejb-jar>
The Document Header
<?xml version="1.0” encoding=“UTF-8”?><!DOCTYPE ejb-jar PUBLIC “-//Sun Microsystems,
Inc.//DTD EnterpriseJavaBeans 1.1//EN” “http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd”>
The Descriptor’s Body
<ejb-jar><description>
Provide information about deployment descriptor (optional)
<display-name>Visual label used by deployment tools (optional)
<small-icon> and <large-icon>16x16 or 32x32 icons used by deployment tools
(optional)<enterprise-beans>
Describes one or more enterprise beans (one required)<ejb-client-jar>
Path of the client JAR (optional)
<assembly-descriptor>Defines how the enterprise beans are used in an
actual application (optional)</ejb-jar>
Enterprise Beans
<enterprise-beans><session> ...</session> Describe any number of session beans
<session> ...</session>
<entity></entity> Describe any number of entity beans
<entity> ...</entity>
</enterprise-beans>
Session Beans
<session><ejb-name> Name of component (one required) <home> Fully qualified class name of remote home interface (one required)
<remote> Fully qualified class name of remote interface (one required)
<ejb-class> Fully qualifed class name of bean class (one required)<session-type> Declares a session bean to be stateful or stateless (one required)
<transaction-type> Declares Bean or Container managed transactions (one required)
<security-role-ref> Declares security roles used by the EJB (zero or more)
<env-entry> Resource references (zero or more)
<ejb-ref> <resource-ref> </session>
Entity Beans<entity>
<ejb-name> Name of component (one required) <home> Fully qualified class name of remote home interface (one required)
<remote> Fully qualified class name of remote interface (one required)
<ejb-class> Fully qualifed class name of bean class (one required)<primkey-field> Primary key field (optional)
<prim-key-class> Primary key class (one required)
<persistence-type> Container or Bean (one required)<reentrant> Bean allows loopbacks: True or False (one required)
<cmp-field> Container managed persistence field (zero or more)<security-role-ref> Declares security roles used by the EJB (zero or more)
<env-entry> Resource references (zero or more)
<ejb-ref> <resource-ref> </entity>
Environment Entries
• Declaring<env-entry>
<env-entry-name>minCheckNumber</env-entry-name> <env-entry-type>java.lang.Integer</env-entry-type>
<env-entry-value>2000</env-entry-value></env-entry>
• Accessing InitialContext jndiContext = new InitialContext(); Integer minimumValue = (Integer)
jndiContext.lookup(“java:comp/env/minCheckNumber”);
References to Other Beans
• Declaring<ejb-ref>
<ejb-ref-name>ejb/RoomHomeRemote</ejb-ref-name> <ejb-ref-type>Entity</ejb-ref-type>
<home>com.relaxalot.RoomHomeRemote</home> <remote>com.relaxalot.RoomRemote</remote></ejb-ref>
• Accessing InitialContext jndiContext = new InitialContext(); Object ref =jndiContext.lookup(“java:comp/env/ejb/RoomHomeRemote”);
References to External Resources
• Declaring<resource-ref> <description>DataSource for RelaxInc
database</description><res-ref-name>jdbc/RelaxInc</res-ref-name> <res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth></resource-ref>
• Accessing InitialContext jndiContext = new InitialContext(); DataSource source = (DataSource)jndiContext.lookup(“java:comp/env/jdbc/RelaxInc”);
Describing Bean Assembly
<assembly-descriptor> <container-transaction>
Declares transaction attributes per each method (zero or more)<security-role>
Declares security roles used when accessing a bean (zero or more)<method-permission>
Declares which security roles are allowed to call one or more of the bean’s methods (zero or more)
</assembly-descriptor>
Session Beans
Topics to be Covered:• Purpose and Types of Session Beans• Stateless Session Beans• Stateful Session Beans• Session Bean Design• Deployment Descriptor Structure