1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package com.ibatis.jpetstore.presentation;
17
18 import com.ibatis.jpetstore.domain.Cart;
19 import com.ibatis.jpetstore.domain.CartItem;
20 import com.ibatis.jpetstore.domain.Item;
21 import com.ibatis.jpetstore.service.CatalogService;
22 import com.ibatis.struts.ActionContext;
23 import com.ibatis.struts.BaseBean;
24
25 import java.util.Iterator;
26 import java.util.Map;
27
28 public class CartBean extends BaseBean {
29
30
31
32 private static final CatalogService catalogService = CatalogService.getInstance();
33
34
35
36 private Cart cart = new Cart();
37 private String workingItemId;
38 private String pageDirection;
39
40
41
42 public Cart getCart() {
43 return cart;
44 }
45
46 public void setCart(Cart cart) {
47 this.cart = cart;
48 }
49
50 public String getWorkingItemId() {
51 return workingItemId;
52 }
53
54 public void setWorkingItemId(String workingItemId) {
55 this.workingItemId = workingItemId;
56 }
57
58 public String getPageDirection() {
59 return pageDirection;
60 }
61
62 public void setPageDirection(String pageDirection) {
63 this.pageDirection = pageDirection;
64 }
65
66
67
68 public String addItemToCart() {
69 if (cart.containsItemId(workingItemId)) {
70 cart.incrementQuantityByItemId(workingItemId);
71 } else {
72
73
74
75 boolean isInStock = catalogService.isItemInStock(workingItemId);
76 Item item = catalogService.getItem(workingItemId);
77 cart.addItem(item, isInStock);
78 }
79
80 return "success";
81 }
82
83 public String removeItemFromCart() {
84
85 Item item = cart.removeItemById(workingItemId);
86
87 if (item == null) {
88 ActionContext.getActionContext().setSimpleMessage("Attempted to remove null CartItem from Cart.");
89 return "failure";
90 } else {
91 return "success";
92 }
93 }
94
95 public String updateCartQuantities() {
96 Map parameterMap = ActionContext.getActionContext().getParameterMap();
97
98 Iterator cartItems = getCart().getAllCartItems();
99 while (cartItems.hasNext()) {
100 CartItem cartItem = (CartItem) cartItems.next();
101 String itemId = cartItem.getItem().getItemId();
102 try {
103 int quantity = Integer.parseInt((String) parameterMap.get(itemId));
104 getCart().setQuantityByItemId(itemId, quantity);
105 if (quantity < 1) {
106 cartItems.remove();
107 }
108 } catch (Exception e) {
109
110 }
111 }
112
113 return "success";
114 }
115
116 public String switchCartPage() {
117 if ("next".equals(pageDirection)) {
118 cart.getCartItemList().nextPage();
119 } else if ("previous".equals(pageDirection)) {
120 cart.getCartItemList().previousPage();
121 }
122 return "success";
123 }
124
125 public String viewCart() {
126 return "success";
127 }
128
129 public void clear() {
130 cart = new Cart();
131 workingItemId = null;
132 pageDirection = null;
133 }
134
135 }