The Stateful Session Bean

Each stateful session bean is dedicated to one client for the life of the bean instance; it acts on behalf of that client as its agent. Stateful session beans are not swapped among EJB objects or kept in an instance pool like entity and stateless session bean instances. Once a stateful session bean is instantiated and assigned to an EJB object, it is dedicated to that EJB object for its entire life cycle.[31]

Stateful session beans maintain conversational state, which means that the instance variables of the bean class can maintain data specific to the client between method invocations. This makes it possible for methods to be interdependent, so that changes made to the bean’s state in one method call can affect the results of subsequent method invocations. Therefore, every method call from a client must be serviced by the same instance (at least conceptually), so the bean instance’s state can be predicted from one method invocation to the next. In contrast, stateless session beans don’t maintain client-specific data from one method call to the next, so any instance can be used to service any method call from any client.

Although stateful session beans maintain conversational state, they are not themselves persistent like entity beans. Entity beans represent data in the database; their persistence fields are written directly to the database. Stateful session beans can access the database but do not represent data in the database. In addition, stateful beans are not used concurrently like entity beans. If you have an entity EJB object that wraps an instance of the ship called Paradise, for example, all client requests for that ship will be coordinated through the same EJB object.[32] With stateful session beans, the EJB object is dedicated to one client—stateful session beans are not used concurrently.

Stateful session beans are often considered extensions of the client. This makes sense if you think of a client as being made up of operations and state. Each task may rely on some information gathered or changed by a previous operation. A GUI client is a perfect example: when you fill in the fields on a GUI client you are creating conversational state. Pressing a button executes an operation that might fill in more fields, based on the information you entered previously. The information in the fields is conversational state.

Stateful session beans allow you to encapsulate some of the business logic and conversational state of a client and move it to the server. Moving this logic to the server thins the client application and makes the system as a whole easier to manage. The stateful session bean acts as an agent for the client, managing processes or taskflow to accomplish a set of tasks; it manages the interactions of other beans in addition to direct data access over several operations to accomplish a complex set of tasks. By encapsulating and managing taskflow on behalf of the client, stateful beans present a simplified interface that hides the details of many interdependent operations on the database and other beans from the client.

Getting Set Up for the TravelAgent EJB

The TravelAgent EJB will make use of the Cabin, Cruise, Reservation, and Customer beans developed in Chapter 6 and Chapter 7. It will coordinate the interaction of these entity beans to book a passenger on a cruise. We’ll modify the Reservation EJB that was used in Chapter 7 so that it can be created with all its relationships identified right away. To do so, we overload its ejbCreate( ) method:

public abstract class ReservationBean implements javax.ejb.EntityBean {

    public Integer ejbCreate(CustomerRemote customer, CruiseLocal cruise,
        CabinLocal cabin, double price, Date dateBooked) {

        setAmountPaid(price);
        setDate(dateBooked);
        return null;
    }
    public void ejbPostCreate(CustomerRemote customer, CruiseLocal cruise,
        CabinLocal cabin, double price, Date dateBooked)
        throws javax.ejb.CreateException {

        setCruise(cruise);

        // add Cabin to collection-based CMR field
        Set cabins = new HashSet( );
        cabins.add(cabin);
        this.setCabins(cabins);

        try {
            Integer primKey = (Integer)customer.getPrimaryKey( );
            javax.naming.Context jndiContext = new InitialContext( );
            CustomerHomeLocal home = (CustomerHomeLocal)
                jndiContext.lookup("java:comp/env/ejb/CustomerHomeLocal");
            CustomerLocal custL = home.findByPrimaryKey(primKey);

            // add Customer to collection-based CMR field
            Set customers = new HashSet( );
            customers.add(custL);
            this.setCustomers(customers);

        } catch (RemoteException re) {
            throw new CreateException("Invalid Customer");
        } catch (FinderException fe) {
            throw new CreateException("Invalid Customer");
        } catch (NamingException ne) {
            throw new CreateException("Invalid Customer");
        }
    }

Relationship fields use local EJB object references, so we must convert the CustomerRemote reference to a CustomerLocal reference in order to set the Reservation EJB’s customer relationship field. To do this, you can either use the JNDI ENC to locate the local home interface and then execute the findByPrimaryKey( ) method, or implement an ejbSelect( ) method in the Reservation EJB to locate the CustomerLocal reference.

The TravelAgent EJB

The TravelAgent EJB, which we have already seen, is a stateful session bean that encapsulates the process of making a reservation on a cruise. We will develop this bean further to demonstrate how stateful session beans can be used as taskflow objects. We won’t develop a local interface for the TravelAgent EJB, partly because it is designed to be used by remote clients (and therefore doesn’t require local component interfaces), and partly because the rules for developing local interfaces for stateful session beans are the same as those for stateless session and entity beans.

The remote interface (TravelAgent)

In Chapter 4, we developed an early version of the TravelAgentRemote interface that contained a single business method, listCabins( ). We are now going to remove the listCabins( ) method and redefine the TravelAgent EJB so that it behaves like a taskflow object. Later in this chapter, we will add a modified listing method for obtaining a more specific list of cabins for the user.

As a stateful session bean that models taskflow, the TravelAgent EJB manages the interactions between several other beans while maintaining conversational state. Here’s the modified TravelAgentRemote interface:

package com.titan.travelagent;

import java.rmi.RemoteException;
import javax.ejb.FinderException;
import com.titan.processpayment.CreditCardDO;

public interface TravelAgentRemote extends javax.ejb.EJBObject {

    public void setCruiseID(Integer cruise) 
        throws RemoteException, FinderException;

    public void setCabinID(Integer cabin) 
        throws RemoteException, FinderException;

    public TicketDO bookPassage(CreditCardDO card, double price)
        throws RemoteException,IncompleteConversationalState;   
}

The purpose of the TravelAgent EJB is to make cruise reservations. To accomplish this task, the bean needs to know which cruise, cabin, and customer make up the reservation. Therefore, the client using the TravelAgent EJB needs to gather this kind of information before making the booking. The TravelAgentRemote interface provides methods for setting the IDs of the cruise and cabin that the customer wants to book. We can assume that the cabin ID comes from a list and that the cruise ID comes from some other source. The customer is set in the create( ) method of the home interface—more about this later.

Once the customer, cruise, and cabin are chosen, the TravelAgent EJB is ready to process the reservation. This operation is performed by the bookPassage( ) method, which needs the customer’s credit card information and the price of the cruise. bookPassage( ) is responsible for charging the customer’s account, reserving the chosen cabin in the right ship on the right cruise, and generating a ticket for the customer. How this is accomplished is not important to us at this point; when we are developing the remote interface, we are concerned only with the business definition of the bean. We will discuss the implementation when we talk about the bean class.

Note that the bookPassage( ) method throws an application-specific exception, IncompleteConversationalState. This exception is used to communicate business problems encountered while booking a customer on a cruise. The IncompleteConversationalState exception indicates that the TravelAgent EJB did not have enough information to process the booking. Here’s the IncompleteConversationalState class:

package com.titan.travelagent;

public class IncompleteConversationalState extends java.lang.Exception {
    public IncompleteConversationalState( ){super( );}
    public IncompleteConversationalState(String msg){super(msg);}
}

Dependent object (TicketDO)

Like the CreditCardDO and CheckDO classes used in the ProcessPayment EJB, the TicketDO class is defined as a pass-by-value object. One could argue that a ticket should be an entity bean since it is not dependent and may be accessed outside the context of the TravelAgent EJB. However, determining how a business object is used can also dictate whether it should be a bean or simply a class. The TicketDO object, for example, could be digitally signed and emailed to the client as proof of purchase. This would not be feasible if the TicketDO object were an entity bean, because enterprise beans are referenced only through their component interfaces and are never passed by value.

The constructor for TicketDO uses the local interfaces of creating a new TicketDO object:

package com.titan.travelagent;

import com.titan.cruise.CruiseLocal;
import com.titan.cabin.CabinLocal;
import com.titan.customer.CustomerRemote;

public class TicketDO implements java.io.Serializable {
    public Integer customerID;
    public Integer cruiseID;
    public Integer cabinID;
    public double price;
    public String description;
    
    public TicketDO(CustomerRemote customer, CruiseLocal cruise, 
        CabinLocal cabin, double price) throws javax.ejb.FinderException, 
        RemoteException, javax.naming.NamingException {
        
            description = customer.getFirstName( )+
                " " + customer.getLastName( ) + 
                " has been booked for the "
                + cruise.getName( ) + 
                " cruise on ship " + 
                  cruise.getShip( ).getName( ) + ".
" +  
                " Your accommodations include " + 
                  cabin.getName( ) + 
                " a " + cabin.getBedCount( ) + 
                " bed cabin on deck level " + cabin.getDeckLevel( ) + 
                ".
 Total charge = " + price;
            customerID = (Integer)customer.getPrimaryKey( );
            cruiseID = (Integer)cruise.getPrimaryKey( );
            cabinID = (Integer)cabin.getPrimaryKey( );
            this.price = price;
        }
        
    public String toString( ) {
        return description;
    }
}

The home interface (TravelAgentHomeRemote)

Starting with the TravelAgentHomeRemote interface we developed in Chapter 4, we can modify the create( ) method to take a remote reference to the customer who is making the reservation:

package com.titan.travelagent;

import java.rmi.RemoteException;
import javax.ejb.CreateException;
import com.titan.customer.CustomerRemote;

public interface TravelAgentHomeRemote extends javax.ejb.EJBHome {
    public TravelAgentRemote create(CustomerRemote cust)
        throws RemoteException, CreateException;
}

The create( ) method in this home interface requires that a remote reference to a Customer EJB be used to create the TravelAgent EJB. Because there are no other create( ) methods, you cannot create a TravelAgent EJB if you do not know who the customer is. The Customer EJB reference provides the TravelAgent EJB with some of the conversational state it will need to process the bookPassage( ) method.

Taking a peek at the client view

Before settling on definitions for your component interfaces, it is a good idea to figure out how clients will use the bean. Imagine that the TravelAgent EJB is used by a Java application with GUI fields. These fields capture the customer’s preference for the type of cruise and cabin. We start by examining the code used at the beginning of the reservation process:

Context jndiContext = getInitialContext( );
Object ref = jndiContext.lookup("CustomerHomeRemote");
CustomerHomeRemote customerHome =(CustomerHomeRemote)
    PortableRemoteObject.narrow(ref, CustomerHomeRemote.class);

String ln = tfLastName.getText( );
String fn = tfFirstName.getText( );
String mn = tfMiddleName.getText( );
CustomerRemote customer = customerHome.create(nextID, ln, fn, mn); 

ref = jndiContext.lookup("TravelAgentHomeRemote");
TravelAgentHomeRemote home = (TravelAgentHomeRemote)
    PortableRemoteObject.narrow(ref, TravelAgentHomeRemote.class);
        
TravelAgentRemote agent = home.create(customer);

This code creates a new Customer EJB based on information the travel agent gathered over the phone. The CustomerRemote reference is then used to create a TravelAgent EJB. Next, we gather the cruise and cabin choices from another part of the applet:

Integer cruise_id = new Integer(textField_cruiseNumber.getText( ));

Integer cabin_id = new Integer( textField_cabinNumber.getText( ));

agent.setCruiseID(cruise_id);
                     agent.setCabinID(cabin_id);

The travel agent chooses the cruise and cabin the customer wishes to reserve. These IDs are set in the TravelAgent EJB, which maintains the conversational state for the whole process.

At the end of the process, the travel agent completes the reservation by processing the booking and generating a ticket. Because the TravelAgent EJB has maintained the conversational state, caching the customer, cabin, and cruise information, only the credit card and price are needed to complete the transaction:

String cardNumber = textField_cardNumber.getText( );
Date date = dateFormatter.parse(textField_cardExpiration.getText( ));
String cardBrand = textField_cardBrand.getText( );
CreditCardDO card = new CreditCardDO(cardNumber,date,cardBrand);
double price = double.valueOf(textField_cruisePrice.getText( )).doubleValue( );
TicketDO ticket = agent.bookPassage(card,price);
PrintingService.print(ticket);

This summary of how the client will use the TravelAgent EJB confirms that our remote interface and home interface definitions are workable. We can now move ahead with development.

TravelAgentBean: The bean class

We can now implement all of the behavior expressed in the new remote interface and home interface for the TravelAgent EJB.[33] Here is a partial definition of the new TravelAgentBean class:

import com.titan.reservation.*;

import java.sql.*;
import javax.sql.DataSource;
import java.util.Vector;
import java.rmi.RemoteException;
import javax.naming.NamingException;
import javax.ejb.EJBException;
import com.titan.processpayment.*;
import com.titan.cruise.*;
import com.titan.customer.*;
import com.titan.cabin.*;

public class TravelAgentBean implements javax.ejb.SessionBean {

    public CustomerRemote customer;
    public CruiseLocal cruise;
    public CabinLocal cabin;

    public javax.ejb.SessionContext ejbContext;

    public javax.naming.Context jndiContext;

    public void ejbCreate(CustomerRemote cust) {
        customer = cust;
    }
    public void setCabinID(Integer cabinID) throws javax.ejb.FinderException { 
        try { 
            CabinHomeLocal home = (CabinHomeLocal)
                jndiContext.lookup("java:comp/env/ejb/CabinHomeLocal");
            
            cabin = home.findByPrimaryKey(cabinID);
        } catch(RemoteException re) {
            throw new EJBException(re);
        }
    }
    public void setCruiseID(Integer cruiseID) throws javax.ejb.FinderException { 
        try { 
           CruiseHomeLocal home = (CruiseHomeLocal)
               jndiContext.lookup("java:comp/env/ejb/CruiseHomeLocal");
           
           cruise = home.findByPrimaryKey(cruiseID);
        } catch(RemoteException re) {
            throw new EJBException(re);
        }
        
    }
    public TicketDO bookPassage(CreditCardDO card, double price)
        throws IncompleteConversationalState {
                   
        if (customer == null || cruise == null || cabin == null) 
        {
            throw new IncompleteConversationalState( );
        }
        try {
            ReservationHomeLocal resHome = (ReservationHomeLocal)            
                jndiContext.lookup("java:comp/env/ejb/ReservationHomeLocal");
             
            ReservationLocal reservation =
                resHome.create(customer, cruise, cabin, price, new Date( ));
                
            Object ref = jndiContext.lookup("java:comp/env/ejb/
                ProcessPaymentHomeRemote");

            ProcessPaymentHomeRemote ppHome = (ProcessPaymentHomeRemote)
                PortableRemoteObject.narrow (ref, ProcessPaymentHomeRemote.class);
            
            ProcessPaymentRemote process = ppHome.create( );
            process.byCredit(customer, card, price);

            TicketDO ticket = new TicketDO(customer, cruise, cabin, price);
            return ticket;
        } catch(Exception e) {
            throw new EJBException(e);
        }
    }
    public void ejbRemove( ) {}
    public void ejbActivate( ) {}
    public void ejbPassivate( ) {}
    
    public void setSessionContext(javax.ejb.SessionContext cntx) 
    {

        ejbContext = cntx;
        try {
            jndiContext = new javax.naming.InitialContext( );
        } catch(NamingException ne) {
            throw new EJBException(ne);
        }
    }
}

This is a lot of code to digest, so we will approach it in small pieces. First, let’s examine the ejbCreate( ) method:

public class TravelAgentBean implements javax.ejb.SessionBean {

    public CustomerRemote customer;
        ...

    public javax.ejb.SessionContext ejbContext;
    public javax.naming.Context jndiContext;

    public void ejbCreate(CustomerRemote cust) {
        customer = cust;
    }

When the bean is created, the remote reference to the Customer EJB is passed to the bean instance and maintained in the customer field. The customer field is part of the bean’s conversational state. We could have obtained the customer’s identity as an integer ID and constructed the remote reference to the Customer EJB in the ejbCreate( ) method. However, we passed the reference directly to demonstrate that remote references to beans can be passed from a client application to a bean. They can also be returned from the bean to the client and passed between beans on the same EJB server or between EJB servers.

References to the SessionContext and JNDI context are held in fields called ejbContext and jndiContext. The “ejb” and “jndi” prefixes help to avoid confusion between the different content types.

When a bean is passivated, the JNDI ENC must be maintained as part of the bean’s conversational state. This means that the JNDI context should not be transient. Once a field is set to reference the JNDI ENC, the reference remains valid for the life of the bean. In the TravelAgentBean, we set the jndiContext field when the SessionContext is set, at the beginning of the bean’s life cycle:

public void setSessionContext(javax.ejb.SessionContext cntx) {
    ejbContext = cntx;
    try {
        jndiContext = new InitialContext( );
    } catch(NamingException ne) {
        throw new EJBException(ne);
    }
}

The EJB container makes special accommodations for references to the SessionContext, the JNDI ENC, references to other beans (remote and home interface types), and the JTA UserTransaction type (discussed in Chapter 15). The container must maintain any instance fields that reference objects of these types as part of the conversational state, even if they are not serializable. All other fields must be serializable or null when the bean is passivated.

The TravelAgent EJB has methods for setting the desired cruise and cabin. These methods take Integer IDs as arguments and retrieve references to the appropriate Cruise or Cabin EJB from the appropriate home interface. These references are also part of the TravelAgent EJB’s conversational state. Here’s how setCabinID( ) and getCabinID( ) are defined:

public void setCabinID(Integer cabinID) 
    throws javax.ejb.FinderException { 
    try { 
        CabinHomeLocal home = (CabinHomeLocal)
            jndiContext.lookup("java:comp/env/ejb/CabinHomeLocal");
            
        cabin = home.findByPrimaryKey(cabinID);
    } catch(RemoteException re) {
        throw new EJBException(re);
    }
}
public void setCruiseID(Integer cruiseID) 
    throws javax.ejb.FinderException { 
    try { 
        CruiseHomeLocal home = (CruiseHomeLocal)
            jndiContext.lookup("java:comp/env/ejb/CruiseHomeLocal");
           
        cruise = home.findByPrimaryKey(cruiseID);
    } catch(RemoteException re) {
        throw new EJBException(re);
    }     
}

It may seem strange that we set these values using Integer IDs, but we keep them in the conversational state as entity bean references. Using Integer IDs is simpler for the client, which does not work with their entity bean references. In the client code, we get the cabin and cruise IDs from text fields. Why make the client obtain a bean reference to the Cruise and Cabin EJBs when an ID is simpler? In addition, using the IDs is cheaper (i.e., requires less network traffic) than passing a remote reference. We need the EJB object references to these bean types in the bookPassage( ) method, so we use their IDs to obtain actual entity bean references. We could have waited until the bookPassage( ) method was invoked before reconstructing the remote references, but this strategy keeps the bookPassage( ) method simple.

JNDI ENC and EJB references

You can use the JNDI ENC to obtain a reference to the home interfaces of other beans. Using the ENC lets you avoid hardcoding vendor-specific JNDI properties into the bean. In other words, the JNDI ENC allows EJB references to be network and vendor independent.

In the TravelAgentBean, we used the JNDI ENC to acquire both the remote home interface of the ProcessPayment EJB and the local home interfaces of the Cruise and Cabin EJBs. The EJB specification recommends that all EJB references be bound to the "java:comp/env/ejb" context, which is the convention followed here. In the TravelAgent EJB, we append the name of the home object to "java:comp/env/ejb“, giving a result like "java:comp/env/ejb/CruiseHomeLocal“.

Remote EJB references in the JNDI ENC

The deployment descriptor provides a special set of tags for declaring remote EJB references. Here’s how the <ejb-ref> tag and its subelements are used:

<ejb-ref>
    <ejb-ref-name>ejb/ProcessPaymentHomeRemote</ejb-ref-name>
    <ejb-ref-type>Session</ejb-ref-type>
    <home>
        com.titan.processpayment.ProcessPaymentHomeRemote
    </home>
    <remote>
       com.titan.processpayment.ProcessPaymentRemote
    </remote>
</ejb-ref>

These elements define a name for the bean within the ENC, declare the bean’s type, and give the names of its remote and home interfaces. When a bean is deployed, the deployer maps the <ejb-ref> elements to actual beans in a way specific to the vendor. The <ejb-ref> elements can also be linked by the application assembler to beans in the same deployment (a subject covered in detail in Chapter 17). However, you should try to use local component interfaces for beans located in the same deployment and container.

Local EJB references in the JNDI ENC

The deployment descriptor also provides a special set of tags, the <ejb-local-ref> elements, to declare local EJB references: enterprise beans that are co-located in the same container and deployed in the same EJB JAR file. The <ejb-local-ref> elements are declared immediately after the <ejb-ref> elements:

<ejb-local-ref>
    <ejb-ref-name>ejb/CruiseHomeLocal</ejb-ref-name>
    <ejb-ref-type>Entity</ejb-ref-type>
    <local-home>
        com.titan.cruise.CruiseHomeLocal
    </local-home>
    <local>
        com.titan.cruise.CruiseLocal
    </local>
    <ejb-link>CruiseEJB</ejb-link>
</ejb-local-ref>
<ejb-local-ref>
    <ejb-ref-name>ejb/CabinHomeLocal</ejb-ref-name>
    <ejb-ref-type>Entity</ejb-ref-type>
    <local-home>
        com.titan.cabin.CabinHomeLocal
    </local-home>
    <local>
        com.titan.cabin.CabinLocal
    </local>
    <ejb-link>CabinEJB</ejb-link>
</ejb-local-ref>

The <ejb-local-ref> element defines a name for the bean within the ENC, declares the bean’s type, and gives the names of its local component interfaces. These elements should be linked explicitly to other co-located beans using the <ejb-link> element, although linking them is not strictly required at this stage—the application assembler or deployer can do it later. The value of the <ejb-link> element within the <ejb-local-ref> must be the same as the <ejb-name> of the appropriate bean in the same JAR file.

At deployment time the EJB container’s tools map the local references declared in the <ejb-local-ref> elements to entity beans that are co-located in the same container system.

The bookPassage( ) method

The last point of interest in our bean definition is the bookPassage( ) method. This method makes use of the conversational state accumulated by the ejbCreate( ), setCabinID( ), and setCruiseID( ) methods to process a reservation for a customer. Here’s how the bookPassage( ) method is defined:

public TicketDO bookPassage(CreditCardDO card, double price)
    throws IncompleteConversationalState {
                   
    if (customer == null || cruise == null || cabin == null) {
        throw new IncompleteConversationalState( );
    }
    try {
        ReservationHomeLocal resHome = (ReservationHomeLocal)
            jndiContext.lookup("java:comp/env/ejb/ReservationHomeLocal");
            
        ReservationLocal reservation =
            resHome.create(customer, cruise, cabin, price, new Date( ));
                
        Object ref = jndiContext.lookup("java:comp/env/ejb/
            ProcessPaymentHomeRemote");

        ProcessPaymentHomeRemote ppHome = (ProcessPaymentHomeRemote)
            PortableRemoteObject.narrow(ref, ProcessPaymentHomeRemote.class);
            
        ProcessPaymentRemote process = ppHome.create( );
        process.byCredit(customer, card, price);

        TicketDO ticket = new TicketDO(customer,cruise,cabin,price);
        return ticket;
    } catch(Exception e) {
        throw new EJBException(e);
    }
}

This method deomonstrates the concept of taskflow. It uses several beans, including the Reservation, ProcessPayment, Customer, Cabin, and Cruise EJBs, to accomplish one task: booking a customer on a cruise. Deceptively simple, this method encapsulates several interactions that ordinarily might have been performed on the client. For the price of one bookPassage( ) call from the client, the TravelAgent EJB performs many operations:

  1. Looks up and obtains a reference to the Reservation EJB’s home.

  2. Creates a new Reservation EJB.

  3. Looks up and obtains a remote reference to the ProcessPayment EJB’s home.

  4. Creates a new ProcessPayment EJB.

  5. Charges the customer’s credit card using the ProcessPayment EJB.

  6. Generates a new TicketDO with all the pertinent information describing the customer’s purchase.

From a design standpoint, encapsulating the taskflow in a stateful session bean means a less complex interface for the client and more flexibility for implementing changes. We could easily change bookPassage( ) to check for overlapped booking (when a customer books passage on two cruises with overlapping dates). This type of enhancement does not change the remote interface, so the client application does not need modification. Encapsulating taskflow in stateful session beans allows the system to evolve without impacting clients.

In addition, the type of clients used can change. One of the biggest problems with two-tier architectures—besides scalability and transactional control—is that the business logic is intertwined with the client logic. As a result, it is difficult to reuse the business logic in a different kind of client. With stateful session beans this is not a problem, because stateful session beans are an extension of the client but are not bound to the client’s presentation. Let’s say that our first implementation of the reservation system used a Java applet with GUI widgets. The TravelAgent EJB would manage conversational state and perform all the business logic while the applet focused on the GUI presentation. If, at a later date, we decide to go to a thin client (HTML generated by a Java servlet, for example), we would simply reuse the TravelAgent EJB in the servlet. Because all the business logic is in the stateful session bean, the presentation (Java applet or servlet or something else) can change easily.

The TravelAgent EJB also provides transactional integrity for processing the customer’s reservation. If any of the operations within the body of the bookPassage( ) method fails, all the operations are rolled back so that none of the changes are accepted. If the credit card cannot be charged by the ProcessPayment EJB, the newly created Reservation EJB and its associated record are not created. The transactional aspects of the TravelAgent EJB are explained in detail in Chapter 15.

The remote and local EJB references can be used within the same taskflow. For example, the bookPassage( ) method uses local references when accessing the Cruise and Cabin beans, but remote references when accessing the ProcessPayment and Customer EJBs. This usage is totally appropriate. The EJB container ensures that the transaction is atomic, i.e., that failures in either the remote or local EJB reference will affect the entire transaction.

Why use a Reservation entity bean?

If we have a Reservation EJB, why do we need a TravelAgent EJB? The TravelAgent EJB uses the Reservation EJB to create a reservation, but it also has to charge the customer and generate a ticket. These activities are not specific to the Reservation EJB, so they need to be captured in a stateful session bean that can manage taskflow and transactional scope. In addition, the TravelAgent EJB provides listing behavior, which spans concepts in Titan’s system. It would have been inappropriate to include any of these other behaviors in the Reservation entity bean.

Listing behavior (listAvailableCabins( ))

As promised, we are going to bring back the cabin-listing behavior we played around with in Chapter 4. This time we are not going to use the Cabin EJB to get the list; instead, we will access the database directly. Accessing the database directly is a double-edged sword. On one hand, we don’t want to access the database directly if entity beans exist that can access the same information. Entity beans provide a safe and consistent interface for a particular set of data. Once an entity bean has been tested and proven, it can be reused throughout the system, substantially reducing data-integrity problems. The Reservation EJB is an example of that kind of usage. Entity beans can also pull together disjointed data and apply additional business logic such as validation, limits, and security to ensure that data access follows the business rules.

But entity beans cannot define every possible data access needed, and they shouldn’t. One of the biggest problems with entity beans is that they tend to become bloated over time. Huge entity beans containing dozens of methods are a sure sign of poor design. Entity beans should be focused on providing data access to a very limited, but conceptually bound, set of data. You should be able to update, read, and insert records or data. Data access that spans concepts, like listing behavior, should not be encapsulated in an entity bean.

Systems always need listing behavior to present clients with choices. In the reservation system, for example, customers need to choose a cabin from a list of available cabins. The word available is key to the definition of this behavior. The Cabin EJB can provide us with a list of cabins, but it does not know whether any given cabin is available. As you may recall, the Cabin-Reservation relationship we defined in Chapter 7 was unidirectional: the Reservation was aware of its Cabin relationships, but the reverse was not true. The question of whether a cabin is available is relevant to the process using it—in this case, the TravelAgent EJB—but may not be relevant to the cabin itself. As an analogy, an automobile entity would not care what road it is on; it is concerned only with characteristics that describe its state and behavior. An automobile-tracking system, on the other hand, would be concerned with the locations of individual automobiles.

To get availability information, we need to compare the list of cabins on our ship to the list of cabins that have already been reserved. The listAvailableCabins( ) method does exactly that. It uses an SQL query to produce a list of cabins that have not yet been reserved for the cruise chosen by the client:

public String [] listAvailableCabins(int bedCount)
    throws IncompleteConversationalState { 
    if (cruise == null) 
        throw new IncompleteConversationalState( );

    Connection con = null;
    PreparedStatement ps = null;;
    ResultSet result = null;
    try {
        Integer cruiseID = (Integer)cruise.getPrimaryKey( );
        Integer shipID = (Integer)cruise.getShip( ).getPrimaryKey( );
        con = getConnection( );
        ps = con.prepareStatement(
            "select ID, NAME, DECK_LEVEL  from CABIN "+
            "where SHIP_ID = ? and BED_COUNT = ? and ID NOT IN "+
            "(SELECT CABIN_ID FROM RESERVATION "+" WHERE CRUISE_ID = ?)");

        ps.setInt(1,shipID.intValue( ));
        ps.setInt(2, bedCount);
        ps.setInt(3,cruiseID.intValue( ));
        result = ps.executeQuery( );
        Vector vect = new Vector( );
        while(result.next( )) {
            StringBuffer buf = new StringBuffer( );
            buf.append(result.getString(1));
            buf.append(','),
            buf.append(result.getString(2));
            buf.append(','),
            buf.append(result.getString(3));
            vect.addElement(buf.toString( ));
        }
        String [] returnArray = new String[vect.size( )];
        vect.copyInto(returnArray);
        return returnArray;
    } catch (Exception e) {
        throw new EJBException(e);
    }
    finally {
        try {
            if (result != null) result.close( );
            if (ps != null) ps.close( );
            if (con!= null) con.close( );
        } catch(SQLException se){se.printStackTrace( );}
    }
}

As you can see, the SQL query is complex. It could have been defined using a method like Cabin.findAvailableCabins(Cruise cruise) in the Cabin EJB. However, this method would be difficult to implement because the Cabin EJB would need to access the Reservation EJB’s data. It’s also easy to imagine cluttering an entity bean with lots of fairly specific find methods that are tied to particular situations. Such clutter isn’t necessary or desirable. To avoid adding find methods for every possible query, you can instead use direct database access as shown in the listAvailableCabins( ) method. Direct database access generally has less impact on performance because the container does not have to manifest EJB object references, but it is also less reusable. When you are deciding whether to add a find method to an entity bean or to make a direct query in a session bean, keep in mind the tradeoff between reusability, performance, and clarity.

The listAvailableCabins( ) method returns an array of String objects. We could have opted to return a collection of remote Cabin references, but we didn’t because we want to keep the client application as lightweight as possible. A list of String objects is much more lightweight than a collection of remote references; this way, the client doesn’t have to work with a group of stubs, each with its own connection to EJB objects on the server. By returning a lightweight String array, we reduce the number of stubs on the client, which keeps the client simple and conserves resources on the server.

To make this method work, you need to create a private getConnection( ) method for obtaining a database connection. This method becomes part of the TravelAgentBean:

private Connection getConnection( ) throws SQLException {
    try {
        DataSource ds = (DataSource)jndiContext.lookup(
            "java:comp/env/jdbc/titanDB");
        return ds.getConnection( );
    } catch(NamingException ne) {
        throw new EJBException(ne);
    }
}

Change the remote interface for TravelAgent EJB to include the listAvailableCabins( ) method:

package com.titan.travelagent;

import java.rmi.RemoteException;
import javax.ejb.FinderException;
import com.titan.processpayment.CreditCard;

public interface TravelAgentRemote extends javax.ejb.EJBObject {

    public void setCruiseID(Integer cruise) throws RemoteException, FinderException;

    public void setCabinID(Integer cabin) throws RemoteException, FinderException;

    public TicketDO bookPassage(CreditCardDO card, double price)
        throws RemoteException,IncompleteConversationalState;   
               
    public String [] listAvailableCabins(int bedCount)
                             throws RemoteException, IncompleteConversationalState;
}

The TravelAgent deployment descriptor

Here’s an abbreviated version of the XML deployment descriptor used for the TravelAgent EJB. It defines not only the TravelAgent EJB, but also the Customer, Cruise, Cabin, and Reservation EJBs. The ProcessPayment EJB is not defined in this deployment descriptor because it is assumed to be deployed in a separate JAR file, or possibly even a separate EJB server on a different network node:

<?xml version="1.0" encoding="UTF-8" ?>
<ejb-jar 
     xmlns="http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
                         http://java.sun.com/xml/ns/j2ee/ejb-jar_2_1.xsd"
     version="2.1">
    <enterprise-beans>
        <session>
            <ejb-name>TravelAgentEJB</ejb-name>
            <home>com.titan.travelagent.TravelAgentHomeRemote</home>
            <remote>com.titan.travelagent.TravelAgentRemote</remote>
            <ejb-class>com.titan.travelagent.TravelAgentBean</ejb-class>
            <session-type>Stateful</session-type>
            <transaction-type>Container</transaction-type>

            <ejb-ref>
                <ejb-ref-name>ejb/ProcessPaymentHomeRemote</ejb-ref-name>
                <ejb-ref-type>Session</ejb-ref-type>
                <home>com.titan.processpayment.ProcessPaymentHomeRemote</home>
                <remote>com.titan.processpayment.ProcessPaymentRemote</remote>
            </ejb-ref>
            <ejb-local-ref>
                <ejb-ref-name>ejb/CabinHomeLocal</ejb-ref-name>
                <ejb-ref-type>Entity</ejb-ref-type>
                <local-home>com.titan.cabin.CabinHomeLocal</local-home>
                <local>com.titan.cabin.CabinLocal</local>
            </ejb-local-ref>
            <ejb-local-ref>
                <ejb-ref-name>ejb/CruiseHomeLocal</ejb-ref-name>
                <ejb-ref-type>Entity</ejb-ref-type>
                <local-home>com.titan.cruise.CruiseHomeLocal</local-home>
                <local>com.titan.cruise.CruiseLocal</local>
            </ejb-local-ref>
            <ejb-local-ref>
                <ejb-ref-name>ejb/ReservationHomeLocal</ejb-ref-name>
                <ejb-ref-type>Entity</ejb-ref-type>
                <local-home>com.titan.reservation.ReservationHomeLocal</local-home>
               <local>com.titan.reservation.ReservationLocal</local>
            </ejb-local-ref>

            <resource-ref>
                <description>DataSource for the Titan database</description>
                <res-ref-name>jdbc/titanDB</res-ref-name>
                <res-type>javax.sql.DataSource</res-type>
                <res-auth>Container</res-auth>
           </resource-ref>
        </session>
        <entity>
            <ejb-name>CabinEJB</ejb-name>
            <local-home>com.titan.cabin.CabinHomeLocal</local-home>
            <local>com.titan.cabin.CabinLocal</local>
            ...
        </entity>
        <entity>
            <ejb-name>CruiseEJB</ejb-name>
            <local-home>com.titan.cruise.CruiseHomeLocal</local-home>
            <local>com.titan.cruise.CruiseLocal</local>
            ...
        </entity>
        <entity>
            <ejb-name>ReservationEJB</ejb-name>
            <local-home>com.titan.reservation.ReservationHomeLocal</local-home>
            <local>com.titan.reservation.ReservationLocal</local>
            ... 
        </entity>   
    </enterprise-beans>

    <assembly-descriptor>
        <security-role>
            <description>This role represents everyone</description>
            <role-name>everyone</role-name>
        </security-role>

        <method-permission>
            <role-name>everyone</role-name>
            <method>
                <ejb-name>TravelAgentEJB</ejb-name>
                <method-name>*</method-name>
            </method>
        </method-permission>

        <container-transaction>
            <method>
                <ejb-name>TravelAgentEJB</ejb-name>
                <method-name>*</method-name>
            </method>
            <trans-attribute>Required</trans-attribute>
        </container-transaction>
    </assembly-descriptor>
</ejb-jar>

The deployment descriptor for EJB 2.0 is exactly the same, except it’s based on a DTD instead of an XML Schema, so it uses a document declaration and has a simpler <ejb-jar> element.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise
JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">

<ejb-jar>
     <enterprise-beans>
     ...

Once you have generated the deployment descriptor, jar the TravelAgent EJB and deploy it in your EJB server. You will also need to deploy the Reservation, Cruise, and Customer EJBs you downloaded earlier. Based on the business methods in the remote interface of the TravelAgent EJB and your past experiences with the Cabin, Ship, and ProcessPayment EJBs, you should be able to create your own client application to test this code.

Exercise 11.2 in the Workbook shows how to deploy the examples in this section.



[31] This is a conceptual model. Some EJB containers may actually use instance swapping with stateful session beans but make it appear as if the same instance is servicing all requests. Conceptually, however, the same stateful session bean instance services all requests.

[32] This is also a conceptual model. Some EJB containers may use separate EJB objects for concurrent access to the same entity, relying on the database to control concurrency. Conceptually, however, the end result is the same.

[33] If you are modifying the bean developed in Chapter 4, remember to delete the listCabin( ) method. We will add a new implementation of that method later in this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.76.164