KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jfox > petstore > domain > Cart


1 /*
2  * JFox - The most lightweight Java EE Application Server!
3  * more details please visit http://www.huihoo.org/jfox or http://www.jfox.org.cn.
4  *
5  * JFox is licenced and re-distributable under GNU LGPL.
6  */

7 package org.jfox.petstore.domain;
8
9 import java.io.Serializable JavaDoc;
10 import java.util.Collection JavaDoc;
11 import java.util.Collections JavaDoc;
12 import java.util.Map JavaDoc;
13 import java.util.TreeMap JavaDoc;
14
15 import org.jfox.petstore.entity.Item;
16
17 /**
18  * Cart is not a Entity Object, just a logic domain Object contain CartItem
19  */

20 public class Cart implements Serializable JavaDoc {
21
22     // itemId => CartItem
23
private final Map JavaDoc<String JavaDoc, CartItem> itemMap = Collections.synchronizedMap(new TreeMap JavaDoc<String JavaDoc, CartItem>());
24
25     public Collection JavaDoc<CartItem> getCartItemList() {
26         return itemMap.values();
27     }
28
29     public CartItem getCartItem(String JavaDoc itemId){
30         return itemMap.get(itemId);
31     }
32
33     public int getNumberOfItems() {
34         return itemMap.size();
35     }
36
37     public boolean containsItemId(String JavaDoc itemId) {
38         return itemMap.containsKey(itemId);
39     }
40
41     public void addItem(Item item, boolean isInStock) {
42         CartItem cartItem = itemMap.get(item.getItemId());
43         if (cartItem == null) {
44             cartItem = new CartItem();
45             cartItem.setItem(item);
46             cartItem.setQuantity(0);
47             cartItem.setInStock(isInStock);
48             itemMap.put(item.getItemId(), cartItem);
49         }
50         cartItem.incrementQuantity();
51     }
52
53
54     public Item removeItemById(String JavaDoc itemId) {
55         CartItem cartItem = itemMap.remove(itemId);
56         if (cartItem == null) {
57             return null;
58         }
59         else {
60             return cartItem.getItem();
61         }
62     }
63
64     public void incrementQuantityByItemId(String JavaDoc itemId) {
65         CartItem cartItem = itemMap.get(itemId);
66         cartItem.incrementQuantity();
67     }
68
69     public void setQuantityByItemId(String JavaDoc itemId, int quantity) {
70         CartItem cartItem = itemMap.get(itemId);
71         cartItem.setQuantity(quantity);
72     }
73
74     public double getSubTotal() {
75         double subTotal = 0;
76         for(CartItem cartItem : itemMap.values()){
77             Item item = cartItem.getItem();
78             double listPrice = item.getListPrice();
79             int quantity = cartItem.getQuantity();
80             subTotal += listPrice * quantity;
81         }
82         return subTotal;
83     }
84 }
85
Popular Tags