📄 cartbean.java
字号:
package examples;
import java.util.*;
import javax.ejb.*;
import java.rmi.RemoteException;
import javax.rmi.PortableRemoteObject;
import javax.naming.*;
/**
*
* This stateful session bean represents a cart which
* a customer is working on. A cart is a set of
* Books that the customer is interested in, but has
* not committed to buying yet. You can think of this
* bean as a shopping cart - as the customer surfs our
* BookStore's web site, this bean stores all the
* Books and quantities he is interested in.
*
* A cart consists of a series of line-items. Each
* line-item represents one particular Book the
* customer wants, as well as a quantity and discount for that
* Book.
*
* The distinction between a cart and an order is that
* a Cart is only temporary and in-memory (hence a
* stateful session bean), whereas an order is a
* persistent record (hence an entity bean). This
* Cart bean is smart enough to know how to transform
* itself into an order (via the purchase() method).
*
*/
public class CartBean implements javax.ejb.SessionBean {
/*
* The shopping cart owner
*/
private String owner;
/**
* The shopping cart contents - a vector of LineItems
*/
private Vector contents;
/**
* The session context
*/
private SessionContext ctx;
/*
* The subtotal (price before taxes) of the goods
*/
private double subTotal;
/*
* The taxes on the goods
*/
private double taxes;
//
// Business methods
//
/**
* Get method for the shopping cart owner's name
* @return shopping cart owner
*/
public String getOwner() { return owner;}
/**
* Set method for the shopping cart owner's name
*
* @param shopping cart owner
*/
public void setOwner(String owner) { this.owner = owner;}
/**
* Adds an item to the shopping cart
*
* @param shopping cart lineitem
*/
public void add(LineItem lineItem) {
/*
* Search for a lineitem in the cart that match the
* BookID passed in. If found, modify that lineitem.
*/
Iterator i = contents.iterator();
try{
while (i.hasNext()) {
LineItem item = (LineItem) i.next();
BookItem book=item.getBookItem();
if (book!=null && book.getBookID().equals(lineItem.getBookItem().getBookID())) {
item.setQuantity(item.getQuantity() + lineItem.getQuantity());
return;
}
}
/*
* Did not find a match, so add a new lineitem.
*/
contents.add(lineItem);
}catch (Exception e) {
throw new EJBException(e);
}
}
/**
* Changes the quantities of contents in the shopping cart
*
* @param Book Id
* @param number of items.
*/
public void modify(String bookID, int quantity) throws Exception {
System.out.println("CartBean.modify()");
/*
* Search for a lineitem in the cart that match the
* BookID passed in. If found, modify that lineitem.
*/
Iterator i = contents.iterator();
while (i.hasNext()) {
LineItem item = (LineItem) i.next();
BookItem book=item.getBookItem();
if (book!=null && book.getBookID().equals(bookID)) {
item.setQuantity(quantity);
if (quantity == 0) {
i.remove();
}
return;
}
}
throw new Exception("CartBean.modify() error: Could not find Book " + bookID);
}
/**
* Loads the entity bean for the given Book id
*
* @param book Id
* @return book entity bean remote object
*/
private Book getBook(String bookId){
try{
Context ctx = new InitialContext();
BookHome bookHome = (BookHome)
PortableRemoteObject.narrow(
ctx.lookup("BookHome"), BookHome.class);
Book book=bookHome.findByPrimaryKey(bookId);
return book;
}catch (Exception e) {
throw new EJBException(e);
}
}
/**
* Returns all the shopping cart line items
*
* @return A collection of Cart LineItems
*/
public Vector getAll() {
System.out.println("CartBean.getAll()");
return contents;
}
/**
* Returns the subtotal price which has been
* previously set by setSubtotal().
*/
public double getSubtotal() throws RemoteException {
return subTotal;
}
/**
* Sets the subtotal price.
*
* Our external pricer bean is responsible for
* calculating the subtotal. It calculates it
* based upon customer discounts (and can be
* extended to include other rules as well).
*/
public void setSubtotal(double subTotal) throws RemoteException {
this.subTotal = subTotal;
}
/**
* Returns the taxes computed for this Cart.
*/
public double getTaxes() throws RemoteException {
return taxes;
}
/**
* Sets the taxes for this Cart.
*/
public void setTaxes(double taxes) throws RemoteException {
this.taxes = taxes;
}
/**
* Returns the total price. Total Price
* is computed from:
* 1) Subtotal price
* 2) Tax
*/
public double getTotalPrice() throws RemoteException {
return subTotal + taxes;
}
/**
* Empties the shopping cart
*/
public void clear() {
System.out.println("clear()");
contents.clear();
}
/**
* Purchases this cart. The cart will create
* an order in the database.
*
* @return The Order confirmation number
*/
public String purchase() {
try {
/*
* Lookup for the order home
*/
OrderHome home=getOrderHome();
/*
* Creates the order
*/
String orderID = makeUniqueID();
Order order=home.create(orderID, owner,"unverified",subTotal,taxes);
/*
* Creates the orderlineitems
*/
Vector orderItems=addOrderLineItems(order);
/*
* Sets the orderlineitems in the Order
*/
order.setLineItems(orderItems);
/*
* Sends the JMS message to the topic
*/
sendMessage(orderID);
/*
* Return the order ID
*/
return orderID;
} catch (Exception e) {
throw new EJBException(e);
}
}
/**
* Sends the JMS message to the topic
*
*@param JMS message, in this case orderId
*/
private void sendMessage(String message) throws Exception{
try{
MessageSender sender=new MessageSender();
sender.sendMessage(message);
}catch(Exception ex){
throw ex;
}
}
/**
* Creates the orderlineitems
*/
private Vector addOrderLineItems(Order order){
try{
Context ctx = new InitialContext();
OrderLineItemHome orderLineItemHome = (OrderLineItemHome)
PortableRemoteObject.narrow(
ctx.lookup("OrderLineItemHome"), OrderLineItemHome.class);
BookHome bookHome = (BookHome)
PortableRemoteObject.narrow(
ctx.lookup("BookHome"), BookHome.class);
Vector orderItems=new Vector();
for (int i=0; i < contents.size(); i++) {
/*
* Extract the fields from
* the cart Line Item...
*/
LineItem item =(LineItem) contents.elementAt(i);
/*
* loads the Book entity bean
*/
Book book=bookHome.findByPrimaryKey(item.getBookItem().getBookID());
String id = makeUniqueID();
/*
* And shove the fields into
* a new Order Line Item.
*/
OrderLineItem orderLineItem = orderLineItemHome.create(id, order, book, item.getQuantity(),item.getDiscount()) ;
orderItems.add(orderLineItem);
}
return orderItems;
} catch (Exception e) {
throw new EJBException(e);
}
}
/**
* Returns unique Id based on current time
*/
private String makeUniqueID(){
return new Long(System.currentTimeMillis()).toString();
}
/**
* Returns an Order home
*/
private OrderHome getOrderHome(){
try{
Context ctx = new InitialContext();
OrderHome home = (OrderHome)
PortableRemoteObject.narrow(
ctx.lookup("OrderHome"), OrderHome.class);
return home;
} catch (Exception e) {
throw new EJBException(e);
}
}
//
// EJB-required methods
//
/**
* Associates this Bean instance with a particular
* context.
*/
public void setSessionContext(SessionContext ctx) {
System.out.println("setSessionContext()");
this.ctx = ctx;
}
/**
* This is the initialization method that
* corresponds to the create() method in the
* Home Interface.
*
* When the client calls the Home Object's
* create() method, the Home Object then calls
* this ejbCreate() method.
*/
public void ejbCreate(String owner) {
System.out.println("ejbCreate(" + owner + ")");
this.owner = owner;
contents = new Vector();
}
/**
* The container calls this method directly after
* activating this instance. You should acquire
* any needed resources.
*/
public void ejbActivate() {
System.out.println("ejbActivate()");
}
/**
* The container calls this method directly before
* passivating this instance. You should release
* resources acquired during ejbActivate().
*/
public void ejbPassivate() {
System.out.println("ejbPassivate()");
}
/**
* Removes this Cart, and hence all client-
* specific state.
*
* In our example, there is really no way for
* the client to 'abort' the Cart, so the EJB
* Container will call this when the Session
* times out.
*/
public void ejbRemove() {
System.out.println("ejbRemove()");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -