⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 shoppingcartejb.java

📁 《J2EE企业级应用开发》一书的配套源代码
💻 JAVA
字号:
package com.j2eeapp.cdstore.cart;

import java.rmi.RemoteException;
import javax.ejb.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Collection;
import com.j2eeapp.cdstore.servicelocator.*;
import com.j2eeapp.cdstore.vo.*;
import com.j2eeapp.cdstore.util.*;
import com.j2eeapp.cdstore.storage.*;
import com.j2eeapp.cdstore.order.*;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * This interface provides methods to add an item to the
 *  * shoppingcart, delete an item from the shopping cart,
 *  * and update item quantities in the shopping cart.
 */
public class ShoppingCartEJB implements SessionBean
{
    /**
     * Attributes declaration
    */
    public SessionContext EJB_Context = null;
    private HashMap cart;
    
    /**
     * @J2EE_METHOD  --  ShoppingCartEJB
     */
    public ShoppingCartEJB    ()  
    { 
    	 cart = new HashMap();

    }
    
    /**
     * @J2EE_METHOD  --  ejbCreate
     * Called by the container to create a session bean instance. Its parameters typically
     * contain the information the client uses to customize the bean instance for its use.
     * It requires a matching pair in the bean class and its home interface.
     */
    public void ejbCreate    ()  
    { 
		 cart = new HashMap();
    }
    
    /**
     * @J2EE_METHOD  --  ejbRemove
     * A container invokes this method before it ends the life of the session object. This
     * happens as a result of a client's invoking a remove operation, or when a container
     * decides to terminate the session object after a timeout. This method is called with
     * no transaction context.
     */
    public void ejbRemove    ()  
    { 

    }
    
    /**
     * @J2EE_METHOD  --  ejbActivate
     * The activate method is called when the instance is activated from its 'passive' state.
     * The instance should acquire any resource that it has released earlier in the ejbPassivate()
     * method. This method is called with no transaction context.
     */
    public void ejbActivate    ()  
    { 

    }
    
    /**
     * @J2EE_METHOD  --  ejbPassivate
     * The passivate method is called before the instance enters the 'passive' state. The
     * instance should release any resources that it can re-acquire later in the ejbActivate()
     * method. After the passivate method completes, the instance must be in a state that
     * allows the container to use the Java Serialization protocol to externalize and store
     * away the instance's state. This method is called with no transaction context.
     */
    public void ejbPassivate    ()  
    { 

    }
    
    /**
     * @J2EE_METHOD  --  setSessionContext
     * Set the associated session context. The container calls this method after the instance
     * creation. The enterprise Bean instance should store the reference to the context
     * object in an instance variable. This method is called with no transaction context.
     */
    public void setSessionContext    (SessionContext sc)  
    { 
		this.EJB_Context=sc;
    }
    
    /**
     * @J2EE_METHOD  --  addItem
     */
    public void addItem    (String itemId) throws RemoteException 
    { 
    	cart.put(itemId, new Integer(1));

    }
    
    public void addItem    (String itemId,int newQty)  throws RemoteException
    { 
    	cart.put(itemId, new Integer(newQty));

    }
    
    
    /**
     * @J2EE_METHOD  --  getItems
     */
    public Collection getItems    ()  throws RemoteException,ServiceLocatorException
    { 
    	HashMap map = cart;
       Collection items = new ArrayList();
       Iterator it = map.keySet().iterator();
       while (it.hasNext())
       {
           String key = (String)it.next();
          // System.out.println(key);
           Integer value = (Integer)map.get(key);
          try {
	           ItemLocalHome itemHome=getItemHome();
	           ItemLocal itemLocal=itemHome.findByPrimaryKey(key);
	           Item item = null;
	           item = itemLocal.getData();
	           // System.out.println(item.getItemId());
	               // convert item item to cart item
               CartItem ci = new CartItem(item.getItemId(),
                                      item.getProductId(),
                                      item.getCategory(),
                                      item.getProductName(),
                                      item.getAttr(),
                                      value.intValue(),
                                      item.getUnitPrice());
               items.add(ci);
           } catch (Exception cce) {
               System.out.println("ShoppingCartEJB caught: " +cce);
               //System.out.println(cce.getClass());
               //cce.printStackTrace(System.out);
           }
           
           
       }
       return items;		
    }
    
   public void deleteItem (String itemID)throws RemoteException
    { 
        cart.remove(itemID);
    } 
    
    /**
     * @J2EE_METHOD  --  updateItemQuantity
     */
    public void updateItemQuantity    (String itemID, int newQty) throws RemoteException 
    { 
	   cart.remove(itemID);
        // remove item if it is less than or equal to 0
        if (newQty > 0) cart.put(itemID, new Integer(newQty));
    }
    
    /**
     * @J2EE_METHOD  --  empty
     */
    public void empty    () throws RemoteException 
    { 
		cart.clear();
    }
    
    /**
     * @J2EE_METHOD  --  getCount
     */
    public Integer getCount    ()  throws RemoteException
    { 
 		 return new Integer(cart.size());
    }
    
    /**
     * @J2EE_METHOD  --  getSubTotal
     */
    public double getSubTotal    ()  throws RemoteException,ServiceLocatorException
    { 
 		  Collection items = getItems();
        if (items == null) return 0.0d;
        // put the subtotal in the request
        double ret = 0.0d;
        // total up the quantities
        for (Iterator it =items.iterator(); it.hasNext(); ) {
            CartItem i = (CartItem) it.next();
            ret += (i.getUnitCost() * i.getQuantity()) ;
        }
        return  ret; 
    }
    public ItemLocalHome getItemHome()throws RemoteException,ServiceLocatorException
    {
    	return (ItemLocalHome)(new EJBServiceLocator().getLocalHome(JNDINames.ITEMLOCAL));
    }
    
    public String checkOut(ContactInfo contactInfo,ShippingInfo shippingInfo,BillingInfo billingInfo,CreditCard card,String cardPassword,String userId)
    	throws RemoteException,NamingException,CreateException,ServiceLocatorException
    {
    	try
    	{
    		
	    	OrderLocalHome orderLocalHome=(OrderLocalHome)new InitialContext().lookup(JNDINames.ORDER);
	    	String orderId=String.valueOf(System.currentTimeMillis());
	    	OrderLocal order=orderLocalHome.create(orderId);
	    	order.setBillingInfo(billingInfo);
	    	order.setShippingInfo(shippingInfo);
	    	order.setContactInfo(contactInfo);
	    	order.setCreditCard(card);
	    	order.setUserId(userId);
	    	order.setOrderDate(System.currentTimeMillis());
	    	order.setTotalPrice((new Double(getSubTotal())).floatValue());
	    	order.setLineItems(getLineItems());
	    	order.setOrderStatus(getOrderStatus(orderId));
	    	//empty();//清空购物车
	    	if(order.payMoneyToBank(cardPassword))
	    		   return orderId;
	        else
	        		return new String("card password is error,or deposite in you card is not enough!");
	      }
	      catch(Exception e)
	      {
	      	System.out.println(e.getMessage());
	      	return null;
	      }
	      
	       
    }
    public OrderStatusLocal getOrderStatus(String orderId)throws NamingException,CreateException
    {
    	OrderStatusLocalHome orderStatusHome=(OrderStatusLocalHome)new InitialContext().lookup(JNDINames.ORDERSTATUS);
    	OrderStatusLocal orderStatus=orderStatusHome.create(new OrderStatus(orderId,orderId,OrderStatusLocalHome.ORDER_STATUS_NOTCOMFIRMED));
    	return orderStatus;
    }
    public Collection getLineItems()throws RemoteException,NamingException,CreateException,ServiceLocatorException
    {
    	
    	try
    	{
    		Collection items = getItems();
	    	Collection re=new ArrayList();
	    	int i=0;
	        LineItemLocalHome itemHome=(LineItemLocalHome)new InitialContext().lookup(JNDINames.LINEITEM);
	        LineItemLocal itemLocal;
	        for (Iterator it =items.iterator(); it.hasNext(); )
	        {
	            CartItem cart = (CartItem) it.next();
	            LineItem lineItem=new LineItem(System.currentTimeMillis()+"_"+i,cart.getItemId(),cart.getQuantity(),cart.getUnitCost());
	            itemLocal =itemHome.create(lineItem);
	            re.add(itemLocal);
	            i++;
	        }
	        return re;
	     }
	     catch(Exception e)
	     {
	     	System.out.println(e.getMessage());
	     	return null;
	     }
	     	
            
    }
    	
    
  
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -