Advertisement
Lauda

AjaxServlet (Handler)

Jul 2nd, 2014
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 15.90 KB | None | 0 0
  1. package servlets;
  2.  
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. import java.util.ArrayList;
  6.  
  7. import javax.servlet.ServletException;
  8. import javax.servlet.http.HttpServlet;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import javax.servlet.http.HttpSession;
  12.  
  13. import model.Bill;
  14. import model.Category;
  15. import model.Component;
  16. import model.Device;
  17. import model.Item;
  18. import model.User;
  19. import model.UserRole;
  20.  
  21. import org.json.JSONException;
  22. import org.json.simple.JSONObject;
  23. import org.json.simple.parser.JSONParser;
  24.  
  25. import DB.WebShop;
  26. import functions.UndoAction;
  27.  
  28. public class AjaxServlet extends HttpServlet {
  29.  
  30.     /**
  31.      *
  32.      */
  33.     private static final long serialVersionUID = -5279877218992865295L;
  34.  
  35.     public AjaxServlet()
  36.     {
  37.         super();
  38.     }
  39.     @SuppressWarnings("unchecked")
  40.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  41.         HttpSession session = request.getSession();
  42.         User user = (User) session.getAttribute("user");
  43.  
  44.         if (user == null)
  45.         {
  46.             response.sendError(401, "You are not authorised for this action. Please log in.");
  47.             return;
  48.         }
  49.  
  50.         String data = request.getParameter("data");
  51.         JSONObject ajaxRequest = null;
  52.        
  53.         if (data != null)
  54.         {
  55.             JSONParser parser = new JSONParser();
  56.             try
  57.             {
  58.                 Object tmp = parser.parse(data);
  59.                 ajaxRequest = (JSONObject) tmp;
  60.  
  61.             } catch (Exception e) {
  62.                 // TODO Auto-generated catch block
  63.                 e.printStackTrace();
  64.             }
  65.         }
  66.  
  67.         // Let's get action:
  68.         if (ajaxRequest != null)
  69.         {
  70.             try {
  71.                 if (ajaxRequest.get("action") != null)
  72.                 {
  73.                     String key = (String) ajaxRequest.get("key");
  74.                     String bean = (String) ajaxRequest.get("bean");
  75.                     JSONObject obj = new JSONObject();
  76.  
  77.                     if (ajaxRequest.get("action").equals("delete"))
  78.                     {
  79.                         doDelete(bean, key, request, response);
  80.                     }
  81.                     // This action is only available for devices
  82.                     else if (ajaxRequest.get("action").equals("unpublish"))
  83.                     {
  84.                         doUnpublish(key, request, response);
  85.                     }
  86.                     // This action is only available for devices
  87.                     else if (ajaxRequest.get("action").equals("publish"))
  88.                     {
  89.                         doPublish(key, request, response);
  90.                     }
  91.                     else if (ajaxRequest.get("action").equals("addcart"))
  92.                     {
  93.                         String amount = (String)ajaxRequest.get("amount");
  94.                         Boolean edit = (ajaxRequest.get("edit") != null);
  95.                         System.out.println(edit);
  96.                         doAddCart(bean, key, amount, edit, request, response);
  97.                     }
  98.                     else if (ajaxRequest.get("action").equals("removeCart"))
  99.                     {
  100.                         doRemoveCart(bean, key, request, response);
  101.                     }
  102.                     else
  103.                     {
  104.                         response.setContentType("application/json; charset=UTF-8");
  105.                         obj.put("error", new Boolean(true));
  106.                         obj.put("message", "Action is not defined.");
  107.                         PrintWriter pw = response.getWriter();
  108.                         pw.print(obj);
  109.                     }
  110.                 }
  111.             } catch (JSONException e) {
  112.                 // TODO Auto-generated catch block
  113.                 e.printStackTrace();
  114.             }
  115.         }
  116.     }
  117.  
  118.     @SuppressWarnings("unchecked")
  119.     private void doDelete(String bean, String key, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  120.         HttpSession session = request.getSession();
  121.         WebShop ws = (WebShop) getServletContext().getAttribute("webShop");
  122.         User user = (User) session.getAttribute("user");
  123.  
  124.         // We can do this and use SessionCheckFilter too...just in case
  125.         if(user.getRole() != UserRole.ADMIN.getValue())
  126.         {
  127.             response.sendError(401, "You are not authorised for this action. Only admins can delete users.");
  128.             return;
  129.         }
  130.  
  131.         UndoAction undoer = UndoAction.getInstance();
  132.         response.setContentType("application/json; charset=UTF-8");
  133.         JSONObject obj = new JSONObject();
  134.  
  135.         if (bean == null || key == null)
  136.         {
  137.             response.sendError(400, "Invalid request!");
  138.             return;
  139.         }
  140.  
  141.         if (bean.equals("user"))
  142.         {
  143.             // Let's try not to delete ourselves...
  144.             User logged = (User) session.getAttribute("user");
  145.             User deletedUser = null;
  146.  
  147.             if (!logged.getKey().equals(key) )
  148.             {
  149.                 deletedUser = (User)ws.getUsers().remove(key);
  150.             }
  151.  
  152.             // Return removed user:
  153.             if (deletedUser != null)
  154.             {
  155.                 String undoKey = undoer.add(deletedUser);
  156.                 obj.put("undoKey", undoKey);
  157.                 obj.put("error", new Boolean(false));
  158.                 obj.put("deletedKeys", deletedUser.getKey());
  159.                 obj.put("message", "User successfully deleted.");
  160.             }
  161.             // Something terribly wrong happened and user was not deleted
  162.             else
  163.             {
  164.                 obj.put("error", new Boolean(true));
  165.                 obj.put("deletedKeys", null);
  166.                 obj.put("message", "Error deleting user.");
  167.             }
  168.         }
  169.         else if (bean.equals("category"))
  170.         {
  171.             Category deletedCategory = (Category)ws.getCategories().remove(key);   
  172.             if (deletedCategory != null)
  173.             {
  174.                 ArrayList<Category> recursiveDelete = new ArrayList<Category>();
  175.                 ArrayList<String> deletedKeys = new ArrayList<String>();
  176.                 ArrayList<String> deletedComponents = new ArrayList<String>();
  177.                 deletedKeys.add(deletedCategory.getKey());
  178.                 String additionalMessage = "";
  179.  
  180.                 // If we are removing a category, we might as well remove subcategories too, riiiiight?
  181.                 // TODO: Add some warning before removing subcats and components XDD
  182.                 deletedComponents.addAll(deletedCategory.removeComponents()); // Remove components that were under root category
  183.                 for (Category c : deletedCategory.getSubcategories())
  184.                 {
  185.                     recursiveDelete.add(c);
  186.                 }
  187.  
  188.                 for (Category category : recursiveDelete) {
  189.                     ws.getCategories().remove(category.getKey());
  190.                     deletedKeys.add(category.getKey());
  191.                     deletedComponents.addAll(category.removeComponents()); // remove components that were under subcategory
  192.                 }
  193.  
  194.                 if(recursiveDelete.size() > 0)
  195.                     additionalMessage = "Subcategories deleted as well.";
  196.  
  197.                 obj.put("error", new Boolean(false));
  198.                 obj.put("deletedKeys", deletedKeys);
  199.                 obj.put("deletedComponents", deletedComponents);
  200.                 obj.put("message", "Category successfully deleted. " + additionalMessage);
  201.  
  202.             }
  203.             else { //delete failed
  204.                 obj.put("error", new Boolean(true));
  205.                 obj.put("deletedKeys", null);
  206.                 obj.put("message", "Error deleting category.");
  207.             }
  208.  
  209.         }
  210.         else if (bean.equals("component"))
  211.         {
  212.             Component deletedComponent = (Component)ws.getComponents().remove(key);
  213.  
  214.             // Return removed component:
  215.             if (deletedComponent != null)
  216.             {
  217.                 String undoKey = undoer.add(deletedComponent);
  218.                 obj.put("undoKey", undoKey);
  219.                 obj.put("error", new Boolean(false));
  220.                 obj.put("deletedKeys", deletedComponent.getKey());
  221.                 obj.put("message", "Component successfully deleted.");
  222.             }
  223.             // Something terribly wrong happened...
  224.             else
  225.             {
  226.                 obj.put("error", new Boolean(true));
  227.                 obj.put("deletedKeys", null);
  228.                 obj.put("message", "Error deleting component.");
  229.             }
  230.         }
  231.         else if(bean.equals("device"))
  232.         {
  233.             Device deletedDevice = (Device) ws.getDevices().remove(key);
  234.  
  235.             if (deletedDevice != null)
  236.             {
  237.                 String undoKey = undoer.add(deletedDevice);
  238.                 obj.put("undoKey", undoKey);
  239.                 obj.put("error", new Boolean(false));
  240.                 obj.put("deletedKeys", deletedDevice.getKey());
  241.                 obj.put("message", "Device successfully deleted.");
  242.             }
  243.             else
  244.             { //delete failed
  245.                 obj.put("error", new Boolean(true));
  246.                 obj.put("deletedKeys", null);
  247.                 obj.put("message", "Error deleting device.");
  248.             }
  249.         }
  250.         else {
  251.             obj.put("error", new Boolean(true));
  252.             obj.put("message", "Action is not defined.");
  253.         }
  254.  
  255.         PrintWriter pw = response.getWriter();
  256.         pw.print(obj);
  257.     }
  258.  
  259.     @SuppressWarnings("unchecked")
  260.     private void doUnpublish(String key, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException
  261.     {
  262.         HttpSession session = request.getSession();
  263.         WebShop ws = (WebShop) getServletContext().getAttribute("webShop");
  264.         User user = (User) session.getAttribute("user");
  265.  
  266.         // TODO: Add check in SessionCheckFilter as well
  267.         if(user.getRole() != UserRole.ADMIN.getValue())
  268.         {
  269.             response.sendError(401, "You are not authorised for this action. Only admins can unpublish devices.");
  270.             return;
  271.         }
  272.  
  273.         response.setContentType("application/json; charset=UTF-8");
  274.         JSONObject obj = new JSONObject();
  275.  
  276.         if(key == null)
  277.         {
  278.             response.sendError(400, "Invalid request!");
  279.             return;
  280.         }
  281.  
  282.         if (ws.getDevices().containsKey(key))
  283.         {
  284.             ws.getDevices().get(key).setAvailable(false);
  285.             obj.put("error", new Boolean(false));
  286.             obj.put("message", "Device unpublished successfully.");
  287.         }
  288.         else
  289.         {
  290.             obj.put("error", new Boolean(true));
  291.             obj.put("message", "Error unpublishing device.");
  292.         }
  293.  
  294.         PrintWriter pw = response.getWriter();
  295.         pw.print(obj);
  296.     }
  297.  
  298.     @SuppressWarnings("unchecked")
  299.     private void doPublish(String key, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException
  300.     {
  301.         HttpSession session = request.getSession();
  302.         WebShop ws = (WebShop) getServletContext().getAttribute("webShop");
  303.         User user = (User) session.getAttribute("user");
  304.  
  305.         if(user.getRole() != UserRole.ADMIN.getValue())
  306.         {
  307.             response.sendError(401, "You are not authorised for this action. Only admins can publish devices.");
  308.             return;
  309.         }
  310.  
  311.         response.setContentType("application/json; charset=UTF-8");
  312.         JSONObject obj = new JSONObject();
  313.  
  314.         if (key == null)
  315.         {
  316.             response.sendError(400, "Invalid request!");
  317.             return;
  318.         }
  319.  
  320.         if (ws.getDevices().containsKey(key))
  321.         {
  322.             ws.getDevices().get(key).setAvailable(true);
  323.             obj.put("error", new Boolean(false));
  324.             obj.put("message", "Device published successfully.");
  325.         }
  326.         else
  327.         {
  328.             outputError(response, "Error publishing device.");
  329.         }
  330.  
  331.         PrintWriter pw = response.getWriter();
  332.         pw.print(obj);
  333.     }
  334.  
  335.     @SuppressWarnings("unchecked")
  336.     private void doAddCart(String bean, String key, String amount, Boolean edit, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException
  337.     {
  338.         HttpSession session = request.getSession();
  339.         WebShop ws = (WebShop) getServletContext().getAttribute("webShop");
  340.         User user = (User) session.getAttribute("user");
  341.         Bill cart = (Bill) session.getAttribute("cart");
  342.         int _amountRequested = 1;
  343.  
  344.         try{
  345.             _amountRequested = Integer.parseInt(amount);
  346.         } catch (Exception ex) {
  347.         //  ex.printStackTrace();
  348.         }
  349.  
  350.         // We don't want to have admins going around and randomly buying stuff...ehehe only users can do such thing!
  351.         if(user.getRole() == UserRole.ADMIN.getValue())
  352.         {
  353.             response.sendError(401, "You are not authorised for this action. Only users can add to their carts.");
  354.             return;
  355.         }
  356.  
  357.         response.setContentType("application/json; charset=UTF-8");
  358.         JSONObject obj = new JSONObject();
  359.  
  360.         if (bean == null || key == null)
  361.         {
  362.             response.sendError(400, "Invalid request!");
  363.             return;
  364.         }
  365.  
  366.         bean = bean.toLowerCase();
  367.         if (bean.equals("component") || bean.equals("device"))
  368.         {
  369.             Item item = null;
  370.  
  371.             if (ws.getComponents().containsKey(key))
  372.             {
  373.                 item = ws.getComponents().get(key);
  374.             }
  375.             else if(ws.getDevices().containsKey(key))
  376.             {
  377.                 item = ws.getDevices().get(key);
  378.             }
  379.             else
  380.             {
  381.                 outputError(response, "Item does not exist.");
  382.                 return;
  383.             }
  384.  
  385.             Boolean inCart = cart.getItems().containsKey(item);
  386.             int inCartAmout = 0;
  387.             String itemName = "n/a", itemType = "n/a", itemDesc = "n/a", itemKey = "n/a";
  388.             double itemPrice = 0.0;
  389.             if (inCart)
  390.             {
  391.                 inCartAmout = cart.getItems().get(item);
  392.             }
  393.  
  394.             // Checking if item is available in stock && we have enough for user to buy:
  395.             if (item instanceof Component)
  396.             {
  397.                 itemName = item.getName();
  398.                 itemType = item.getTypeof();
  399.                 itemDesc = item.getDescription();
  400.                 itemPrice = item.getPrice();
  401.                 itemKey = item.getKey();
  402.                
  403.                 int afterAdding = ((Component)item).getAmount();
  404.                 if (edit)
  405.                 {
  406.                     afterAdding -= _amountRequested; // Current inCartAmout will be overwritten
  407.                 }
  408.                 else
  409.                 {
  410.                     afterAdding -= (inCartAmout + 1);
  411.                 }
  412.  
  413.                 if (afterAdding < 0)
  414.                 {
  415.                     outputError(response, "You cannot order more items than available amount.");
  416.                     return;
  417.                 }
  418.             }
  419.            
  420.             itemName = item.getName();
  421.             itemType = item.getTypeof();
  422.             itemDesc = item.getDescription();
  423.             itemPrice = item.getPrice();
  424.             itemKey = item.getKey();
  425.  
  426.             System.out.println("Adding to cart '" + key + "'... Item already in cart: " + inCart + " :: add amount: " + _amountRequested);
  427.  
  428.             if (edit)
  429.             {
  430.                 cart.changeAmount(item, _amountRequested);
  431.                 obj.put("message", "Successfully increased \"" + key + "\" amount.");
  432.             }
  433.             else
  434.             {
  435.                 cart.insert(item, _amountRequested);
  436.                 obj.put("message", "Successfully added item \"" + key + "\" to the cart.");
  437.                
  438.             }
  439.  
  440.             obj.put("error", new Boolean(false));
  441.             obj.put("itemKey", itemKey);
  442.             obj.put("itemName", itemName);
  443.             obj.put("itemType", itemType);
  444.             obj.put("itemDesc", itemDesc);
  445.             obj.put("itemPrice", itemPrice);
  446.             obj.put("itemAmount", _amountRequested);
  447.             obj.put("cartItems", cart.getCount());
  448.             obj.put("type", "addedit");
  449.  
  450.         }
  451.         else
  452.         {
  453.             outputError(response,  "Error adding to cart, invalid device type.");
  454.             return;
  455.         }
  456.         PrintWriter pw = response.getWriter();
  457.         pw.print(obj);
  458.     }
  459.  
  460.     @SuppressWarnings("unchecked")
  461.     private void outputError(HttpServletResponse response, String message) throws IOException, JSONException
  462.     {
  463.         JSONObject obj = new JSONObject();
  464.         obj.put("error", new Boolean(true));
  465.         obj.put("message", message);
  466.  
  467.         PrintWriter pw = response.getWriter();
  468.         pw.print(obj);
  469.     }
  470.  
  471.     @SuppressWarnings("unchecked")
  472.     private void doRemoveCart(String bean, String key, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException
  473.     {
  474.         HttpSession session = request.getSession();
  475.         WebShop ws = (WebShop) getServletContext().getAttribute("webShop");
  476.         User user = (User) session.getAttribute("user");
  477.         Bill cart = (Bill) session.getAttribute("cart");
  478.  
  479.         if(user.getRole() == UserRole.ADMIN.getValue()){
  480.             response.sendError(401, "You are not authorised for this action. Only users can add to their carts.");
  481.             return;
  482.         }
  483.  
  484.         response.setContentType("application/json; charset=UTF-8");
  485.         JSONObject obj = new JSONObject();
  486.  
  487.         if(bean == null || key == null){
  488.             response.sendError(400, "Invalid request!");
  489.             return;
  490.         }
  491.  
  492.         bean = bean.toLowerCase();
  493.  
  494.         if (bean.equals("component"))
  495.         {
  496.             if (ws.getComponents().containsKey(key))
  497.             {
  498.                 Component c = ws.getComponents().get(key);
  499.                 cart.getItems().remove(c);
  500.                 obj.put("error", new Boolean(false));
  501.                 obj.put("message", "Successfully removed component \""+key+"\" from the cart.");
  502.                 obj.put("cartItems", cart.getCount());
  503.                 obj.put("cartPrice", cart.getTotalPrice());
  504.                 obj.put("removedKey", key);
  505.                 obj.put("type", "remove");
  506.             }
  507.             else
  508.             {
  509.                 obj.put("error", new Boolean(true));
  510.                 obj.put("message", "Component \""+key+"\" could not be deleted form cart.");
  511.                 obj.put("cartItems", cart.getCount());
  512.                 obj.put("cartPrice", cart.getTotalPrice());
  513.                 obj.put("type", "remove");
  514.             }
  515.  
  516.         }
  517.         else if (bean.equals("device"))
  518.         {
  519.             if (ws.getDevices().containsKey(key))
  520.             {
  521.                 Device d = ws.getDevices().get(key);
  522.                 cart.getItems().remove(d);
  523.                 obj.put("error", new Boolean(false));
  524.                 obj.put("message", "Successfully removed device \""+key+"\" from the cart.");
  525.                 obj.put("cartItems", cart.getCount());
  526.                 obj.put("cartPrice", cart.getTotalPrice());
  527.                 obj.put("removedKey", key);
  528.                 obj.put("type", "remove");
  529.             }
  530.             else
  531.             {
  532.                 obj.put("error", new Boolean(true));
  533.                 obj.put("message", "Device \""+key+"\" could not be deleted form cart.");
  534.                 obj.put("cartItems", cart.getCount());
  535.                 obj.put("cartPrice", cart.getTotalPrice());
  536.                 obj.put("type", "remove");
  537.             }
  538.         }
  539.         else
  540.         {
  541.             outputError(response, "Error removing from, invalid device type.");
  542.             return;
  543.         }
  544.  
  545.         PrintWriter pw = response.getWriter();
  546.         pw.print(obj);
  547.     }
  548. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement