01 /*
02 *
03 * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
04 *
05 */
06 package demo.townsend.action;
07
08 import java.util.Iterator;
09 import java.util.List;
10
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 import javax.servlet.http.HttpSession;
14
15 import org.apache.struts.action.Action;
16 import org.apache.struts.action.ActionForm;
17 import org.apache.struts.action.ActionForward;
18 import org.apache.struts.action.ActionMapping;
19 import org.apache.struts.action.ActionMessage;
20 import org.apache.struts.action.ActionMessages;
21
22 import demo.townsend.common.Constants;
23 import demo.townsend.form.AddToListForm;
24 import demo.townsend.service.DataKeeper;
25 import demo.townsend.service.Product;
26 import demo.townsend.service.ProductCatalog;
27
28 /**
29 * AddToListAction processes the request to add an item to the user's list.
30 * User's list is fetched from the HttpSession object, the item indicated in the
31 * AddToListForm is added to the list, and the modified list is loaded back into
32 * the HttpSession object.
33 */
34 public class AddToListAction extends Action {
35 @Override
36 public ActionForward execute(ActionMapping mapping, ActionForm form,
37 HttpServletRequest request, HttpServletResponse response)
38 throws Exception {
39
40 String newProdId = ((AddToListForm) form).getId();
41 Product newProd = null;
42 List<Product> catalog = new ProductCatalog().getCatalog();
43 for (Iterator<Product> iter = catalog.iterator(); iter.hasNext();) {
44 Product p = iter.next();
45 if (p.getId().equals(newProdId)) {
46 newProd = p;
47 }
48 }
49
50 HttpSession session = request.getSession();
51 if (session == null) {
52 ActionMessages errors = new ActionMessages();
53 errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
54 "error.expired.session"));
55 saveErrors(request, errors);
56 return mapping.findForward(Constants.NO_SESSION);
57 }
58 DataKeeper dkeeper = (DataKeeper) session
59 .getAttribute(Constants.DATA_KEY);
60 if (dkeeper == null) {
61 dkeeper = new DataKeeper();
62 }
63
64 dkeeper.addListItem(newProd);
65
66 session.setAttribute(Constants.DATA_KEY, dkeeper);
67
68 return mapping.findForward(Constants.SUCCESS_KEY);
69 }
70 }
|