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