Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package servlets;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.ArrayList;
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- import model.Bill;
- import model.Category;
- import model.Component;
- import model.Device;
- import model.Item;
- import model.User;
- import model.UserRole;
- import org.json.JSONException;
- import org.json.simple.JSONObject;
- import org.json.simple.parser.JSONParser;
- import DB.WebShop;
- import functions.UndoAction;
- public class AjaxServlet extends HttpServlet {
- /**
- *
- */
- private static final long serialVersionUID = -5279877218992865295L;
- public AjaxServlet()
- {
- super();
- }
- @SuppressWarnings("unchecked")
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- HttpSession session = request.getSession();
- User user = (User) session.getAttribute("user");
- if (user == null)
- {
- response.sendError(401, "You are not authorised for this action. Please log in.");
- return;
- }
- String data = request.getParameter("data");
- JSONObject ajaxRequest = null;
- if (data != null)
- {
- JSONParser parser = new JSONParser();
- try
- {
- Object tmp = parser.parse(data);
- ajaxRequest = (JSONObject) tmp;
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- // Let's get action:
- if (ajaxRequest != null)
- {
- try {
- if (ajaxRequest.get("action") != null)
- {
- String key = (String) ajaxRequest.get("key");
- String bean = (String) ajaxRequest.get("bean");
- JSONObject obj = new JSONObject();
- if (ajaxRequest.get("action").equals("delete"))
- {
- doDelete(bean, key, request, response);
- }
- // This action is only available for devices
- else if (ajaxRequest.get("action").equals("unpublish"))
- {
- doUnpublish(key, request, response);
- }
- // This action is only available for devices
- else if (ajaxRequest.get("action").equals("publish"))
- {
- doPublish(key, request, response);
- }
- else if (ajaxRequest.get("action").equals("addcart"))
- {
- String amount = (String)ajaxRequest.get("amount");
- Boolean edit = (ajaxRequest.get("edit") != null);
- System.out.println(edit);
- doAddCart(bean, key, amount, edit, request, response);
- }
- else if (ajaxRequest.get("action").equals("removeCart"))
- {
- doRemoveCart(bean, key, request, response);
- }
- else
- {
- response.setContentType("application/json; charset=UTF-8");
- obj.put("error", new Boolean(true));
- obj.put("message", "Action is not defined.");
- PrintWriter pw = response.getWriter();
- pw.print(obj);
- }
- }
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- @SuppressWarnings("unchecked")
- private void doDelete(String bean, String key, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- HttpSession session = request.getSession();
- WebShop ws = (WebShop) getServletContext().getAttribute("webShop");
- User user = (User) session.getAttribute("user");
- // We can do this and use SessionCheckFilter too...just in case
- if(user.getRole() != UserRole.ADMIN.getValue())
- {
- response.sendError(401, "You are not authorised for this action. Only admins can delete users.");
- return;
- }
- UndoAction undoer = UndoAction.getInstance();
- response.setContentType("application/json; charset=UTF-8");
- JSONObject obj = new JSONObject();
- if (bean == null || key == null)
- {
- response.sendError(400, "Invalid request!");
- return;
- }
- if (bean.equals("user"))
- {
- // Let's try not to delete ourselves...
- User logged = (User) session.getAttribute("user");
- User deletedUser = null;
- if (!logged.getKey().equals(key) )
- {
- deletedUser = (User)ws.getUsers().remove(key);
- }
- // Return removed user:
- if (deletedUser != null)
- {
- String undoKey = undoer.add(deletedUser);
- obj.put("undoKey", undoKey);
- obj.put("error", new Boolean(false));
- obj.put("deletedKeys", deletedUser.getKey());
- obj.put("message", "User successfully deleted.");
- }
- // Something terribly wrong happened and user was not deleted
- else
- {
- obj.put("error", new Boolean(true));
- obj.put("deletedKeys", null);
- obj.put("message", "Error deleting user.");
- }
- }
- else if (bean.equals("category"))
- {
- Category deletedCategory = (Category)ws.getCategories().remove(key);
- if (deletedCategory != null)
- {
- ArrayList<Category> recursiveDelete = new ArrayList<Category>();
- ArrayList<String> deletedKeys = new ArrayList<String>();
- ArrayList<String> deletedComponents = new ArrayList<String>();
- deletedKeys.add(deletedCategory.getKey());
- String additionalMessage = "";
- // If we are removing a category, we might as well remove subcategories too, riiiiight?
- // TODO: Add some warning before removing subcats and components XDD
- deletedComponents.addAll(deletedCategory.removeComponents()); // Remove components that were under root category
- for (Category c : deletedCategory.getSubcategories())
- {
- recursiveDelete.add(c);
- }
- for (Category category : recursiveDelete) {
- ws.getCategories().remove(category.getKey());
- deletedKeys.add(category.getKey());
- deletedComponents.addAll(category.removeComponents()); // remove components that were under subcategory
- }
- if(recursiveDelete.size() > 0)
- additionalMessage = "Subcategories deleted as well.";
- obj.put("error", new Boolean(false));
- obj.put("deletedKeys", deletedKeys);
- obj.put("deletedComponents", deletedComponents);
- obj.put("message", "Category successfully deleted. " + additionalMessage);
- }
- else { //delete failed
- obj.put("error", new Boolean(true));
- obj.put("deletedKeys", null);
- obj.put("message", "Error deleting category.");
- }
- }
- else if (bean.equals("component"))
- {
- Component deletedComponent = (Component)ws.getComponents().remove(key);
- // Return removed component:
- if (deletedComponent != null)
- {
- String undoKey = undoer.add(deletedComponent);
- obj.put("undoKey", undoKey);
- obj.put("error", new Boolean(false));
- obj.put("deletedKeys", deletedComponent.getKey());
- obj.put("message", "Component successfully deleted.");
- }
- // Something terribly wrong happened...
- else
- {
- obj.put("error", new Boolean(true));
- obj.put("deletedKeys", null);
- obj.put("message", "Error deleting component.");
- }
- }
- else if(bean.equals("device"))
- {
- Device deletedDevice = (Device) ws.getDevices().remove(key);
- if (deletedDevice != null)
- {
- String undoKey = undoer.add(deletedDevice);
- obj.put("undoKey", undoKey);
- obj.put("error", new Boolean(false));
- obj.put("deletedKeys", deletedDevice.getKey());
- obj.put("message", "Device successfully deleted.");
- }
- else
- { //delete failed
- obj.put("error", new Boolean(true));
- obj.put("deletedKeys", null);
- obj.put("message", "Error deleting device.");
- }
- }
- else {
- obj.put("error", new Boolean(true));
- obj.put("message", "Action is not defined.");
- }
- PrintWriter pw = response.getWriter();
- pw.print(obj);
- }
- @SuppressWarnings("unchecked")
- private void doUnpublish(String key, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException
- {
- HttpSession session = request.getSession();
- WebShop ws = (WebShop) getServletContext().getAttribute("webShop");
- User user = (User) session.getAttribute("user");
- // TODO: Add check in SessionCheckFilter as well
- if(user.getRole() != UserRole.ADMIN.getValue())
- {
- response.sendError(401, "You are not authorised for this action. Only admins can unpublish devices.");
- return;
- }
- response.setContentType("application/json; charset=UTF-8");
- JSONObject obj = new JSONObject();
- if(key == null)
- {
- response.sendError(400, "Invalid request!");
- return;
- }
- if (ws.getDevices().containsKey(key))
- {
- ws.getDevices().get(key).setAvailable(false);
- obj.put("error", new Boolean(false));
- obj.put("message", "Device unpublished successfully.");
- }
- else
- {
- obj.put("error", new Boolean(true));
- obj.put("message", "Error unpublishing device.");
- }
- PrintWriter pw = response.getWriter();
- pw.print(obj);
- }
- @SuppressWarnings("unchecked")
- private void doPublish(String key, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException
- {
- HttpSession session = request.getSession();
- WebShop ws = (WebShop) getServletContext().getAttribute("webShop");
- User user = (User) session.getAttribute("user");
- if(user.getRole() != UserRole.ADMIN.getValue())
- {
- response.sendError(401, "You are not authorised for this action. Only admins can publish devices.");
- return;
- }
- response.setContentType("application/json; charset=UTF-8");
- JSONObject obj = new JSONObject();
- if (key == null)
- {
- response.sendError(400, "Invalid request!");
- return;
- }
- if (ws.getDevices().containsKey(key))
- {
- ws.getDevices().get(key).setAvailable(true);
- obj.put("error", new Boolean(false));
- obj.put("message", "Device published successfully.");
- }
- else
- {
- outputError(response, "Error publishing device.");
- }
- PrintWriter pw = response.getWriter();
- pw.print(obj);
- }
- @SuppressWarnings("unchecked")
- private void doAddCart(String bean, String key, String amount, Boolean edit, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException
- {
- HttpSession session = request.getSession();
- WebShop ws = (WebShop) getServletContext().getAttribute("webShop");
- User user = (User) session.getAttribute("user");
- Bill cart = (Bill) session.getAttribute("cart");
- int _amountRequested = 1;
- try{
- _amountRequested = Integer.parseInt(amount);
- } catch (Exception ex) {
- // ex.printStackTrace();
- }
- // We don't want to have admins going around and randomly buying stuff...ehehe only users can do such thing!
- if(user.getRole() == UserRole.ADMIN.getValue())
- {
- response.sendError(401, "You are not authorised for this action. Only users can add to their carts.");
- return;
- }
- response.setContentType("application/json; charset=UTF-8");
- JSONObject obj = new JSONObject();
- if (bean == null || key == null)
- {
- response.sendError(400, "Invalid request!");
- return;
- }
- bean = bean.toLowerCase();
- if (bean.equals("component") || bean.equals("device"))
- {
- Item item = null;
- if (ws.getComponents().containsKey(key))
- {
- item = ws.getComponents().get(key);
- }
- else if(ws.getDevices().containsKey(key))
- {
- item = ws.getDevices().get(key);
- }
- else
- {
- outputError(response, "Item does not exist.");
- return;
- }
- Boolean inCart = cart.getItems().containsKey(item);
- int inCartAmout = 0;
- String itemName = "n/a", itemType = "n/a", itemDesc = "n/a", itemKey = "n/a";
- double itemPrice = 0.0;
- if (inCart)
- {
- inCartAmout = cart.getItems().get(item);
- }
- // Checking if item is available in stock && we have enough for user to buy:
- if (item instanceof Component)
- {
- itemName = item.getName();
- itemType = item.getTypeof();
- itemDesc = item.getDescription();
- itemPrice = item.getPrice();
- itemKey = item.getKey();
- int afterAdding = ((Component)item).getAmount();
- if (edit)
- {
- afterAdding -= _amountRequested; // Current inCartAmout will be overwritten
- }
- else
- {
- afterAdding -= (inCartAmout + 1);
- }
- if (afterAdding < 0)
- {
- outputError(response, "You cannot order more items than available amount.");
- return;
- }
- }
- itemName = item.getName();
- itemType = item.getTypeof();
- itemDesc = item.getDescription();
- itemPrice = item.getPrice();
- itemKey = item.getKey();
- System.out.println("Adding to cart '" + key + "'... Item already in cart: " + inCart + " :: add amount: " + _amountRequested);
- if (edit)
- {
- cart.changeAmount(item, _amountRequested);
- obj.put("message", "Successfully increased \"" + key + "\" amount.");
- }
- else
- {
- cart.insert(item, _amountRequested);
- obj.put("message", "Successfully added item \"" + key + "\" to the cart.");
- }
- obj.put("error", new Boolean(false));
- obj.put("itemKey", itemKey);
- obj.put("itemName", itemName);
- obj.put("itemType", itemType);
- obj.put("itemDesc", itemDesc);
- obj.put("itemPrice", itemPrice);
- obj.put("itemAmount", _amountRequested);
- obj.put("cartItems", cart.getCount());
- obj.put("type", "addedit");
- }
- else
- {
- outputError(response, "Error adding to cart, invalid device type.");
- return;
- }
- PrintWriter pw = response.getWriter();
- pw.print(obj);
- }
- @SuppressWarnings("unchecked")
- private void outputError(HttpServletResponse response, String message) throws IOException, JSONException
- {
- JSONObject obj = new JSONObject();
- obj.put("error", new Boolean(true));
- obj.put("message", message);
- PrintWriter pw = response.getWriter();
- pw.print(obj);
- }
- @SuppressWarnings("unchecked")
- private void doRemoveCart(String bean, String key, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException
- {
- HttpSession session = request.getSession();
- WebShop ws = (WebShop) getServletContext().getAttribute("webShop");
- User user = (User) session.getAttribute("user");
- Bill cart = (Bill) session.getAttribute("cart");
- if(user.getRole() == UserRole.ADMIN.getValue()){
- response.sendError(401, "You are not authorised for this action. Only users can add to their carts.");
- return;
- }
- response.setContentType("application/json; charset=UTF-8");
- JSONObject obj = new JSONObject();
- if(bean == null || key == null){
- response.sendError(400, "Invalid request!");
- return;
- }
- bean = bean.toLowerCase();
- if (bean.equals("component"))
- {
- if (ws.getComponents().containsKey(key))
- {
- Component c = ws.getComponents().get(key);
- cart.getItems().remove(c);
- obj.put("error", new Boolean(false));
- obj.put("message", "Successfully removed component \""+key+"\" from the cart.");
- obj.put("cartItems", cart.getCount());
- obj.put("cartPrice", cart.getTotalPrice());
- obj.put("removedKey", key);
- obj.put("type", "remove");
- }
- else
- {
- obj.put("error", new Boolean(true));
- obj.put("message", "Component \""+key+"\" could not be deleted form cart.");
- obj.put("cartItems", cart.getCount());
- obj.put("cartPrice", cart.getTotalPrice());
- obj.put("type", "remove");
- }
- }
- else if (bean.equals("device"))
- {
- if (ws.getDevices().containsKey(key))
- {
- Device d = ws.getDevices().get(key);
- cart.getItems().remove(d);
- obj.put("error", new Boolean(false));
- obj.put("message", "Successfully removed device \""+key+"\" from the cart.");
- obj.put("cartItems", cart.getCount());
- obj.put("cartPrice", cart.getTotalPrice());
- obj.put("removedKey", key);
- obj.put("type", "remove");
- }
- else
- {
- obj.put("error", new Boolean(true));
- obj.put("message", "Device \""+key+"\" could not be deleted form cart.");
- obj.put("cartItems", cart.getCount());
- obj.put("cartPrice", cart.getTotalPrice());
- obj.put("type", "remove");
- }
- }
- else
- {
- outputError(response, "Error removing from, invalid device type.");
- return;
- }
- PrintWriter pw = response.getWriter();
- pw.print(obj);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement