1
package com.bittercode.util;
3
import java.io.PrintWriter;
5
import javax.servlet.http.HttpServletRequest;
6
import javax.servlet.http.HttpSession;
8
import com.bittercode.model.UserRole;
11
* Store UTil File To Store Commonly used methods
13
public class StoreUtil {
16
* Check if the User is logged in with the requested role
18
public static boolean isLoggedIn(UserRole role, HttpSession session) {
20
return session.getAttribute(role.toString()) != null;
24
* Modify the active tab in the page menu bar
26
public static void setActiveTab(PrintWriter pw, String activeTab) {
28
pw.println("<script>document.getElementById(activeTab).classList.remove(\"active\");activeTab=" + activeTab
30
pw.println("<script>document.getElementById('" + activeTab + "').classList.add(\"active\");</script>");
35
* Add/Remove/Update Item in the cart using the session
37
public static void updateCartItems(HttpServletRequest req) {
38
String selectedBookId = req.getParameter("selectedBookId");
39
HttpSession session = req.getSession();
40
if (selectedBookId != null) { // add item to the cart
42
// Items will contain comma separated bookIds that needs to be added in the cart
43
String items = (String) session.getAttribute("items");
44
if (req.getParameter("addToCart") != null) { // add to cart
45
if (items == null || items.length() == 0)
46
items = selectedBookId;
47
else if (!items.contains(selectedBookId))
48
items = items + "," + selectedBookId; // if items already contains bookId, don't add it
50
// set the items in the session to be used later
51
session.setAttribute("items", items);
54
* Quantity of each item in the cart will be stored in the session as:
55
* Prefixed with qty_ following its bookId
56
* For example 2 no. of book with id 'myBook' in the cart will be
57
* added to the session as qty_myBook=2
60
if (session.getAttribute("qty_" + selectedBookId) != null)
61
itemQty = (int) session.getAttribute("qty_" + selectedBookId);
63
session.setAttribute("qty_" + selectedBookId, itemQty);
64
} else { // remove from the cart
66
if (session.getAttribute("qty_" + selectedBookId) != null)
67
itemQty = (int) session.getAttribute("qty_" + selectedBookId);
70
session.setAttribute("qty_" + selectedBookId, itemQty);
72
session.removeAttribute("qty_" + selectedBookId);
73
items = items.replace(selectedBookId + ",", "");
74
items = items.replace("," + selectedBookId, "");
75
items = items.replace(selectedBookId, "");
76
session.setAttribute("items", items);