1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mybatis.jpetstore.web.actions;
17
18 import java.util.Iterator;
19
20 import javax.servlet.http.HttpServletRequest;
21
22 import net.sourceforge.stripes.action.ForwardResolution;
23 import net.sourceforge.stripes.action.Resolution;
24 import net.sourceforge.stripes.action.SessionScope;
25 import net.sourceforge.stripes.integration.spring.SpringBean;
26
27 import org.mybatis.jpetstore.domain.Cart;
28 import org.mybatis.jpetstore.domain.CartItem;
29 import org.mybatis.jpetstore.domain.Item;
30 import org.mybatis.jpetstore.service.CatalogService;
31
32
33
34
35
36
37 @SessionScope
38 public class CartActionBean extends AbstractActionBean {
39
40 private static final long serialVersionUID = -4038684592582714235L;
41
42 private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
43 private static final String CHECK_OUT = "/WEB-INF/jsp/cart/Checkout.jsp";
44
45 @SpringBean
46 private transient CatalogService catalogService;
47
48 private Cart cart = new Cart();
49 private String workingItemId;
50
51 public Cart getCart() {
52 return cart;
53 }
54
55 public void setCart(Cart cart) {
56 this.cart = cart;
57 }
58
59 public void setWorkingItemId(String workingItemId) {
60 this.workingItemId = workingItemId;
61 }
62
63
64
65
66
67
68 public Resolution 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 new ForwardResolution(VIEW_CART);
81 }
82
83
84
85
86
87
88 public Resolution removeItemFromCart() {
89
90 Item item = cart.removeItemById(workingItemId);
91
92 if (item == null) {
93 setMessage("Attempted to remove null CartItem from Cart.");
94 return new ForwardResolution(ERROR);
95 } else {
96 return new ForwardResolution(VIEW_CART);
97 }
98 }
99
100
101
102
103
104
105 public Resolution updateCartQuantities() {
106 HttpServletRequest request = context.getRequest();
107
108 Iterator<CartItem> cartItems = getCart().getAllCartItems();
109 while (cartItems.hasNext()) {
110 CartItem cartItem = cartItems.next();
111 String itemId = cartItem.getItem().getItemId();
112 try {
113 int quantity = Integer.parseInt(request.getParameter(itemId));
114 getCart().setQuantityByItemId(itemId, quantity);
115 if (quantity < 1) {
116 cartItems.remove();
117 }
118 } catch (Exception e) {
119
120 }
121 }
122
123 return new ForwardResolution(VIEW_CART);
124 }
125
126 public ForwardResolution viewCart() {
127 return new ForwardResolution(VIEW_CART);
128 }
129
130 public ForwardResolution checkOut() {
131 return new ForwardResolution(CHECK_OUT);
132 }
133
134 public void clear() {
135 cart = new Cart();
136 workingItemId = null;
137 }
138
139 }