01: package org.springunit.framework.samples.jpetstore.domain;
02:
03: import java.io.Serializable;
04: import java.util.Collections;
05: import java.util.HashMap;
06: import java.util.Iterator;
07: import java.util.Map;
08:
09: import org.springframework.beans.support.PagedListHolder;
10:
11: public class Cart implements Serializable {
12:
13: public Cart() {
14: this .itemList.setPageSize(4);
15: }
16:
17: public Iterator<CartItem> getAllCartItems() {
18: return (Iterator<CartItem>) this .itemList.getSource()
19: .iterator();
20: }
21:
22: public PagedListHolder getCartItemList() {
23: return this .itemList;
24: }
25:
26: public int getNumberOfItems() {
27: return this .itemList.getSource().size();
28: }
29:
30: public boolean containsItemId(Integer itemId) {
31: return this .itemMap.containsKey(itemId);
32: }
33:
34: public void addItem(Item item, boolean isInStock) {
35: CartItem cartItem = this .itemMap.get(item.getId());
36: if (cartItem == null) {
37: cartItem = new CartItem();
38: cartItem.setItem(item);
39: cartItem.setQuantity(0);
40: cartItem.setInStock(isInStock);
41: this .itemMap.put(item.getId(), cartItem);
42: this .itemList.getSource().add(cartItem);
43: }
44: cartItem.incrementQuantity();
45: }
46:
47: public Item removeItemById(Integer itemId) {
48: CartItem cartItem = this .itemMap.remove(itemId);
49: if (cartItem == null) {
50: return null;
51: } else {
52: this .itemList.getSource().remove(cartItem);
53: return cartItem.getItem();
54: }
55: }
56:
57: public void incrementQuantityByItemId(Integer itemId) {
58: CartItem cartItem = this .itemMap.get(itemId);
59: cartItem.incrementQuantity();
60: }
61:
62: public void setQuantityByItemId(Integer itemId, int quantity) {
63: CartItem cartItem = this .itemMap.get(itemId);
64: cartItem.setQuantity(quantity);
65: }
66:
67: public double getSubTotal() {
68: double subTotal = 0;
69: Iterator<CartItem> items = getAllCartItems();
70: while (items.hasNext()) {
71: CartItem cartItem = items.next();
72: Item item = cartItem.getItem();
73: double listPrice = item.getListPrice();
74: int quantity = cartItem.getQuantity();
75: subTotal += listPrice * quantity;
76: }
77: return subTotal;
78: }
79:
80: private static final long serialVersionUID = 8L;
81:
82: private final Map<Integer, CartItem> itemMap = Collections
83: .synchronizedMap(new HashMap<Integer, CartItem>());
84:
85: private final PagedListHolder itemList = new PagedListHolder();
86:
87: }
|