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