test
Форк от lirfrnk/test
1package com.bittercode.util;
2
3import java.io.PrintWriter;
4
5import javax.servlet.http.HttpServletRequest;
6import javax.servlet.http.HttpSession;
7
8import com.bittercode.model.UserRole;
9
10/*
11* Store UTil File To Store Commonly used methods
12*/
13public class StoreUtil {
14
15/**
16* Check if the User is logged in with the requested role
17*/
18public static boolean isLoggedIn(UserRole role, HttpSession session) {
19
20return session.getAttribute(role.toString()) != null;
21}
22
23/**
24* Modify the active tab in the page menu bar
25*/
26public static void setActiveTab(PrintWriter pw, String activeTab) {
27
28pw.println("<script>document.getElementById(activeTab).classList.remove(\"active\");activeTab=" + activeTab
29+ "</script>");
30pw.println("<script>document.getElementById('" + activeTab + "').classList.add(\"active\");</script>");
31
32}
33
34/**
35* Add/Remove/Update Item in the cart using the session
36*/
37public static void updateCartItems(HttpServletRequest req) {
38String selectedBookId = req.getParameter("selectedBookId");
39HttpSession session = req.getSession();
40if (selectedBookId != null) { // add item to the cart
41
42// Items will contain comma separated bookIds that needs to be added in the cart
43String items = (String) session.getAttribute("items");
44if (req.getParameter("addToCart") != null) { // add to cart
45if (items == null || items.length() == 0)
46items = selectedBookId;
47else if (!items.contains(selectedBookId))
48items = items + "," + selectedBookId; // if items already contains bookId, don't add it
49
50// set the items in the session to be used later
51session.setAttribute("items", items);
52
53/*
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
58*/
59int itemQty = 0;
60if (session.getAttribute("qty_" + selectedBookId) != null)
61itemQty = (int) session.getAttribute("qty_" + selectedBookId);
62itemQty += 1;
63session.setAttribute("qty_" + selectedBookId, itemQty);
64} else { // remove from the cart
65int itemQty = 0;
66if (session.getAttribute("qty_" + selectedBookId) != null)
67itemQty = (int) session.getAttribute("qty_" + selectedBookId);
68if (itemQty > 1) {
69itemQty--;
70session.setAttribute("qty_" + selectedBookId, itemQty);
71} else {
72session.removeAttribute("qty_" + selectedBookId);
73items = items.replace(selectedBookId + ",", "");
74items = items.replace("," + selectedBookId, "");
75items = items.replace(selectedBookId, "");
76session.setAttribute("items", items);
77}
78}
79}
80
81}
82}
83