Package oss.ngocminh.lego.service

Source Code of oss.ngocminh.lego.service.OrderCreateController

package oss.ngocminh.lego.service;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oss.ngocminh.lego.data.Entity;
import oss.ngocminh.lego.data.EntityImpl;
import oss.ngocminh.lego.persistence.ProductDAO;

/**
* Servlet implementation class OrderCreateController
*/
public class OrderCreateController extends AbstractController {

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    try {
      Connection conn = getConnection();
      ProductDAO productDAO = new ProductDAO(conn);
      int productId = Integer.parseInt(req.getParameter("product"));
      Entity product = productDAO.findById(productId);
      productDAO.fetchImage(product);
      int quantity = Integer.parseInt(req.getParameter("quantity"));
      conn.close();
     
      List<Entity> orders = (List<Entity>) req.getSession().getAttribute("orders");
      if (orders == null) {
        orders = new LinkedList<Entity>();
        req.getSession().setAttribute("orders", orders);
      }
      Entity order = new EntityImpl();
      order.put("product_id", productId);
      order.put("product", product);
      order.put("quantity", quantity);
      addOrMerge(orders, order);
     
      redirect("cart_view", resp);
    } catch (SQLException e) {
      throw new ServletException(e);
    }
  }

  private void addOrMerge(List<Entity> orders, Entity order) {
    for (Entity oldOrder : orders) {
      if (oldOrder.get("product_id").equals(order.get("product_id"))) {
        oldOrder.put("quantity", (Integer) oldOrder.get("quantity")
            + (Integer) order.get("quantity"));
        return;
      }
    }
    orders.add(order);
  }

}
TOP

Related Classes of oss.ngocminh.lego.service.OrderCreateController

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.