-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStoreUtil.java
More file actions
77 lines (62 loc) · 3.02 KB
/
StoreUtil.java
File metadata and controls
77 lines (62 loc) · 3.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.bittercode.util;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import com.bittercode.model.UserRole;
/*
* Store UTil File To Store Commonly used methods
*/
public class StoreUtil {
public static boolean isLoggedIn(UserRole role, HttpSession session) {
return session.getAttribute(role.toString()) != null;
}
/**
* Add/Remove/Update Item in the cart using the session
*/
public static void setActiveTab(PrintWriter pw, String activeTab) {
pw.println("<script>document.getElementById(activeTab).classList.remove(\"active\");activeTab=" + activeTab
+ "</script>");
pw.println("<script>document.getElementById('" + activeTab + "').classList.add(\"active\");</script>");
}
public static void updateCartItems(HttpServletRequest req) {
String selectedBookId = req.getParameter("selectedBookId");
HttpSession session = req.getSession();
if (selectedBookId != null) { // add item to the cart
// Items will contain comma separated bookIds that needs to be added in the cart
String items = (String) session.getAttribute("items");
if (req.getParameter("addToCart") != null) { // add to cart
if (items == null || items.length() == 0)
items = selectedBookId;
else if (!items.contains(selectedBookId))
items = items + "," + selectedBookId; // if items already contains bookId, don't add it
// set the items in the session to be used later
session.setAttribute("items", items);
/*
* Quantity of each item in the cart will be stored in the session as:
* Prefixed with qty_ following its bookId
* For example 2 no. of book with id 'myBook' in the cart will be
* added to the session as qty_myBook=2
*/
int itemQty = 0;
if (session.getAttribute("qty_" + selectedBookId) != null)
itemQty = (int) session.getAttribute("qty_" + selectedBookId);
itemQty += 1;
session.setAttribute("qty_" + selectedBookId, itemQty);
} else { // remove from the cart
int itemQty = 0;
if (session.getAttribute("qty_" + selectedBookId) != null)
itemQty = (int) session.getAttribute("qty_" + selectedBookId);
if (itemQty > 1) {
itemQty--;
session.setAttribute("qty_" + selectedBookId, itemQty);
} else {
session.removeAttribute("qty_" + selectedBookId);
items = items.replace(selectedBookId + ",", "");
items = items.replace("," + selectedBookId, "");
items = items.replace(selectedBookId, "");
session.setAttribute("items", items);
}
}
}
}
}