📄 shoppingcartbean.java
字号:
/*
* @author : Neelesh
* @Version : 1.0
*
* Development Environment : Oracle9i JDeveloper
* Name of the File : ShoppingCartBean.java
* Creation/Modification History :
*
* Neelesh 04-Oct-2002 Created
*
*/
package oracle.otnsamples.vsm.services;
// EJB
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import oracle.otnsamples.util.KeyFactory;
import oracle.otnsamples.util.ServiceLocator;
import oracle.otnsamples.util.Utilities;
import oracle.otnsamples.vsm.Constants;
import oracle.otnsamples.vsm.entities.CustomerLocal;
import oracle.otnsamples.vsm.entities.CustomerLocalHome;
import oracle.otnsamples.vsm.entities.ItemDetailLocal;
import oracle.otnsamples.vsm.entities.ItemDetailLocalHome;
import oracle.otnsamples.vsm.entities.ItemDetailPK;
import oracle.otnsamples.vsm.entities.ItemLocal;
import oracle.otnsamples.vsm.entities.ItemLocalHome;
import oracle.otnsamples.vsm.entities.OrderItemLocal;
import oracle.otnsamples.vsm.entities.OrderItemLocalHome;
import oracle.otnsamples.vsm.entities.ProductOrderLocal;
import oracle.otnsamples.vsm.entities.ProductOrderLocalHome;
import oracle.otnsamples.vsm.services.data.Address;
import oracle.otnsamples.vsm.services.data.CartItem;
/**
* This is the implementation for Shopping Cart Services.
* The bean provides implementations for methods defined in the Shopping Cart
* interface. The bean is implemented as a stateful session bean to track a
* user's shopping cart. The bean interacts with various local entities to
* manage persistence. The references to these entities can be found in ejb-jar.xml
*/
public class ShoppingCartBean implements SessionBean {
// contents of the cart, a table of itemids v/s CartItem objects
private HashMap cartContents;
// the locale of the user
public Locale userLocale;
// shipping addreess for the items in cart
private Address shippingAddress;
// cart user
private String userName;
// Session context of the stateful bean
private SessionContext context;
/**
* The business methods removes an item from the cart
* @param <b>itemID</b> - id of the item to be removed
* @throws <b>CartException</b> if the item cannot be removed
*/
public void removeFromCart( String itemID ) throws CartException {
// Remove the value from the table of
cartContents.remove( String.valueOf( itemID ) );
}
/**
* The business methods changes the shipping address
* @param <b>address</b> - the new shipping address
* @throws <b>CartException</b> if the shipping address cannot be changed
*/
public void changeShippingAddress( Address address ) throws CartException {
shippingAddress = address;
}
/**
* The business methods checks out the cart
* @return <b>String</b> - the checkout status
* @throws <b>CartException</b> if checkout fails
*/
public String checkout() throws CartException {
if(userName==null){
throw new CartException("Invalid user","error.cart.nulluser");
}
try {
// Get all items in the cart
CartItem[] cart = getCart();
if(cart.length>0){
// make sure that shipping address is set
getShippingAddress();
ItemLocalHome itemHome = getItemLocalHome();
ProductOrderLocalHome productOrderHome = getOrderLocalHome();
OrderItemLocalHome orderItemHome = getOrderItemLocalHome();
// create a new product order with user name, current date
ProductOrderLocal order = productOrderHome.create( KeyFactory.getKey(),
new Date(), userName );
//set the shipping address for the order
order.setPhone( shippingAddress.getPhone() );
order.setCity( shippingAddress.getCity() );
order.setCountry( shippingAddress.getCountry() );
order.setShipToAddress( shippingAddress.getAddress() );
order.setState( shippingAddress.getState() );
order.setZip( new Integer( shippingAddress.getZip() ) );
// Find the current order items, there will be none
Collection orderItems = new ArrayList();
// Failure message is initialized.
String checkoutFailMessage = "";
// For each item in the cart,
String orderId = order.getId();
// Orders are always accepted at checkout time. The shop owner
// will decide whether to approve or reject the orders
for( int i = cart.length-1;i >=0 ;i-- ) {
try{
// create an order item for the item
OrderItemLocal orderItem = orderItemHome.create(cart[i].getId(),
orderId, cart[i].getShopId(),
Constants.PURCHASED,
cart[i].getQuantity(),
cart[i].getUnitPrice());
orderItem.setShopID(cart[i].getShopId());
orderItems.add( orderItem );
// remove checked out item from cart
cartContents.remove( cart[i].getId());
}catch(EJBException ex){
checkoutFailMessage += cart[i].getItemName() + ",";
}
}
// after creating order items, set them to product order to maintain
//Order-OrderItem relation
order.setOrderItems( orderItems );
// If all the items could not be processed, a few items were left out
if( checkoutFailMessage.length() != 0 ) {
// Remove the , at the end
checkoutFailMessage = checkoutFailMessage.
substring(0,checkoutFailMessage.length()-1);
return Utilities.loadParams("CartMessages_"+userLocale.getLanguage()).
getProperty("error.checkout.outofstock")+checkoutFailMessage;
}
else {// check out successful
return null;
}
}else{
return Utilities.loadParams("CartMessages_"+userLocale.getLanguage())
.getProperty("error.checkout.emptycart");
}
}
catch( Exception ex ) {
context.setRollbackOnly();
ex.printStackTrace();
//unknown error has occurred, rollback all database txns
throw new CartException( "Unable to checkout cart because " +
ex.getMessage(),"error.cart.checkoutfail" );
}
}
/**
* Gets the username for the cart
* @return <b>String </b> username
*/
public String getUserName() {
return userName;
}
/**
* The business methods adds an item to the cart
* @param <b>itemID</b> - id of the item to be added
* @param <b>qty</b> quantity to be added
* @throws <b>CartException</b> if the item cannot be added
*/
public void addToCart( String itemID, int qty ) throws CartException {
try {
CartItem cartItem = null;
// Check if this item is already there in the cart
if( cartContents.containsKey( itemID ) ) {
cartItem = (CartItem)cartContents.get( itemID );
}
else {
// If it is not there, create a new cart item
cartItem = new CartItem();
// find Item Entity for the id provided
ItemLocalHome itemhome = (ItemLocalHome)ServiceLocator.getLocator().
getService( "java:comp/env/ejb/ItemLocal" );
ItemLocal item = itemhome.findByPrimaryKey( itemID );
ItemDetailLocalHome home = getItemDetailLocalHome();
ItemDetailLocal itemDetail = home.findByPrimaryKey
(new ItemDetailPK(itemID,userLocale.getLanguage()));
// set the cart items name, andd unit price
cartItem.setItemName( itemDetail.getName());
cartItem.setUnitPrice( itemDetail.getUnitPrice().doubleValue());
cartItem.setShopId(item.getShopID());
// place the new item in cart
cartContents.put( itemID, cartItem );
}
// set the id of the item
cartItem.setId( itemID );
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -