/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import DataEntryBean.GovtOrderCreationDetailBean;
import DataEntryBean.GovtOrderCreationExpenseBean;
import DataEntryBean.GovtOrderCreationHeaderBean;
import LoginDb.DbHandler;
import java.lang.reflect.InvocationTargetException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import org.apache.commons.beanutils.BeanUtils;

/**
 *
 * @author 590685
 */
public class GovtOrderCreationServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {

        HttpSession session = request.getSession(false);
        Connection con = null;
        Connection con1 = null;
        Connection con2 = null;
        CallableStatement stmt = null;
        CallableStatement proc = null;
        String message = "";
        String orderId = "";
        String pacsId = (String) session.getAttribute("pacsId");
        String user = (String) session.getAttribute("user");
       // String ServletName = request.getParameter("handle_id");
        //String orderNo = request.getParameter("govtOrderCode");
        //String desc = request.getParameter("descDetails");
        //String startDate = request.getParameter("procStartDate");
        //String endDate = request.getParameter("procEndDate");
        //String commissionRate = request.getParameter("govtCodeDetails");
        GovtOrderCreationHeaderBean oGovtOrderCreationHeaderBeanBean = new GovtOrderCreationHeaderBean();

        ArrayList<GovtOrderCreationDetailBean> alGovtOrderCreationDetailBean = new ArrayList<GovtOrderCreationDetailBean>();
        ArrayList<GovtOrderCreationExpenseBean> alGovtOrderCreationExpenseBean = new ArrayList<GovtOrderCreationExpenseBean>();
        ArrayList<GovtOrderCreationDetailBean> alGovtOrderCreationDetailBeanNew = new ArrayList<GovtOrderCreationDetailBean>();
        ArrayList<GovtOrderCreationDetailBean> alGovtOrderCreationDetailUpdated = new ArrayList<GovtOrderCreationDetailBean>();
        ArrayList<GovtOrderCreationDetailBean> alGovtOrderCreationDetailDeleted = new ArrayList<GovtOrderCreationDetailBean>();


        ArrayList<GovtOrderCreationExpenseBean> alGovtOrderCreationExpenseBeanNew = new ArrayList<GovtOrderCreationExpenseBean>();
        ArrayList<GovtOrderCreationExpenseBean> alGovtOrderCreationExpenseBeanUpdated = new ArrayList<GovtOrderCreationExpenseBean>();
        ArrayList<GovtOrderCreationExpenseBean> alGovtOrderCreationExpenseBeanDeleted = new ArrayList<GovtOrderCreationExpenseBean>();

        try {
           // BeanUtils.populate(oGovtOrderCreationHeaderBeanBean, request.getParameterMap());
        } catch (IllegalAccessException ex) {
           // Logger.getLogger(AccountCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error Occurred during processing.");
        } catch (InvocationTargetException ex) {
           // Logger.getLogger(AccountCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error Occurred during processing.");
        }

        GovtOrderCreationDetailBean oGovtOrderCreationDetailBean = new GovtOrderCreationDetailBean();
        try {
           // BeanUtils.populate(oGovtOrderCreationDetailBean, request.getParameterMap());
        } catch (IllegalAccessException ex) {
           // Logger.getLogger(AccountCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error Occurred during processing.");
        } catch (InvocationTargetException ex) {
           // Logger.getLogger(AccountCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error Occurred during processing.");
        }

        GovtOrderCreationExpenseBean oGovtOrderCreationExpenseBean = new GovtOrderCreationExpenseBean();
        try {
          //  BeanUtils.populate(oGovtOrderCreationExpenseBean, request.getParameterMap());
        } catch (IllegalAccessException ex) {
           // Logger.getLogger(AccountCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error Occurred during processing.");
        } catch (InvocationTargetException ex) {
           // Logger.getLogger(AccountCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
           System.out.println("Error Occurred during processing.");
        }

        if ("Create".equalsIgnoreCase(ServletName)) {

            //START HEADER PART
            try {

                con = DbHandler.getDBConnection();
                try {

                    stmt = con.prepareCall("{ call GPS_Operation.govt_proc_head(?,?,?,?,?,?,?) }");

                } catch (SQLException ex) {
                   // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error Occurred during processing.");
                }

                stmt.setString(1, oGovtOrderCreationHeaderBeanBean.getGovtOrderCodeCreate());
                stmt.setString(2, oGovtOrderCreationHeaderBeanBean.getGovtOrderDesc());
                stmt.setString(3, oGovtOrderCreationHeaderBeanBean.getProcStartDate());
                stmt.setString(4, oGovtOrderCreationHeaderBeanBean.getProcEndDate());
                stmt.setString(5, pacsId);
                stmt.setString(6, oGovtOrderCreationHeaderBeanBean.getGovtCommission());
                stmt.registerOutParameter(7, java.sql.Types.VARCHAR);
                stmt.execute();
                //orderId = stmt.getString(7);
                message = "Order Code Already Exsist";

            } catch (SQLException ex) {
               // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               // System.out.println(ex.toString());
               System.out.println("Error Occurred during processing.");
            } finally {
                try {
                con.close();
                } catch (SQLException e) {
               // System.out.println(e.toString());
                    System.out.println("Error Occurred during processing.");
                }
            }

            //END HEADER PART
            //START DETAIL PART
            if (!orderId.equals("Order Code Already Exsist")) {
                int counter = Integer.parseInt(request.getParameter("rowCounter"));

                for (int i = 1; i <= counter; i++) {
                    try {

                        String item_type = request.getParameter("item_type" + i);
                        String item_subtype = request.getParameter("item_subtype" + i);
                        String item_unit = request.getParameter("item_unit" + i);
                       // String qty = request.getParameter("qty" + i);
                      //  String item_rateperunit = request.getParameter("item_rateperunit" + i);
                      //  String total = request.getParameter("total" + i);
                       // String commodityId = request.getParameter("commodityId" + i);

                        if (commodityId != null) {
                            oGovtOrderCreationDetailBean = new GovtOrderCreationDetailBean();
                            oGovtOrderCreationDetailBean.setCommodityId(commodityId);
                            oGovtOrderCreationDetailBean.setItem_type(item_type);
                            oGovtOrderCreationDetailBean.setItem_subtype(item_subtype);
                            oGovtOrderCreationDetailBean.setItem_unit(item_unit);
                            oGovtOrderCreationDetailBean.setQty(qty);
                            oGovtOrderCreationDetailBean.setItem_rateperunit(item_rateperunit);
                            oGovtOrderCreationDetailBean.setTotal(total);

                            alGovtOrderCreationDetailBean.add(oGovtOrderCreationDetailBean);
                        }
                    } catch (Exception e) {
                        System.out.println("Error Occurred during processing.");
                    }
                }

                if (alGovtOrderCreationDetailBean.size() > 0) {
                    try {
                        con1 = DbHandler.getDBConnection();
                        stmt = con1.prepareCall("{ call GPS_Operation.govt_proc_detail(?,?,?,?,?) }");
                        for (int j = 0; j < alGovtOrderCreationDetailBean.size(); j++) {
                            oGovtOrderCreationDetailBean = alGovtOrderCreationDetailBean.get(j);
                            stmt.setString(1, orderId);
                            stmt.setString(2, oGovtOrderCreationDetailBean.getCommodityId());
                            stmt.setString(3, oGovtOrderCreationDetailBean.getQty());
                            stmt.setString(4, oGovtOrderCreationDetailBean.getItem_rateperunit());
                            stmt.setString(5, oGovtOrderCreationDetailBean.getTotal());
                            stmt.addBatch();

                        }

                        stmt.executeBatch();

                    } catch (SQLException ex) {
                        String delete = "Delete from gps_govt_proc_header where id = '" + orderId + "' ";
                        Connection conn = DbHandler.getDBConnection();
                        PreparedStatement pstmt = conn.prepareCall(delete);
                        pstmt.executeQuery();
                        if (conn != null) {
                           // conn.commit();
                            conn.close();
                        }
                       // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error Occurred during processing.");
                    } finally {
                        try {
                        con1.close();
                        } catch (SQLException e) {
                       // System.out.println(e.toString());
                            System.out.println("Error Occurred during processing.");
                        }
                    }

                }

                // END DETAIL PART
                // START EXPENSE PART
                int counter1 = Integer.parseInt(request.getParameter("rowCounter1"));



                for (int i = 1; i <= counter1; i++) {
                    try {

                       // String expense_head = request.getParameter("expense_head" + i);
                       // String expense_unit = request.getParameter("expense_unit" + i);
                       // String expense_rate_per_unit = request.getParameter("expense_rate_per_unit" + i);

                        oGovtOrderCreationExpenseBean = new GovtOrderCreationExpenseBean();
                        oGovtOrderCreationExpenseBean.setExpense_head(expense_head);
                        oGovtOrderCreationExpenseBean.setExpense_unit(expense_unit);
                        oGovtOrderCreationExpenseBean.setExpense_rate_per_unit(expense_rate_per_unit);

                        alGovtOrderCreationExpenseBean.add(oGovtOrderCreationExpenseBean);

                    } catch (Exception e) {
                        System.out.println("Error occurred during processing.");
                    }
                }

                if (alGovtOrderCreationExpenseBean.size() > 0) {

                    try {
                        con2 = DbHandler.getDBConnection();
                        stmt = con2.prepareCall("{ call GPS_Operation.expense_detail(?,?,?,?) }");
                        for (int j = 0; j < alGovtOrderCreationExpenseBean.size(); j++) {
                            oGovtOrderCreationExpenseBean = alGovtOrderCreationExpenseBean.get(j);
                            stmt.setString(1, orderId);
                            stmt.setString(2, oGovtOrderCreationExpenseBean.getExpense_head());
                            stmt.setString(3, oGovtOrderCreationExpenseBean.getExpense_unit());
                            stmt.setString(4, oGovtOrderCreationExpenseBean.getExpense_rate_per_unit());
                            stmt.addBatch();

                        }
                        stmt.executeBatch();
                        message = "Order Created Successfully. Order Id is " + orderId;
                    } catch (SQLException ex) {
                        String deleteHead = "Delete from gps_govt_proc_header where id = '" + orderId + "' ";
                        String deleteDetail = "Delete from gps_govt_proc_detail where order_id = '" + orderId + "' ";
                        Connection conn = DbHandler.getDBConnection();
                        Connection conn1 = DbHandler.getDBConnection();
                        PreparedStatement pstmt = conn.prepareCall(deleteHead);
                        PreparedStatement pstmt1 = conn1.prepareCall(deleteDetail);
                        pstmt.executeQuery();
                        pstmt1.executeQuery();
                        if (conn != null) {
                           // conn.commit();
                            conn.close();
                        }
                        if (conn1 != null) {
                           // conn1.commit();
                            conn1.close();
                        }
                       // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error Occurred during processing.");
                    } finally {
                        try {
                            stmt.close();
                        } catch (SQLException e) {
                           // System.out.println(e.toString());
                           System.out.println("Error Occurred during stmt close.");
                        }
                        try {
                            con2.close();
                        } catch (SQLException ex) {
                           // con.rollback();
                           // con1.rollback();
                           // con2.rollback();
                           // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                           // System.out.println(ex.toString());
                           System.out.println("Error Occurred during connection close.");
                        }
                    }

                }
            }

            request.setAttribute("message", message);
            request.getRequestDispatcher("/GPS_JSP/GovtOrderCreation.jsp").forward(request, response);

        } else if ("Search".equalsIgnoreCase(ServletName)) {

            try {
              //  BeanUtils.populate(oGovtOrderCreationHeaderBeanBean, request.getParameterMap());
            } catch (IllegalAccessException ex) {
               // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error Occurred during processing.");
            } catch (InvocationTargetException ex) {
               // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error Occurred during processing.");
            }

            Connection connection = null;
            ResultSet resultset = null;
            Statement statement = null;
            connection = DbHandler.getDBConnection();
            int SeachFound = 0;

            try {
                statement = connection.createStatement();
            } catch (SQLException ex) {
               // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error Occurred during processing.");
            }
            try {

               // ResultSet rs = statement.executeQuery("select id,order_code,order_desc,TO_CHAR(proc_start_dt, 'dd/mm/yyyy') as proc_start_dt,TO_CHAR(proc_end_dt,'dd/mm/yyyy') as proc_end_dt,commissionrate from gps_govt_proc_header t where t.id= '" + oGovtOrderCreationHeaderBeanBean.getGovtOrderId() + "' ");

                while (rs.next()) {

                    oGovtOrderCreationHeaderBeanBean.setGovtOrderId(rs.getString("id"));
                    oGovtOrderCreationHeaderBeanBean.setGovtOrderCodeCreate(rs.getString("order_code"));
                    oGovtOrderCreationHeaderBeanBean.setGovtOrderDesc(rs.getString("order_desc"));
                    oGovtOrderCreationHeaderBeanBean.setProcStartDate(rs.getString("PROC_START_DT"));
                    oGovtOrderCreationHeaderBeanBean.setProcEndDate(rs.getString("proc_end_dt"));
                    oGovtOrderCreationHeaderBeanBean.setGovtCommission(rs.getString("commissionrate"));


                    SeachFound = 1;
                    request.setAttribute("displayFlag", "Y");

                }

                statement.close();

            } catch (SQLException ex) {
               // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error Occurred during processing.");
            }

            if (SeachFound == 0) {
                message = "Order not exists in the system";
                request.setAttribute("message", message);
            }

            //For Details Part Populate
            try {
                statement = connection.createStatement();
            } catch (SQLException ex) {
               // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error Occurred during processing.");
            }
            try {

                String query = "select t.order_id,g.TYPE_DESC,g.SUBTYPE_DESC,g.unit,t.rate_unit,t.total,t.QUANTITY_AVAILABLE,g.id,t.detail_id "
                        + " from gps_govt_proc_detail t,gps_commodity_master g"
                        + " where t.commodity_id=g.id"
                        + " and t.order_id= '" + oGovtOrderCreationHeaderBeanBean.getGovtOrderId() + "' ";
              //  ResultSet rs = statement.executeQuery(query);

                while (rs.next()) {

                    oGovtOrderCreationDetailBean = new GovtOrderCreationDetailBean();
                    oGovtOrderCreationDetailBean.setGovtOrderId_Dtl(rs.getString("order_id"));
                    oGovtOrderCreationDetailBean.setItem_type(rs.getString("TYPE_DESC"));
                    oGovtOrderCreationDetailBean.setItem_subtype(rs.getString("SUBTYPE_DESC"));
                    oGovtOrderCreationDetailBean.setItem_unit(rs.getString("unit"));
                    oGovtOrderCreationDetailBean.setItem_rateperunit(rs.getString("rate_unit"));
                    oGovtOrderCreationDetailBean.setTotal(rs.getString("total"));
                    oGovtOrderCreationDetailBean.setQty(rs.getString("QUANTITY_AVAILABLE"));
                    oGovtOrderCreationDetailBean.setCommodityId("id");
                    oGovtOrderCreationDetailBean.setDetailIDAmend(rs.getString("detail_id"));

                    alGovtOrderCreationDetailBean.add(oGovtOrderCreationDetailBean);

                }

                statement.close();


            } catch (SQLException ex) {
               // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error Occurred during processing.");
            }
            //start of expense part
            try {
                statement = connection.createStatement();
            } catch (SQLException ex) {
               // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error Occurred during processing.");
            }
            try {

                String query = "select expense_head,expense_unit,expense_rate,expense_id from order_expense_detail t"
                        + " where t.order_id= '" + oGovtOrderCreationHeaderBeanBean.getGovtOrderId() + "' ";
               // ResultSet rs = statement.executeQuery(query);

                while (rs.next()) {

                    oGovtOrderCreationExpenseBean = new GovtOrderCreationExpenseBean();
                    oGovtOrderCreationExpenseBean.setExpense_head(rs.getString("expense_head"));
                    oGovtOrderCreationExpenseBean.setExpense_unit(rs.getString("expense_unit"));
                    oGovtOrderCreationExpenseBean.setExpense_rate_per_unit(rs.getString("expense_rate"));
                    oGovtOrderCreationExpenseBean.setExpenseIDAmend(rs.getString("expense_id"));



                    alGovtOrderCreationExpenseBean.add(oGovtOrderCreationExpenseBean);

                }

                statement.close();


            } catch (SQLException ex) {
               // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error Occurred during processing.");
            }

            connection.close();

            request.setAttribute("GovtOrderCreationHeaderBeanObj", oGovtOrderCreationHeaderBeanBean);
            request.setAttribute("alGovtOrderCreationDetailBean", alGovtOrderCreationDetailBean);
            request.setAttribute("alGovtOrderCreationExpenseBean", alGovtOrderCreationExpenseBean);

            request.getRequestDispatcher("/GPS_JSP/GovtOrderCreation.jsp").forward(request, response);

        } else if ("Update".equalsIgnoreCase(ServletName)) {
            try {

                con = DbHandler.getDBConnection();
                try {

                    stmt = con.prepareCall("{ call GPS_Operation.upsert_govt_header(?,?,?,?,?,?,?,?) }");

                } catch (SQLException ex) {
                   // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error Occurred during processing.");
                }

                stmt.setString(1, oGovtOrderCreationHeaderBeanBean.getOrderidAmend());
                stmt.setString(2, oGovtOrderCreationHeaderBeanBean.getGovtOrderCodeCreateAmend());
                stmt.setString(3, oGovtOrderCreationHeaderBeanBean.getGovtOrderDescAmend());
                stmt.setString(4, oGovtOrderCreationHeaderBeanBean.getProcStartDateAmend());
                stmt.setString(5, oGovtOrderCreationHeaderBeanBean.getProcEndDateAmend());
                stmt.setString(6, pacsId);
                stmt.setString(7, oGovtOrderCreationHeaderBeanBean.getGovtCommissionAmend());
                stmt.registerOutParameter(8, java.sql.Types.VARCHAR);
                stmt.execute();
               // message = stmt.getString(8);


            } catch (SQLException ex) {
               // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
               // System.out.println(ex.toString());
               System.out.println("Error Occurred during processing.");
            } finally {
                try {
                con.close();
                } catch (SQLException e) {
                    //System.out.println(e.toString());
                    System.out.println("Error Occurred during connection close.");
                }
            }
            //up to this Okay for Header table update
            int add = Integer.parseInt(request.getParameter("add"));
            int counterfor_Detail = Integer.parseInt(request.getParameter("rowCounterAmend"));
            counterfor_Detail = counterfor_Detail + add;

            for (int i = 1; i <= counterfor_Detail; i++) {
                try {

                    String item_descAmend = request.getParameter("item_descAmend" + i);
                    String subtype_descAmend = request.getParameter("subtype_descAmend" + i);
                    String item_unitAmend = request.getParameter("item_unitAmend" + i);
                  //  String qtyAmend = request.getParameter("qtyAmend" + i);
                 //   String item_rateperunitAmend = request.getParameter("item_rateperunitAmend" + i);
                  //  String totalAmend = request.getParameter("totalAmend" + i);
                  //  String commodityIdAmend = request.getParameter("commodityIdAmend" + i);
                    String item_typeAmend = request.getParameter("item_typeAmend" + i);
                    String item_subtypeAmend = request.getParameter("item_subtypeAmend" + i);
                    String rowStatus = request.getParameter("rowStatus" + i);
                   // String detailID = request.getParameter("detailIDAmend" + i);

                    if (item_typeAmend != null && item_subtypeAmend != null && rowStatus != null) {
                        oGovtOrderCreationDetailBean = new GovtOrderCreationDetailBean();
                        oGovtOrderCreationDetailBean.setItem_descAmend(item_descAmend);
                        oGovtOrderCreationDetailBean.setSubtype_descAmend(subtype_descAmend);
                        oGovtOrderCreationDetailBean.setItem_unitAmend(item_unitAmend);
                        oGovtOrderCreationDetailBean.setQtyAmend(qtyAmend);
                        oGovtOrderCreationDetailBean.setItem_rateperunitAmend(item_rateperunitAmend);
                        oGovtOrderCreationDetailBean.setTotalAmend(totalAmend);
                        oGovtOrderCreationDetailBean.setCommodityIdAmend(commodityIdAmend);
                        oGovtOrderCreationDetailBean.setItem_typeAmend(item_typeAmend);
                        oGovtOrderCreationDetailBean.setItem_subtypeAmend(item_subtypeAmend);


                        oGovtOrderCreationDetailBean.setDetailIDAmend(detailID);

                        if (rowStatus.equals("N")) {
                            alGovtOrderCreationDetailBeanNew.add(oGovtOrderCreationDetailBean);
                        } else {
                            alGovtOrderCreationDetailUpdated.add(oGovtOrderCreationDetailBean);
                        }


                    }

                } catch (Exception e) {
                    System.out.println("Error Occurred during processing.");
                }
            }

            //For Deletion

            //String deletedRows = request.getParameter("deletedRows");


            if ((!deletedRows.equalsIgnoreCase(null)) || (!deletedRows.equalsIgnoreCase(""))) {
                StringTokenizer tokenizer = new StringTokenizer(deletedRows, ",");

                while (tokenizer.hasMoreTokens()) {

                    oGovtOrderCreationDetailBean = new GovtOrderCreationDetailBean();
                    oGovtOrderCreationDetailBean.setDetailIDAmend(tokenizer.nextToken());

                    alGovtOrderCreationDetailDeleted.add(oGovtOrderCreationDetailBean);

                }
            }




            if ((alGovtOrderCreationDetailUpdated.size() > 0) && (!message.equalsIgnoreCase(""))) {

                try {
                    con = DbHandler.getDBConnection();
                    try {
                        proc = con.prepareCall("{ call GPS_Operation.Upsert_govt_dtl(?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       System.out.println("Error Occurred during processing.");
                    }


                    for (int j = 0; j < alGovtOrderCreationDetailUpdated.size(); j++) {

                        oGovtOrderCreationDetailBean = alGovtOrderCreationDetailUpdated.get(j);


                        proc.setString(1, oGovtOrderCreationHeaderBeanBean.getOrderidAmend());
                        proc.setString(2, oGovtOrderCreationDetailBean.getDetailIDAmend());
                        proc.setString(3, oGovtOrderCreationDetailBean.getCommodityIdAmend());
                        proc.setString(4, oGovtOrderCreationDetailBean.getQtyAmend());
                        proc.setString(5, oGovtOrderCreationDetailBean.getItem_rateperunitAmend());
                        proc.setString(6, oGovtOrderCreationDetailBean.getTotalAmend());
                        proc.setString(7, ServletName);
                        proc.addBatch();



                    }

                    proc.executeBatch();
                    message = "Govt Order Successfully Updated";

                } catch (SQLException ex) {
                   // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error Occurred during processing.");
                } finally {
                    try {
                        proc.close();
                    } catch (SQLException e) {
                       // System.out.println(e.toString());
                       System.out.println("Error Occurred during proc close.");
                    }
                    try {
                        con.close();
                    } catch (SQLException ex) {
                       // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error Occurred during connection close.");
                    }
                }
            }

            //for deletion

            if ((alGovtOrderCreationDetailDeleted.size() > 0) && (!message.equalsIgnoreCase(""))) {

                try {
                    con = DbHandler.getDBConnection();
                    try {
                        proc = con.prepareCall("{ call GPS_Operation.Upsert_govt_dtl(?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       System.out.println("Error Occurred during processing.");
                    }

                    for (int j = 0; j < alGovtOrderCreationDetailDeleted.size(); j++) {

                        oGovtOrderCreationDetailBean = new GovtOrderCreationDetailBean();

                        oGovtOrderCreationDetailBean = alGovtOrderCreationDetailDeleted.get(j);


                        proc.setString(1, oGovtOrderCreationHeaderBeanBean.getOrderidAmend());
                        proc.setString(2, oGovtOrderCreationDetailBean.getDetailIDAmend());
                        proc.setString(3, oGovtOrderCreationDetailBean.getCommodityIdAmend());
                        proc.setString(4, oGovtOrderCreationDetailBean.getQtyAmend());
                        proc.setString(5, oGovtOrderCreationDetailBean.getItem_rateperunitAmend());
                        proc.setString(6, oGovtOrderCreationDetailBean.getTotalAmend());
                        proc.setString(7, "Delete");
                        proc.addBatch();

                    }

                    proc.executeBatch();

                } catch (SQLException ex) {
                   // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error Occurred during processing.");
                } finally {
                    try {
                        proc.close();
                    } catch (SQLException e) {
                       // System.out.println(e.toString());
                       System.out.println("Error Occurred during proc close.");
                    }
                    try {
                        con.close();
                    } catch (SQLException ex) {
                       // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error Occurred during connection close.");
                    }
                }
            }

            //For New Insertion

            if ((alGovtOrderCreationDetailBeanNew.size() > 0) && (!message.equalsIgnoreCase(""))) {

                try {
                    con = DbHandler.getDBConnection();
                    try {
                        proc = con.prepareCall("{call GPS_Operation.Upsert_govt_dtl(?,?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       System.out.println("Error Occurred during processing.");
                    }


                    for (int j = 0; j < alGovtOrderCreationDetailBeanNew.size(); j++) {

                        oGovtOrderCreationDetailBean = new GovtOrderCreationDetailBean();
                        oGovtOrderCreationDetailBean = alGovtOrderCreationDetailBeanNew.get(j);


                        proc.setString(1, oGovtOrderCreationHeaderBeanBean.getOrderidAmend());
                        proc.setString(2, oGovtOrderCreationDetailBean.getDetailIDAmend());
                        proc.setString(3, oGovtOrderCreationDetailBean.getCommodityIdAmend());
                        proc.setString(4, oGovtOrderCreationDetailBean.getQtyAmend());
                        proc.setString(5, oGovtOrderCreationDetailBean.getItem_rateperunitAmend());
                        proc.setString(6, oGovtOrderCreationDetailBean.getTotalAmend());
                        proc.setString(7, "Create");
                        proc.addBatch();

                    }

                    proc.executeBatch();

                } catch (SQLException ex) {
                   // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error Occurred during processing.");
                } finally {
                    try {
                        proc.close();
                    } catch (SQLException e) {
                       // System.out.println(e.toString());
                       System.out.println("Error Occurred during proc close.");
                    }
                    try {
                        con.close();
                    } catch (SQLException ex) {
                       // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error Occurred during connection close.");
                    }
                }
            }

            //Detail Two portion starts here

            int counterfor_Expense = Integer.parseInt(request.getParameter("rowCounterAmend2"));

            for (int i = 1; i <= counterfor_Expense; i++) {
                try {


                  //  String expense_headAmend = request.getParameter("expense_headAmend" + i);
                   // String expense_unitAmend = request.getParameter("expense_unitAmend" + i);
                  //  String expense_rate_per_unitAmend = request.getParameter("expense_rate_per_unitAmend" + i);
                    String rowStatus_Expn = request.getParameter("rowStatus_Expn" + i);
                   // String ExpenseIDAmend = request.getParameter("ExpenseIDAmend" + i);

                    if (expense_headAmend != null && expense_unitAmend != null && rowStatus_Expn != null) {
                        oGovtOrderCreationExpenseBean = new GovtOrderCreationExpenseBean();

                        oGovtOrderCreationExpenseBean.setExpense_headAmend(expense_headAmend);
                        oGovtOrderCreationExpenseBean.setExpense_unitAmend(expense_unitAmend);
                        oGovtOrderCreationExpenseBean.setExpense_rate_per_unitAmend(expense_rate_per_unitAmend);


                        oGovtOrderCreationExpenseBean.setExpenseIDAmend(ExpenseIDAmend);

                        if (rowStatus_Expn.equals("N")) {
                            alGovtOrderCreationExpenseBeanNew.add(oGovtOrderCreationExpenseBean);
                        } else {
                            alGovtOrderCreationExpenseBeanUpdated.add(oGovtOrderCreationExpenseBean);
                        }

                    }

                } catch (Exception e) {
                    System.out.println("Error occurred during processing.");
                }
            }

            //For Deletion

           // String deletedRows2 = request.getParameter("deletedRows2");

            if ((!deletedRows2.equalsIgnoreCase(null)) || (!deletedRows2.equalsIgnoreCase(""))) {
                StringTokenizer tokenizer2 = new StringTokenizer(deletedRows2, ",");

                while (tokenizer2.hasMoreTokens()) {

                    oGovtOrderCreationExpenseBean = new GovtOrderCreationExpenseBean();
                    oGovtOrderCreationExpenseBean.setExpenseIDAmend(tokenizer2.nextToken());

                    alGovtOrderCreationExpenseBeanDeleted.add(oGovtOrderCreationExpenseBean);

                }
            }

            if ((alGovtOrderCreationExpenseBeanUpdated.size() > 0) && (!message.equalsIgnoreCase(""))) {

                try {
                    con = DbHandler.getDBConnection();
                    try {
                        proc = con.prepareCall("{ call GPS_Operation.Upsert_govt_Expense(?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       System.out.println("Error Occurred during processing.");
                    }


                    for (int j = 0; j < alGovtOrderCreationExpenseBeanUpdated.size(); j++) {

                        oGovtOrderCreationExpenseBean = alGovtOrderCreationExpenseBeanUpdated.get(j);

                        proc.setString(1, oGovtOrderCreationHeaderBeanBean.getOrderidAmend());
                        proc.setString(2, oGovtOrderCreationExpenseBean.getExpenseIDAmend());
                        proc.setString(3, oGovtOrderCreationExpenseBean.getExpense_headAmend());
                        proc.setString(4, oGovtOrderCreationExpenseBean.getExpense_unitAmend());
                        proc.setString(5, oGovtOrderCreationExpenseBean.getExpense_rate_per_unitAmend());

                        proc.setString(6, ServletName);
                        proc.addBatch();

                    }

                    proc.executeBatch();
                    message = "Govt Order Successfully Updated";

                } catch (SQLException ex) {
                   // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error Occurred during processing.");
                } finally {
                    try {
                        proc.close();
                    } catch (SQLException e) {
                       // System.out.println(e.toString());
                       System.out.println("Error Occurred during proc close.");
                    }
                    try {
                        con.close();
                    } catch (SQLException ex) {
                       // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error Occurred during connection close.");
                    }
                }
            }

            //for deletion

            if ((alGovtOrderCreationExpenseBeanDeleted.size() > 0) && (!message.equalsIgnoreCase(""))) {

                try {
                    con = DbHandler.getDBConnection();
                    try {
                        proc = con.prepareCall("{ call GPS_Operation.Upsert_govt_Expense(?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       System.out.println("Error Occurred during processing.");
                    }


                    for (int j = 0; j < alGovtOrderCreationExpenseBeanDeleted.size(); j++) {

                        oGovtOrderCreationDetailBean = new GovtOrderCreationDetailBean();

                        oGovtOrderCreationExpenseBean = alGovtOrderCreationExpenseBeanDeleted.get(j);

                        proc.setString(1, oGovtOrderCreationHeaderBeanBean.getOrderidAmend());
                        proc.setString(2, oGovtOrderCreationExpenseBean.getExpenseIDAmend());
                        proc.setString(3, oGovtOrderCreationExpenseBean.getExpense_headAmend());
                        proc.setString(4, oGovtOrderCreationExpenseBean.getExpense_unitAmend());
                        proc.setString(5, oGovtOrderCreationExpenseBean.getExpense_rate_per_unitAmend());

                        proc.setString(6, "Delete");
                        proc.addBatch();

                    }

                    proc.executeBatch();

                } catch (SQLException ex) {
                   // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error Occurred during processing.");
                } finally {
                    try {
                        proc.close();
                    } catch (SQLException e) {
                       // System.out.println(e.toString());
                       System.out.println("Error Occurred during proc close.");
                    }
                    try {
                        con.close();
                    } catch (SQLException ex) {
                       // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error Occurred during connection close.");
                    }
                }
            }

            //For New Insertion

            if ((alGovtOrderCreationExpenseBeanNew.size() > 0) && (!message.equalsIgnoreCase(""))) {

                try {
                    con = DbHandler.getDBConnection();
                    try {
                        proc = con.prepareCall("{call GPS_Operation.Upsert_govt_Expense(?,?,?,?,?,?) }");
                    } catch (SQLException ex) {
                       // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       System.out.println("Error Occurred during processing.");
                    }

                    for (int j = 0; j < alGovtOrderCreationExpenseBeanNew.size(); j++) {

                        oGovtOrderCreationExpenseBean = new GovtOrderCreationExpenseBean();
                        oGovtOrderCreationExpenseBean = alGovtOrderCreationExpenseBeanNew.get(j);


                        proc.setString(1, oGovtOrderCreationHeaderBeanBean.getOrderidAmend());
                        proc.setString(2, oGovtOrderCreationExpenseBean.getExpenseIDAmend());
                        proc.setString(3, oGovtOrderCreationExpenseBean.getExpense_headAmend());
                        proc.setString(4, oGovtOrderCreationExpenseBean.getExpense_unitAmend());
                        proc.setString(5, oGovtOrderCreationExpenseBean.getExpense_rate_per_unitAmend());

                        proc.setString(6, "Create");
                        proc.addBatch();

                    }

                    proc.executeBatch();

                } catch (SQLException ex) {
                   // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   // System.out.println(ex.toString());
                   System.out.println("Error Occurred during processing.");
                } finally {
                    try {
                        proc.close();
                    } catch (SQLException e) {
                       // System.out.println(e.toString());
                       System.out.println("Error Occurred during proc close.");
                    }
                    try {
                        con.close();
                    } catch (SQLException ex) {
                       // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
                       // System.out.println(ex.toString());
                       System.out.println("Error Occurred during connection close.");
                    }
                }
            }

            //up to this all update delete new insert are okay for detail table 1
            request.setAttribute("message", message);
            request.getRequestDispatcher("/GPS_JSP/GovtOrderCreation.jsp").forward(request, response);

        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);

        } catch (SQLException ex) {
           // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);

        } catch (SQLException ex) {
           // Logger.getLogger(GovtOrderCreationServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
