📄 cartbean.java
字号:
package examples;
import java.util.*;
import javax.ejb.*;
import java.rmi.RemoteException;
import javax.rmi.PortableRemoteObject;
import javax.naming.*;
import javax.jms.*;
/*
* This stateful session bean represents a cart which a customer is
* working on. A cart is a set of products that the customer is
* interested in, but has not committed to buying yet. As the
* customer surfs our Jasmine's web site, this bean stores all the
* products and quantities he is interested in.
*
* A cart consists of a series of line-items. Each line-item
* represents one particular product the customer wants, as well as a
* quantity and discount for that product.
*
* The distinction between a cart and an order is that a quote is only
* temporary and in-memory (hence a stateful session bean), whereas an
* order is a persistent record (hence an entity bean). This quote
* bean is smart enough to know how to transform itself into an order
* (via the purchase() method).
*/
public class CartBean
implements javax.ejb.SessionBean
{
private static final String productHomeName = "java:comp/env/ejb/ProductHome";
/**
* 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
* productID passed in. If found, modify that lineitem.
*/
Iterator i = contents.iterator();
try
{
while (i.hasNext())
{
LineItem item = (LineItem) i.next();
ProductItem product=item.getProductItem();
if (product != null &&
product.getProductID().equals(lineItem.getProductItem().getProductID()))
{
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 product Id
* @param number of items.
*/
public void modify(String productID, int quantity)
throws Exception
{
System.out.println("CartBean.modify()");
/*
* Search for a lineitem in the cart that match the
* productID passed in. If found, modify that lineitem.
*/
Iterator i = contents.iterator();
while (i.hasNext())
{
LineItem item = (LineItem) i.next();
ProductItem product=item.getProductItem();
if (product!=null && product.getProductID().equals(productID))
{
item.setQuantity(quantity);
if (quantity == 0)
{
i.remove();
}
return;
}
}
throw new Exception("CartBean.modify() error: Could not find product " +
productID);
}
/**
* Loads the entity bean for the given product id
*
* @param product Id
* @return product entity bean remote object
*/
private Product getProduct(String productId)
{
try
{
Context ctx = new InitialContext();
ProductHome productHome =
(ProductHome)PortableRemoteObject.narrow(
ctx.lookup(productHomeName), ProductHome.class);
Product product = productHome.findByPrimaryKey(productId);
return product;
}
catch (Exception e)
{
throw new EJBException(e);
}
}
/**
* Returns all the shopping cart line items
*
* @return A collection of Cart LineItems
*/
public Vector 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()
{
contents.clear();
}
/**
* Purchases this cart. The cart will create
* an order in the database.
*
* @return The Order confirmation number
*/
public String purchase()
{
System.out.println("CartBean.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 order line items
*/
Vector orderItems = addOrderLineItems(order);
/*
* Sets the order line items 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 a JMS message to a destination (Queue or Topic)
*
* @param a message string, in this case orderId
*/
private void sendMessage(String text)
throws Exception
{
Connection connection = null;
MessageProducer producer = null;
Session session = null;
try
{
Context jndiContext = new InitialContext();
ConnectionFactory connectionFactory =
(ConnectionFactory)jndiContext.lookup("jms/MyQcf");
Destination destination =
(Destination)jndiContext.lookup("jms/OrderQueue");
connection = connectionFactory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = session.createProducer(destination);
connection.start();
TextMessage msg = session.createTextMessage();
msg.setText(text);
producer.send(msg);
}
catch(Exception ex)
{
throw ex;
}
finally
{
if (connection != null)
{
try
{
producer.close();
connection.close();
session.close();
}
catch (JMSException e)
{
// ignore
}
}
}
}
/**
* Creates the orderlineitems
*/
private Vector addOrderLineItems(Order order)
{
try
{
Context ctx = new InitialContext();
OrderLineItemHome orderLineItemHome =
(OrderLineItemHome)PortableRemoteObject.narrow(
ctx.lookup("java:comp/env/ejb/OrderLineItemHome"), OrderLineItemHome.class);
ProductHome productHome =
(ProductHome)PortableRemoteObject.narrow(
ctx.lookup(productHomeName), ProductHome.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 product entity bean
*/
Product product =
productHome.findByPrimaryKey(item.getProductItem().getProductID());
String id = makeUniqueID();
/*
* And shove the fields into
* a new Order Line Item.
*/
OrderLineItem orderLineItem =
orderLineItemHome.create(id,
order,
product,
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("java:comp/env/ejb/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 quote, and hence all client-
* specific state.
*
* In our example, there is really no way for
* the client to 'abort' the quote, 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 + -