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

import java.io.PrintWriter;
import DataEntryBean.EnquiryBean;
import DataEntryBean.GLTransactionEnquiryBean;
import DataEntryBean.GlAccountEnquiryBean;
import DataEntryBean.PassbookBean;
import DataEntryBean.TransactionEnquiryBean;
import LoginDb.DbHandler;
import Passbook.PassbookPrinter;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
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 oracle.jdbc.OracleTypes;
import org.apache.commons.beanutils.BeanUtils;

/**
 *
 * @author IPKS
 */
public class PassbookServlet 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 {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet PassbookServlet</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet PassbookServlet at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {
            out.close();
        }
    }

    // <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 {
        processRequest(request, response);
    }

    /** 
     * 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 {

        HttpSession session = request.getSession(false);
        Connection connection = null;
        ResultSet rs = null;
        CallableStatement proc = null;
        int totalCount = 0;
        int gapNoOfLines = 0;
        int gap = 3;
        String message = "";
        String pacsId = (String) session.getAttribute("pacsId");
        String headPacsId = (String) session.getAttribute("headPacsId");
        String pacsName = (String) session.getAttribute("pacsName");
        int date_width = 12;
        int narr_width = 50;
        int dr_width = 15;
        int cr_width = 15;
        int endbal_width = 20;
        int header = 3;
        int prod_width = 0;
        String from_date = "";
        String to_date = "";
        String printType = "";
        String accNo = "";
        String acctSubType="";

        int recordsPerPage = 32;
        int noOfPages = 0;

       // String accType = request.getParameter("accType");
       // String accSubType = request.getParameter("accSubType");
       // String pacsName = request.getParameter("pacsName");

        PassbookBean oPassbookBean = new PassbookBean();
        ArrayList<PassbookBean> alPassbookBean = new ArrayList<PassbookBean>();
        ArrayList<String> arr = new ArrayList<String>();

        int page = 1;
        String reprint = request.getParameter("reprint");
        if (request.getParameter("page") != null
                && !(request.getParameter("page").equals("1")) && !(request.getParameter("page").equals("null"))) {
           // page = Integer.parseInt(request.getParameter("page"));
            if (null != reprint && !(reprint.equals(""))) {
                if (reprint.equals("Y")) {
                    page = page + 1;
                }
            }

        }

        try {
            Properties prop = new Properties();
            String propFileName = "config.properties";
            String absolute = getClass().getProtectionDomain().getCodeSource().getLocation().toExternalForm();
            absolute = absolute.substring(absolute.indexOf("/") + 1, absolute.lastIndexOf("/") + 1);
            System.out.println(absolute);
            absolute = absolute.replace('\\', '/');
            absolute = absolute.concat(propFileName);


            prop.load(new FileInputStream(absolute));

            System.out.println(absolute);
            //throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
            gap = Integer.parseInt(prop.getProperty("GAP"));
            header = Integer.parseInt(prop.getProperty("HEADER"));
            recordsPerPage = Integer.parseInt(prop.getProperty("RECORDSPERPAGE"));
            prod_width = Integer.parseInt(prop.getProperty("PROD_WIDTH"));

            System.out.println("header: " + header);
            System.out.println("gapNoOfLines: " + gapNoOfLines);
            System.out.println("recordsPerPage: " + recordsPerPage);
            System.out.println("PROD_WIDTH: " +prod_width);
            //inputStream.close();

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

        } finally {
              System.out.println("Processing done.");
            }

        int startRow = 0;
        int endRow = 0;
        startRow = (page - 1) * recordsPerPage + 1;
        System.out.println("startROW: " + startRow);
        endRow = page * recordsPerPage;
        System.out.println("endROW: " + endRow);
        int recordCount = 0;
        
        int totalRecordCount = 0;
        //totalRecordCount = Integer.parseInt(request.getParameter("totalRecordCount"));

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

        printType = oPassbookBean.getPrintType();
        accNo = oPassbookBean.getAccNo();

        if (oPassbookBean.getPrintType().equalsIgnoreCase("U")) {
            try {
                connection = DbHandler.getDBConnection();
                try {
                    proc = connection.prepareCall("{ call Passbook.passbookPrint(?,?,?,?,?,?,?,?,?,?,?) }");
                    System.out.println("Calling Procedure");
                } catch (SQLException ex) {
                   // Logger.getLogger(GlProductOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during processing. of Procedure");
                   ex.printStackTrace();
                }

                proc.setString(1, oPassbookBean.getAccNo());
                proc.setString(2, oPassbookBean.getPrintType());
                proc.setString(3, oPassbookBean.getAccType());
                proc.setString(4, pacsId);
                proc.registerOutParameter(5, OracleTypes.CURSOR);
                proc.registerOutParameter(6, OracleTypes.NUMBER);
                proc.registerOutParameter(7, OracleTypes.NUMBER);
                proc.setString(8, oPassbookBean.getFrom_date());
                proc.setString(9, oPassbookBean.getTo_date());
                proc.setInt(10, startRow);
                proc.setInt(11, endRow);
                proc.executeUpdate();

                //rs = (ResultSet) proc.getObject(5);
                totalCount = proc.getInt(7);
                System.out.println("totalcount: " +totalCount);

                gapNoOfLines = totalCount % recordsPerPage;
                System.out.println("gapNoOfLines: " +gapNoOfLines);
                if (gapNoOfLines > (recordsPerPage / 2)) {
                    gapNoOfLines = gapNoOfLines + 3;
                }
                int j = 0;
                gapNoOfLines = gapNoOfLines + header;
                System.out.println("gapNoOfLines after adding header: " + gapNoOfLines);
                for (j = 0; j < gapNoOfLines; j++) {
                    oPassbookBean = new PassbookBean();
                    alPassbookBean.add(oPassbookBean);
                }
                //j = 0;
                while (rs.next()) {

                    if (j == ((recordsPerPage / 2) + header)) {
                        for (int i = 0; i < gap; i++) {
                            oPassbookBean = new PassbookBean();
                            alPassbookBean.add(oPassbookBean);
                        }
                    }
                    oPassbookBean = new PassbookBean();
                    oPassbookBean.setTxn_date(rs.getString("txn_date"));
                    oPassbookBean.setAccNo(accNo);
                    oPassbookBean.setNarration(rs.getString("narration"));
                    if (rs.getString("DR_AMT").equalsIgnoreCase("0")) {
                        oPassbookBean.setDr_amt("");
                    } else {
                        oPassbookBean.setDr_amt(rs.getString("DR_AMT"));
                    }
                    if (rs.getString("CR_AMT").equalsIgnoreCase("0")) {
                        oPassbookBean.setCr_amt("");
                    } else {
                        oPassbookBean.setCr_amt(rs.getString("CR_AMT"));
                    }
                    oPassbookBean.setEnd_bal(rs.getString("end_bal"));
                    oPassbookBean.setCBS_REF_NO(rs.getString("CBS_REF_NO"));

                    j++;
                    alPassbookBean.add(oPassbookBean);
                }

                //recordCount = alPassbookBean.size();


                //request.setAttribute("alPassbookBean", alPassbookBean);
                /*PassbookPrinter oPassbookPrinter = new PassbookPrinter(alPassbookBean);

                if (oPassbookPrinter.successFlag) {
                try {
                proc = connection.prepareCall("{ call Passbook.updTxn(?,?) }");
                } catch (SQLException ex) {
                Logger.getLogger(GlProductOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
                for (int i = 0; i < alPassbookBean.size(); i++) {

                oPassbookBean = alPassbookBean.get(i);
                proc.setString(1, oPassbookBean.getCBS_REF_NO());
                proc.registerOutParameter(2, OracleTypes.VARCHAR);

                proc.executeUpdate();
                }

                message = (String) proc.getObject(2);
                }*/

                String addToPrinter = new String();
                for (int i = 0; i < alPassbookBean.size(); i++) {

                    oPassbookBean = alPassbookBean.get(i);
                    addToPrinter = addToPrinter + padString(blankNull(oPassbookBean.getTxn_date()), date_width);
                    addToPrinter = addToPrinter + padString(blankNull(oPassbookBean.getNarration()), narr_width);
                    addToPrinter = addToPrinter + padString(blankNull(oPassbookBean.getDr_amt()), dr_width);
                    addToPrinter = addToPrinter + padString(blankNull(oPassbookBean.getCr_amt()), cr_width);

                    /*if (!(oPassbookBean.getDr_amt() == null || oPassbookBean.getCr_amt() == null)) {
                    if (!oPassbookBean.getDr_amt().equalsIgnoreCase("0")) {
                    addToPrinter = addToPrinter  + padString(blankNull(oPassbookBean.getDr_amt()),dr_width);
                    } else {
                    addToPrinter = addToPrinter + padString(blankNull(oPassbookBean.getDr_amt()),dr_width);
                    }

                    if (!oPassbookBean.getCr_amt().equalsIgnoreCase("0")) {
                    addToPrinter = addToPrinter + padString(blankNull(oPassbookBean.getCr_amt()),cr_width);
                    } else {
                    addToPrinter = addToPrinter ;
                    }
                    } else {
                    addToPrinter = addToPrinter;
                    }*/
                    addToPrinter = addToPrinter + padString(blankNull(oPassbookBean.getEnd_bal()), endbal_width);
                    addToPrinter = addToPrinter + "\n";
                    arr.add(addToPrinter);

                }

                addToPrinter = addToPrinter.substring(0, addToPrinter.length() - 1);
                /*for(int i=0;i<arr.size();i++){
                String[] tokens = arr.get(i - 1).split(",");
                }*/

                request.setAttribute("addToPrinter", addToPrinter);


                try {
                    proc = connection.prepareCall("{ call Passbook.updTxn(?,?,?) }");
                } catch (SQLException ex) {
                   // Logger.getLogger(GlProductOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during processing.");
                   //ex.printstacktrace();
                }
                for (int i = 0; i < alPassbookBean.size(); i++) {

                    oPassbookBean = alPassbookBean.get(i);
                    proc.setString(1, oPassbookBean.getCBS_REF_NO());
                    proc.setString(2, oPassbookBean.getAccNo());
                    proc.registerOutParameter(3, OracleTypes.VARCHAR);

                    proc.executeUpdate();
                }

                //message = (String) proc.getObject(3);

               // response.setContentLength(addToPrinter.length());
                request.setAttribute("accType", accType);
                request.setAttribute("accSubType", accSubType);
                request.setAttribute("message", message);
                request.setAttribute("accNo", accNo);
                request.setAttribute("accSubType", accSubType);
               request.getRequestDispatcher("/Deposit/PrintPassbook.jsp").forward(request, response);

            } catch (Exception ex) {
               // Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            } finally {
                try {
                    proc.close();
                } catch (SQLException e) {
                    System.out.println("Error occurred during proc close.");
                }
                try {
                    connection.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during coonection close.");
                }
                System.out.println("Processing done.");
            }
        }

        //For First Page
        if (oPassbookBean.getPrintType().equalsIgnoreCase("F")) {
            try {
                connection = DbHandler.getDBConnection();
                try {
                    proc = connection.prepareCall("{ call Passbook.passbookPrint(?,?,?,?,?,?,?,?,?,?,?) }");
                } catch (SQLException ex) {
                   // Logger.getLogger(GlProductOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during processing.");
                }

                proc.setString(1, oPassbookBean.getAccNo());
                proc.setString(2, oPassbookBean.getPrintType());
                proc.setString(3, oPassbookBean.getAccType());
                proc.setString(4, pacsId);
                proc.registerOutParameter(5, OracleTypes.CURSOR);
                proc.registerOutParameter(6, OracleTypes.NUMBER);
                proc.registerOutParameter(7, OracleTypes.NUMBER);
                proc.setString(8, oPassbookBean.getFrom_date());
                proc.setString(9, oPassbookBean.getTo_date());
                proc.setInt(10, startRow);
                proc.setInt(11, endRow);
                proc.executeUpdate();

               // rs = (ResultSet) proc.getObject(5);
                totalCount = proc.getInt(7);
                System.out.println("records per page: " +recordsPerPage);

                int j = 0;
                gapNoOfLines = (recordsPerPage / 2) + header + 4;
                System.out.println("gapNoOfLines after adding header: " + gapNoOfLines);
                for (j = 0; j < gapNoOfLines; j++) {
                    oPassbookBean = new PassbookBean();
                    alPassbookBean.add(oPassbookBean);
                }
                System.out.println(alPassbookBean.size());
                //j = 0;
                while (rs.next()) {

                    oPassbookBean = new PassbookBean();
                    alPassbookBean.add(oPassbookBean);

                    oPassbookBean = new PassbookBean();
                    if (rs.getString("acct_type").equalsIgnoreCase("SB")) {
                        oPassbookBean.setProdName(leftPadString("SAVINGS DEPOSIT", 50));

                    } else if (rs.getString("acct_type").equalsIgnoreCase("RD")) {
                        oPassbookBean.setProdName(leftPadString("RECURRING DEPOSIT", 50));
                    
                    } else if (rs.getString("acct_type").equalsIgnoreCase("CR")) {
                        oPassbookBean.setProdName(leftPadString("CURRENT DEPOSIT", 50));

                    } else if (rs.getString("acct_type").equalsIgnoreCase("SHG")) {
                        oPassbookBean.setProdName(leftPadString("SHG DEPOSIT", 50));
                        
                    } else if (rs.getString("acct_type").equalsIgnoreCase("KCC")) {
                        oPassbookBean.setProdName(leftPadString(rs.getString("prod_name"), 50));

                    } else if (rs.getString("acct_type").equalsIgnoreCase("LOAN")) {
                        oPassbookBean.setProdName(leftPadString(rs.getString("prod_name"), 50));
                    }
                    acctSubType = rs.getString("acct_type");
                    System.out.println(oPassbookBean.getProdName());
                    alPassbookBean.add(oPassbookBean);

                    oPassbookBean = new PassbookBean();
                    alPassbookBean.add(oPassbookBean);

                    oPassbookBean = new PassbookBean();
                    oPassbookBean.setCustName(padString(" Customer Name", 24) + ":" + padString(rs.getString("custName"), 30) + " Society CIF : " + rs.getString("cif_no"));
                     // Added for debugging
                     String customer_account_name=rs.getString("custName");
                    System.out.println("customer account name is:" +customer_account_name);
                    String customer_cif_no=rs.getString("cif_no");
                    System.out.println(customer_cif_no);
                    
                    alPassbookBean.add(oPassbookBean);
                    // Added for debugging
                /*    String customer_account_name=rs.getString("custName");
                    System.out.println("customer account name is:" +customer_account_name);
                    String customer_cif_no=rs.getString("cif_no");
                    System.out.println(cif_no);*/
                    
                    //guardian name and address
                    oPassbookBean = new PassbookBean();
                    oPassbookBean.setGuardian(padString(" Guardian Name", 24) + ":" + padString(blankNA(rs.getString("guardian_name")), 31).substring(0, 30) + "  NOMINEE : " + blankNA(rs.getString("nominee_name")));
                    alPassbookBean.add(oPassbookBean);

                    oPassbookBean = new PassbookBean();
                    oPassbookBean.setAddress(padString(" Address", 24) + ":" + rs.getString("address"));
                    alPassbookBean.add(oPassbookBean);

                    oPassbookBean = new PassbookBean();
                    oPassbookBean.setContact(padString(" Contact Number", 24) + ":" + padString(blankNA(rs.getString("contact")), 30));
                    oPassbookBean.setAccOpenDt(" Account Open Date : " + rs.getString("open_dt"));
                    alPassbookBean.add(oPassbookBean);


                    //added by rajdip 20062018 for secendary holder name
//                    oPassbookBean = new PassbookBean();
//                    oPassbookBean.setSecHolder(padString("Secondary Holder Name",23) + ":" + rs.getString("scnd_custname"));
//                    alPassbookBean.add(oPassbookBean);

                    oPassbookBean = new PassbookBean();
                    //Changed Society Scccount no to Reference No .
                    //By Rajdip 14/05/2018
                    //Changed Society Scccount no to Socitety Reference No .
                    //By Rajdip 29/06/2018
                    oPassbookBean.setAccNo(padString(" Society Reference Number", 24) + ":" + padString(rs.getString("key_1"), 30) + " Mode of Operation : " + rs.getString("mode_of_ops"));
                    alPassbookBean.add(oPassbookBean);
                    oPassbookBean = new PassbookBean();
                    oPassbookBean.setSecHolder(padString(" Other A/C Holders", 24) + ":" + rs.getString("scnd_custname"));
                    alPassbookBean.add(oPassbookBean);
                    //oPassbookBean = new PassbookBean();
                    //alPassbookBean.add(oPassbookBean);
                    /*oPassbookBean = new PassbookBean();
                    oPassbookBean.setLinkAcc("Bank Account Number: " + blankNA(rs.getString("link_accno")));
                    alPassbookBean.add(oPassbookBean);*/
                    oPassbookBean = new PassbookBean();
                    //if (rs.getString("acct_type").equalsIgnoreCase("SB") || rs.getString("acct_type").equalsIgnoreCase("CR") || rs.getString("acct_type").equalsIgnoreCase("SHG"))
                      //  oPassbookBean.setDccbName(" NEFT/RTGS Details:\n" + " Bank Account Number: " + padString(blankNA(rs.getString("link_accno")), 15) + " IFSC: " + rs.getString("ifsc") + "\n Bank Name : THE WEST BENGAL STATE CO-OPERATIVE BANK\n Branch Name : " + rs.getString("dccb_name") + "," + rs.getString("br_name"));
                    if (rs.getString("acct_type").equalsIgnoreCase("RD")) {
                        oPassbookBean.setRdDetails(padString(" Installment Amount",24) + ":" + padString(rs.getString("install_amt"),30) + " Total Installment : " + rs.getString("term_length") + "\n" + padString(" Interest Rate", 24) + ":" + padString(rs.getString("td_intt_rate"),30) + " Maturity Amount   : " + rs.getString("mat_value") + "\n" + padString(" Maturity Date", 24) + ":" + padString(rs.getString("mat_dt"),30));
                    } 
                    else if (rs.getString("acct_type").equalsIgnoreCase("KCC")) {
                        oPassbookBean.setDccbName(padString(" Due Date",24) + ":" + padString(rs.getString("mat_dt"),30) + " Sancation Amount : " + rs.getString("term_length") + "\n" + padString(" Interest Rate", 24) + ":" + padString(rs.getString("td_intt_rate"),30) + " Limit   : " + rs.getString("mat_value"));
                    }
                    else if (rs.getString("acct_type").equalsIgnoreCase("LOAN")) {
                        oPassbookBean.setDccbName(padString(" Due Date",24) + ":" + padString(rs.getString("mat_dt"),30) + " Sancation Amount : " + rs.getString("mat_value") + "\n" + padString(" Interest Rate", 24) + ":" + padString(rs.getString("td_intt_rate"),30) + " EMI   : " + rs.getString("term_length"));
                    }
                    else {
                       // oPassbookBean.setDccbName(" NEFT/RTGS Details:\n" + " Bank Account Number: " + padString(blankNA(rs.getString("link_accno")), 15) + " IFSC: " + rs.getString("ifsc") + "\n Bank Name : THE WEST BENGAL STATE CO-OPERATIVE BANK\n Branch Name : " + rs.getString("dccb_name") + "," + rs.getString("br_name"));
                       oPassbookBean.setDccbName(" NEFT/RTGS Details:\n" + " Bank Account Number: " + padString(blankNA(rs.getString("link_accno")), 15) + " IFSC: " + rs.getString("ifsc") + "\n Bank Name : " + rs.getString("bank_name") +  "\n Branch Name : " + rs.getString("dccb_name") + " " + rs.getString("br_name")); 
                    }
                                            
                    alPassbookBean.add(oPassbookBean);

                }


                String addToPrinter = new String();

                for (int i = 0; i < alPassbookBean.size(); i++) {

                    oPassbookBean = alPassbookBean.get(i);                    
                    addToPrinter = addToPrinter + blankNull(oPassbookBean.getProdName());
                    System.out.println(oPassbookBean.getProdName());
                    addToPrinter = addToPrinter + blankNull(oPassbookBean.getCustName());
                    System.out.println(oPassbookBean.getCustName());
                    addToPrinter = addToPrinter + blankNull(oPassbookBean.getGuardian());
                    System.out.println(oPassbookBean.getGuardian());
                    addToPrinter = addToPrinter + blankNull(oPassbookBean.getAddress());
                    addToPrinter = addToPrinter + blankNull(oPassbookBean.getContact()) + blankNull(oPassbookBean.getAccOpenDt());
                    addToPrinter = addToPrinter + blankNull(oPassbookBean.getAccNo());
                    addToPrinter = addToPrinter + blankNull(oPassbookBean.getSecHolder());

                  
                    if (acctSubType.equalsIgnoreCase("RD")) {
                        addToPrinter = addToPrinter + blankNull(oPassbookBean.getRdDetails());
                    } else {
                        addToPrinter = addToPrinter + blankNull(oPassbookBean.getDccbName());
                    }

                    addToPrinter = addToPrinter + "\n";
                    arr.add(addToPrinter);

                }
                addToPrinter = addToPrinter.substring(0, addToPrinter.length() - 1);
                //response.setContentLength(addToPrinter.length());
                request.setAttribute("accType", accType);
                request.setAttribute("accSubType", accSubType);
                request.setAttribute("accNo", accNo);
                request.setAttribute("printType", printType);
                request.setAttribute("addToPrinter", addToPrinter);
                request.getRequestDispatcher("/Deposit/PrintPassbook.jsp").forward(request, response);

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

        //For Passbook Reprint
        else if (oPassbookBean.getPrintType().equalsIgnoreCase("R")) {
            try {
                connection = DbHandler.getDBConnection();
                try {
                    proc = connection.prepareCall("{ call Passbook.passbookPrint(?,?,?,?,?,?,?,?,?,?,?) }");
                } catch (SQLException ex) {
                   // Logger.getLogger(GlProductOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during processing.");
                   ex.printStackTrace();
                }

                from_date = oPassbookBean.getFrom_date();
                to_date = oPassbookBean.getTo_date();
                proc.setString(1, oPassbookBean.getAccNo());
                proc.setString(2, oPassbookBean.getPrintType());
                proc.setString(3, oPassbookBean.getAccType());
                proc.setString(4, pacsId);
                proc.registerOutParameter(5, OracleTypes.CURSOR);
                proc.registerOutParameter(6, OracleTypes.NUMBER);
                proc.registerOutParameter(7, OracleTypes.NUMBER);
                proc.setString(8, oPassbookBean.getFrom_date());
                proc.setString(9, oPassbookBean.getTo_date());
                proc.setInt(10, startRow);
                proc.setInt(11, endRow);
                proc.executeUpdate();

                //rs = (ResultSet) proc.getObject(5);
                totalCount = proc.getInt(6);

                System.out.println("totalcount:" +totalCount);
                //totalCount = 10;
                noOfPages = ((totalCount % recordsPerPage) == 0) ? ((totalCount / recordsPerPage) + (totalCount % recordsPerPage)) : (totalCount / recordsPerPage);
                noOfPages = noOfPages + 1;
                System.out.println("Total Count:" + totalCount + " No of Pages:" + noOfPages);
                //totalCount = 50;
                noOfPages = ((totalCount % recordsPerPage) == 0) ? ((totalCount / recordsPerPage) + (totalCount % recordsPerPage)) : (totalCount / recordsPerPage);
                noOfPages = noOfPages + 1;
                System.out.println("Total Count:" + totalCount + " No of Pages:" + noOfPages);

                if (page != noOfPages) {
                    reprint = "Y";
                    request.setAttribute("reprint", reprint);
                } else {
                    reprint = "N";
                    request.setAttribute("reprint", reprint);
                }

                int j = 0;
                while (rs.next()) {
                    if (j == 0) {
                        for (int i = 1; i <= 5; i++) {
                            oPassbookBean = new PassbookBean();
                            alPassbookBean.add(oPassbookBean);
                        }

                    }
                    if (j == 16) {
                        for (int i = 1; i <= 3; i++) {
                            oPassbookBean = new PassbookBean();
                            alPassbookBean.add(oPassbookBean);
                        }
                    }
                    oPassbookBean = new PassbookBean();
                    oPassbookBean.setTxn_date(rs.getString("txn_date"));
                    oPassbookBean.setNarration(rs.getString("narration"));
                    oPassbookBean.setDr_amt(rs.getString("DR_AMT"));
                    oPassbookBean.setCr_amt(rs.getString("CR_AMT"));
                    oPassbookBean.setEnd_bal(rs.getString("end_bal"));
                    oPassbookBean.setCBS_REF_NO(rs.getString("CBS_REF_NO"));
                    j++;

                    alPassbookBean.add(oPassbookBean);
                }

                //request.setAttribute("alPassbookBean", alPassbookBean);
                /*PassbookPrinter oPassbookPrinter = new PassbookPrinter(alPassbookBean);

                if (oPassbookPrinter.successFlag) {
                try {
                proc = connection.prepareCall("{ call Passbook.updTxn(?,?) }");
                } catch (SQLException ex) {
                Logger.getLogger(GlProductOperationServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
                for (int i = 0; i < alPassbookBean.size(); i++) {

                oPassbookBean = alPassbookBean.get(i);
                proc.setString(1, oPassbookBean.getCBS_REF_NO());
                proc.registerOutParameter(2, OracleTypes.VARCHAR);

                proc.executeUpdate();
                }

                message = (String) proc.getObject(2);
                }*/

                String addToPrinter = "";
                for (int i = 0; i < alPassbookBean.size(); i++) {

                    oPassbookBean = alPassbookBean.get(i);
                    addToPrinter = addToPrinter + padString(blankNull(oPassbookBean.getTxn_date()), date_width);
                    addToPrinter = addToPrinter + padString(blankNull(oPassbookBean.getNarration()), narr_width);
                    addToPrinter = addToPrinter + padString(blankNull(oPassbookBean.getDr_amt()), dr_width);
                    addToPrinter = addToPrinter + padString(blankNull(oPassbookBean.getCr_amt()), cr_width);
                    addToPrinter = addToPrinter + padString(blankNull(oPassbookBean.getEnd_bal()), endbal_width);
                    addToPrinter = addToPrinter + "\n";
                    arr.add(addToPrinter);

                }

                request.setAttribute("addToPrinter", addToPrinter);
                request.setAttribute("page", page + 1);
                request.setAttribute("accNo", oPassbookBean.getAccNo());
                request.setAttribute("from_date", from_date);
                request.setAttribute("to_date", to_date);
                request.setAttribute("printType", "R");
                request.setAttribute("accType", accType);
                request.setAttribute("accSubType", accSubType);
                request.setAttribute("message", message);
               // request.getRequestDispatcher("/Deposit/PrintPassbook.jsp").forward(request, response);

            } catch (SQLException ex) {
               // Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
               System.out.println("Error occurred during processing.");
            } finally {
                try {
                    proc.close();
                } catch (SQLException e) {
                    System.out.println("Error occurred during proc close.");
                }
                try {
                    connection.close();
                } catch (SQLException ex) {
                   // Logger.getLogger(UploadServlet.class.getName()).log(Level.SEVERE, null, ex);
                   System.out.println("Error occurred during connection close.");
                }
                System.out.println("Processing done.");
            }
            request.getRequestDispatcher("/Deposit/PrintPassbook.jsp").forward(request, response);
        } else
        {
            //No code
        }

      processRequest(request, response);

    }

    public String blankNull(String s) {
        return (s == null) ? "" : s;
    }

    public String blankNA(String s) {
        return (s == null) ? "NA" : s;
    }

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

    public String padString(String s, int padlen) {
        for (int i = s.length(); i <= padlen; i++) {
            s = s + " ";
        }
        return s;
    }

    public String leftPadString(String s, int padlen) {
        for (int i = s.length(); i <= padlen; i++) {
            s = " " + s;
        }
        return s;
    }
}
