Trader ControllerS2C Home « Trader Controller

In this lesson we take our first look at the controller part of the MVC paradigm and code the controller components for the trader.

On initial entry to the trader facilites page, or after extended inactivity, the trader is directed to the Signin Java servlet class for authentication.

After successful authentication the trader facilites page is rendered and after selection of a trader facility the TraderFacilities Java servlet class, acting as a front controller, is used to direct flow to the relevant module.

After control is dispatched to the relevant module via the front controller if the database needs to be accessed to populate the view, or to action user input, then control is passed to the TraderProcessInput Java servlet class which calls the TraderDBAccess Java servlet class with the appropriate parameters for deletion/insertion/modificatiom/retrieval of data.

We also need to email customers who have registered on the site with the latest customer reports when the mass email function has been processed and for this purpose we will create the SendEmails Java servlet class to format our mail before sending it to the EmailUtility utility java class for dispatch to our customers.

Compiling The Signin ClassTop

The Signin class authenticates the traders credentials via a username and password entered via the Trader Sign-in Page - signin.html static html page. This is triggered on initial entry to the trader facilites page, or after extended inactivity and when submitted calls the Signin class to verify authentication.

Cut and paste the following code into your text editor and save it in the   c:\_ServletsJSP_Case_Study\bstrader\src\controller directory as Signin.java.


package controller;
 
import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Signin extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private Connection cn;
    private static final String CONTENT_TYPE = "text/html";
    String queryString = ""; //Used to put SQL statement in

    // Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();

    // Get traders username and password
    String username = request.getParameter("username");
    String password1 = request.getParameter("password1");

    //Constructor sets up connection to the database
    String jdbcDriver = "com.mysql.jdbc.Driver";
    String protocolHeader = "jdbc:mysql://localhost:3306/";
    String dbName = "bootsale";
    String user = "root";
    String password = "root";
    try {
        // Load in the driver
        Class.forName(jdbcDriver);
        System.out.println("...Driver loaded");
        // Get a connection
        cn = DriverManager.getConnection(protocolHeader+dbName, user, password);
        System.out.println("...Connection established");
    }
    catch(Exception ex)
       {System.out.println("Problem opening the database"+ex);}

    try {
        // Create a query
        Statement st = cn.createStatement();
        System.out.println("...Statement created");

        // Create SQL command
        queryString = "SELECT * FROM trader WHERE tradername = '"+username+"'";
        System.out.println(queryString);

        // Put data from query in a result set
        ResultSet rs = st.executeQuery(queryString);

        //Only one row returned no need for looping
        rs.next();
        System.out.println("...Record accessed");

        // Check to see if Password matches
        if (rs.getString("password1").equals(password1)) {
            // Redirect dependant upon match
            System.out.println("...Password Matched");
            String contextPath= "/bstrader/trader_facilities.html";
            response.sendRedirect(response.encodeRedirectURL(contextPath));       }
        else {
           System.out.println("...Password Not Matched");
           String contextPath= "/bstrader/trader_signin.html";
           response.sendRedirect(response.encodeRedirectURL(contextPath));
           rs.close();

        }
    }
    catch(Exception ex)
        {System.out.println("No Username entered"+ex);
        String contextPath= "/bstrader/trader_signin.html";
        response.sendRedirect(response.encodeRedirectURL(contextPath));
    }

    System.out.println("...Terminating");
    // Close database connection
    try {
        cn.close();
        {System.out.println("...Connection closed");}
    }
    catch(Exception ex)
        {System.out.println("Problem closing connection");}
    }

    public String gerServletInfo() {
        return "A servlet that checks username and password against database";
    }
}

Compiling Our Source File With the -cp and -d Options

Open your command line editor:

Change to directory  cd c:\_ServletsJSP_Case_Study\bstrader\src\controller

Compile Signin.java using the java compiler with the -cp and -d options as below, making sure you change apache-tomcat-6.0.37 to wherever you downloaded Tomcat to.

  javac -cp c:\apache-tomcat-6.0.37\lib\servlet-api.jar -d ..\..\classes Signin.java

The following screenshot shows that we get a clean compile and also the Signin class is now compiled into the classes\controller directory.

compile trader Signin

Compiling The TraderFacilities ClassTop

After successful authentication the trader can select a facility via the Trader Facilities Page - trader_facilities.html static html page. On facility selection control is passed to the TraderFacilities Java servlet class, acting as a front controller, which is used to direct flow to the relevant module.

Cut and paste the following code into your text editor and save it in the   c:\_ServletsJSP_Case_Study\bstrader\src\controller directory as TraderFacilities.java.


package controller;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class TraderFacilities extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private static final String CONTENT_TYPE = "text/html";

    // Process the HTTP Get request 
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType(CONTENT_TYPE);
        // Decide which facility button had been pressed
        String label = request.getParameter("Facility");
        if (label != null) {
            if ("ADD a Stock Item".equals(label)) {
                gotoJSPPage("/WEB-INF/jsp/AddSI.jsp", request, response);
            } else if ("MODIFY a Stock Item".equals(label)
                    || "DELETE a Stock Item".equals(label)
                    || "Inventory".equals(label)
                    || "Stock Reorder".equals(label) || "Sales".equals(label)
                    || "Out Of Stock".equals(label)) {
                request.setAttribute("action", "AllSI");
                gotoServlet("/processinput", request, response);
            } else if ("ADD a Location".equals(label)) {
                gotoJSPPage("/WEB-INF/jsp/AddBSLoc.jsp", request, response);
            } else if ("MODIFY a Location".equals(label)
                    || "DELETE a Location".equals(label)
                    || "ADD to Diary".equals(label)) {
                request.setAttribute("action", "AllBSLoc");
                gotoServlet("/processinput", request, response);
            } else if ("MODIFY Diary".equals(label)
                    || "DELETE from Diary".equals(label)) {
                request.setAttribute("action", "AllBSDiary");
                gotoServlet("/processinput", request, response);
            } else if ("Mass Email".equals(label)) {
                request.setAttribute("action", "AllRU");
                request.setAttribute("label", "Mass Email"); 
                gotoServlet("/processinput", request, response);
            } else if ("Customer".equals(label)) {
                request.setAttribute("action", "CustRep");
                gotoServlet("/processinput", request, response);
            }
        } else {
            // First time in after authorisation so output trader facilities
            // html page
            String contextPath = "/bstrader/trader_facilities.html";
            response.sendRedirect(response.encodeRedirectURL(contextPath));
        }
    }

    // Process the HTTP Post request 
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType(CONTENT_TYPE);
        // Decide which trader facility JSP we need to go to from Controller
        String label = request.getParameter("label");
        if (label != null) {
            if ("ModifiedSI".equals(label)) {
                request.setAttribute("action", "ModifySI");
                gotoServlet("/processinput", request, response);
            } else if ("ModifiedBSLoc".equals(label)) {
                request.setAttribute("action", "ModifyBSLoc");
                gotoServlet("/processinput", request, response);
            } else if ("ModifiedBSDiary".equals(label)) {
                request.setAttribute("action", "ModifyBSDiary");
                gotoServlet("/processinput", request, response);
            } else {
                System.out.println("Unknown action! " + label);
            }
        } else {
            label = request.getParameter("Facility");

            if (label != null) {
                if ("ADD a Stock Item".equals(label)) {
                    gotoJSPPage("/WEB-INF/jsp/AddSI.jsp", request, response);
                } else if ("MODIFY a Stock Item".equals(label)) {
                    gotoJSPPage("/WEB-INF/jsp/SelectSI.jsp", request, response);
                } else if ("DELETE a Stock Item".equals(label)) {
                    gotoJSPPage("/WEB-INF/jsp/DeleteSI.jsp", request, response);
                } else if ("ADD a Location".equals(label)) {
                    gotoJSPPage("/WEB-INF/jsp/AddBSLoc.jsp", request, response);
                } else if ("MODIFY a Location".equals(label)) {
                    gotoJSPPage("/WEB-INF/jsp/SelectBSLoc.jsp", request,
                            response);
                } else if ("DELETE a Location".equals(label)) {
                    gotoJSPPage("/WEB-INF/jsp/DeleteBSLoc.jsp", request,
                            response);
                } else if ("ADD to Diary".equals(label)) {
                    gotoJSPPage("/WEB-INF/jsp/AddBSDiary.jsp", request,
                            response);
                } else if ("MODIFY Diary".equals(label)) {
                    gotoJSPPage("/WEB-INF/jsp/SelectBSDiary.jsp", request,
                            response);
                } else if ("DELETE from Diary".equals(label)) {
                    gotoJSPPage("/WEB-INF/jsp/DeleteBSDiary.jsp", request,
                            response);
                } else if ("Mass Email".equals(label)) {
                    gotoJSPPage("/WEB-INF/jsp/MassEmail.jsp", request, response);
                }
            } else {
                label = request.getParameter("action2");

                if ("MODIFIED Stock Item".equals(label)) {
                    gotoJSPPage("/WEB-INF/jsp/ModifySI.jsp", request, response);
                } else if ("MODIFIED Location".equals(label)) {
                    gotoJSPPage("/WEB-INF/jsp/ModifyBSLoc.jsp", request,
                            response);
                } else if ("MODIFIED Diary".equals(label)) {
                    gotoJSPPage("/WEB-INF/jsp/ModifyBSDiary.jsp", request,
                            response);
                }
            }
        }
    }

    // go to requested JSP Trader Facilities page
    public void gotoJSPPage(String pageName, ServletRequest request,
            ServletResponse response) throws ServletException, IOException {
        RequestDispatcher dispatcher = getServletContext()
                .getRequestDispatcher(pageName);
        dispatcher.forward(request, response);
    }

    // go to requested Servlet
    public void gotoServlet(String pageName, HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher dispatcher = getServletContext()
                .getRequestDispatcher(pageName);
        dispatcher.forward(request, response);
    }

    public String gerServletInfo() {
        return "A servlet that checks trader facility button pressed and redirects appropriately";
    }
}

Compiling Our Source File With the -cp and -d Options

Open your command line editor:

Change to directory  cd c:\_ServletsJSP_Case_Study\bstrader\src\controller

Compile TraderFacilities.java using the java compiler with the -cp and -d options as below, making sure you change apache-tomcat-6.0.37 to wherever you downloaded Tomcat to.

  javac -cp c:\apache-tomcat-6.0.37\lib\servlet-api.jar -d ..\..\classes TraderFacilities.java

The following screenshot shows that we get a clean compile and also the TraderFacilities class is now compiled into the classes\controller directory.

compile trader TraderFacilities

Compiling The TraderProcessInput ClassTop

After control is dispatched to the relevant module via the front controller if the database needs to be accessed to populate the view, or to action user input, then control is passed to the TraderProcessInput Java servlet class which calls the TraderDBAccess Java servlet class with the appropriate parameters for deletion/insertion/modificatiom/retrieval of data.

Cut and paste the following code into your text editor and save it in the   c:\_ServletsJSP_Case_Study\bstrader\src\controller directory as TraderProcessInput.java.


package controller;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;
import java.sql.*;
import java.util.regex.PatternSyntaxException;

import model.TraderDBAccess;

public class TraderProcessInput extends HttpServlet {

    private static final long serialVersionUID = 1L;

    // Process the HTTP Get request
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        HttpSession session = request.getSession();

        // Decide which database record to access
        String action = (String) request.getAttribute("action");
        if (action != null) {
            if ("AllSI".equals(action)) {
                processSI(action, session, request, response);
            } else if ("AllBSLoc".equals(action)) {
                processBSLoc(action, session, request, response);
            } else if ("AllBSDiary".equals(action)) {
                processBSDiary(action, session, request, response);
            } else if ("AllRU".equals(action)) {
                processRU(action, session, request, response);
            } else if ("CustRep".equals(action)) {
                processCustRep(action, session, request, response);
            }
        }
    }        

    // Process the HTTP Post request
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        HttpSession session = request.getSession();

        // Decide which database record to update
        String action = request.getParameter("action");
        System.out.println(action);
        if (action != null) {
            if ("AddSI".equals(action) || "SelectSI".equals(action)
                    || "ModifySI".equals(action) || "DeleteSI".equals(action)) {
                processSI(action, request, response);
            } else if ("AddBSLoc".equals(action) || "SelectBSLoc".equals(action)
                    || "ModifyBSLoc".equals(action) || "DeleteBSLoc".equals(action)) {
                processBSLoc(action, request, response);
            } else if ("AddBSDiary".equals(action) || "SelectBSDiary".equals(action)
                    || "ModifyBSDiary".equals(action) || "DeleteBSDiary".equals(action)) {
                updateBSDiary(action, session, request, response);
            }
        }
    }        

    // process stock item action for Get
    public void processSI(String action, HttpSession session, ServletRequest request, ServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();

        // Get all stock item records
        TraderDBAccess tdba = new TraderDBAccess();  
        try {
            tdba.connect();
        } catch(Exception e) {
            System.out.println("Problem opening the database" + e);
            writer.print("<html><head><title>Open Database</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>Database Connection Issue: Problem opening the database</p>" +
                    "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                    "</body></html>");
        }
        try {
            int count = 0;
            String[] stockName = new String[500];
            String[] selectCat = new String[500];
            String[] stockDesc = new String[500];
            int[] stockPrice = new int[500];
            int[] stockLevel = new int[500];
            int[] stockReorderLevel = new int[500];
            int[] stockSoldLastBootsale = new int[500];
            String[] customerName = new String[500];
            String[] feedbackText = new String[500];
            String[] feedbackRating = new String[500];
            ResultSet rs = tdba.getSIFields();
            while(rs.next()) {
                stockName[count] = rs.getString("stockname");
                selectCat[count] = rs.getString("stockitemcategory");
                stockDesc[count] = rs.getString("stockitemdescription");
                stockPrice[count] = rs.getInt("stockprice");
                stockLevel[count] = rs.getInt("stocklevel");
                stockReorderLevel[count] = rs.getInt("stockreorderlevel");
                stockSoldLastBootsale[count] = rs.getInt("stocksoldlastbootsale");
                customerName[count] = rs.getString("customername");
                feedbackText[count] = rs.getString("feedbacktext");
                feedbackRating[count] = rs.getString("feedbackrating");
                count ++;
            }
            session.setAttribute("siStockName", stockName); 
            session.setAttribute("siSelectCat", selectCat); 
            session.setAttribute("siStockDesc", stockDesc); 
            session.setAttribute("siStockPrice", stockPrice); 
            session.setAttribute("siStockLevel", stockLevel); 
            session.setAttribute("siStockReorderLevel", stockReorderLevel); 
            session.setAttribute("siStockSoldLastBootsale", stockSoldLastBootsale); 
            session.setAttribute("siCustomerName", customerName); 
            session.setAttribute("siFeedbackText", feedbackText); 
            session.setAttribute("siFeedbackRating", feedbackRating); 
            session.setAttribute("countsinames", -- count); 
        } catch (SQLException e) {
            writer.print("<html><head><title>Reading BootSale Stock Item Record</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>SQLException: fail reading stockitem database record." +
                    "<p>SQLException was: " + e + "</p>" +
                    "<h3><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></h3>" +
                    "</body></html>");
        }
        try {
            tdba.disconnect();
        } catch(Exception e) {
            System.out.println("Problem closing the database" + e);
            writer.print("<html><head><title>Close Database</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>Database Connection Issue: Problem closing the database</p>" +
                    "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                    "</body></html>");
        }
        String label = request.getParameter("Facility");
        if ("MODIFY a Stock Item".equals(label)) {
            gotoJSPPage("/WEB-INF/jsp/SelectSI.jsp", request, response);
        } else if ("DELETE a Stock Item".equals(label)) {
            gotoJSPPage("/WEB-INF/jsp/DeleteSI.jsp", request, response);
        } else if ("Inventory".equals(label)) {
            gotoJSPPage("/WEB-INF/jsp/InventoryReport.jsp", request, response);
        } else if ("Stock Reorder".equals(label)) {
            gotoJSPPage("/WEB-INF/jsp/StockReorderReport.jsp", request, response);
        } else if ("Sales".equals(label)) {
            gotoJSPPage("/WEB-INF/jsp/SalesReport.jsp", request, response);
        } else if ("Out Of Stock".equals(label)) {
            gotoJSPPage("/WEB-INF/jsp/OutOfStockReport.jsp", request, response);
        }    
    }

    // process boot sale location action for get
    public void processBSLoc(String action, HttpSession session, ServletRequest request, ServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();

        // Get all boot sale location records
        TraderDBAccess tdba = new TraderDBAccess();  
        try {
            tdba.connect();
        } catch(Exception e) {
            System.out.println("Problem opening the database" + e);
            writer.print("<html><head><title>Open Database</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>Database Connection Issue: Problem opening the database</p>" +
                    "<h3><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></h3>" +
                    "</body></html>");
        }
        int count = 0;
        String[] locNames = new String[500];
        String[] locAddr1 = new String[500];
        String[] locAddr2 = new String[500];
        String[] locAddr3 = new String[500];
        String[] locAddr4 = new String[500];
        String[] locPostCode = new String[500];
        try {
            ResultSet rs = tdba.getBSLocFields();

            while(rs.next()) {
               locNames[count] = rs.getString("name");
               locAddr1[count] = rs.getString("address1");
               locAddr2[count] = rs.getString("address2");
               locAddr3[count] = rs.getString("address3");
               locAddr4[count] = rs.getString("address4");
               locPostCode[count] = rs.getString("postcode");
               count ++;
            }
            session.setAttribute("bslocNames", locNames); 
            session.setAttribute("bslocAddr1", locAddr1); 
            session.setAttribute("bslocAddr2", locAddr2); 
            session.setAttribute("bslocAddr3", locAddr3); 
            session.setAttribute("bslocAddr4", locAddr4); 
            session.setAttribute("bslocPostCode", locPostCode); 
            session.setAttribute("countlocnames", -- count); 
        } catch (SQLException e) {
            writer.print("<html><head><title>Reading BootSale Location Record</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>SQLException: fail reading bootsalelocation database record.</p>" +
                    "<p>SQLException was: " + e + "</p>" +
                    "<h3><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></h3>" +
                   "</body></html>");
        }
        try {
            tdba.disconnect();
        } catch(Exception e) {
            System.out.println("Problem closing the database" + e);
            writer.print("<html><head><title>Close Database</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>Database Connection Issue: Problem closing the database</p>" +
                    "<h3><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></h3>" +
                    "</body></html>");
        }
        String label = request.getParameter("Facility");
        if ("MODIFY a Location".equals(label)) {
            gotoJSPPage("/WEB-INF/jsp/SelectBSLoc.jsp", request, response);
        } else if ("DELETE a Location".equals(label)) {
            gotoJSPPage("/WEB-INF/jsp/DeleteBSLoc.jsp", request, response); 
        } else if ("ADD to Diary".equals(label)) {
           gotoJSPPage("/WEB-INF/jsp/AddBSDiary.jsp", request, response);   
        }   
    }

    // process boot sale diary action for Get
    public void processBSDiary(String action, HttpSession session, ServletRequest request, ServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();

        // Get all boot sale diary records
        TraderDBAccess tdba = new TraderDBAccess();  
        try {
            tdba.connect();
        } catch(Exception e) {
            System.out.println("Problem opening the database" + e);
            writer.print("<html><head><title>Open Database</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>Database Connection Issue: Problem opening the database</p>" +
                    "<h3><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></h3>" +
                    "</body></html>");
        }
        try {
            ResultSet rs = tdba.getBSDiaryFields();
            int count;
            count = 0;
            String[] dates = new String[500];
            String[] locNames = new String[500];
            while(rs.next()) {
                String ascDate = rs.getString("date");
                String dateDDMMYYYY = ascDate.substring(8,10) + "/" + ascDate.substring(5,7) + "/" + ascDate.substring(0,4);
                dates[count] = dateDDMMYYYY;
                locNames[count] = rs.getString("name");
                count ++;
            }
            session.setAttribute("bsdDates", dates); 
            session.setAttribute("bsdLocNames", locNames); 
            session.setAttribute("countbsdDates", -- count); 
        } catch (SQLException e) {
            writer.print("<html><head><title>Reading BootSale Diary Record</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>SQLException: fail reading bootsalediary database record.</p>" +
                    "<p>SQLException was: " + e + "</p>" +
                    "<h3><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></h3>" +
                    "</body></html>");
        }
        try {
            tdba.disconnect();
        } catch(Exception e) {
            System.out.println("Problem closing the database" + e);
            writer.print("<html><head><title>Close Database</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>Database Connection Issue: Problem closing the database</p>" +
                    "<h3><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></h3>" +
                    "</body></html>");
        }
        String label = request.getParameter("Facility");
        if ("MODIFY Diary".equals(label)) {
            gotoJSPPage("/WEB-INF/jsp/SelectBSDiary.jsp", request, response);
        } else if ("DELETE from Diary".equals(label)) {
            gotoJSPPage("/WEB-INF/jsp/DeleteBSDiary.jsp", request, response);   
        }    
    }

    // process registered user action for Get
    public void processRU(String action, HttpSession session, ServletRequest request, ServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();

        // Get all registered user records
        TraderDBAccess tdba = new TraderDBAccess();  
        try {
            tdba.connect();
        } catch(Exception e) {
            System.out.println("Problem opening the database" + e);
            writer.print("<html><head><title>Open Database</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>Database Connection Issue: Problem opening the database</p>" +
                    "<h3><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></h3>" +
                    "</body></html>");
        }
        try {
            ResultSet rs = tdba.getRUserFields();
            int count = 0;
            String[] rumail = new String[500];
            while(rs.next()) {
                rumail[count] = rs.getString("email");
                count ++;
            }
            session.setAttribute("ruEmail", rumail); 
            session.setAttribute("countrunames", -- count); 
        } catch (SQLException e) {
            writer.print("<html><head><title>Reading Registered User Record</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>SQLException: fail reading registereduser database record.</p>" +
                    "<p>SQLException was: " + e + "</p>" +
                    "<h3><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></h3>" +
                    "</body></html>");
        }
        try {
            tdba.disconnect();
        } catch(Exception e) {
            System.out.println("Problem closing the database" + e);
            writer.print("<html><head><title>Close Database</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>Database Connection Issue: Problem closing the database</p>" +
                    "<h3><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></h3>" +
                    "</body></html>");
        }
        request.setAttribute("subsequent", "subsequent"); 
        session.setAttribute("subsequent", "subsequent"); 
        gotoJSPPage("/WEB-INF/jsp/MassEmail.jsp", request, response);
    }

    // process customer report action for Get
    public void processCustRep(String action, HttpSession session, ServletRequest request, ServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        
        TraderDBAccess tdba = new TraderDBAccess();  
        try {
            tdba.connect();
        } catch(Exception e) {
            System.out.println("Problem opening the database" + e);
            writer.print("<html><head><title>Open Database</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>Database Connection Issue: Problem opening the database</p>" +
                    "<h3><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></h3>" +
                    "</body></html>");
        }
        int count = 0;
        String[] dates = new String[500];
        String[] locNames = new String[500];
        String[] locAddr1 = new String[500];
        String[] locAddr2 = new String[500];
        String[] locAddr3 = new String[500];
        // Get all boot sale diary records
        try {
            ResultSet rs = tdba.getBSDiaryFields();
            while(rs.next()) {
                String date = rs.getString("Date");
                // Format date to DD/MM/YYYY for display
                String dateDDMMYYYY = date.substring(8,10) + "/" + date.substring(5,7) + "/" + date.substring(0,4);
                dates[count] = dateDDMMYYYY;
                locNames[count] = rs.getString("name");
                ResultSet rs2 = tdba.getBSLocRecord(locNames[count]);
                // Only one row returned no need for looping
                rs2.next();
                locAddr1[count] = rs2.getString("address1")  + ", " + rs2.getString("address2") + ", ";
                String displayData = rs2.getString("address3");
                String displayData2 = rs2.getString("address4");

                if( displayData2.equals("")) {
                } else { 
                  displayData += ", " + displayData2;
                }
                if( displayData.equals("")) {
                    locAddr2[count] = " "; 
                } else { 
                    locAddr2[count] = displayData; 
                }
                locAddr3[count] = rs2.getString("postcode");
                count ++;
            }
            session.setAttribute("bsdDates", dates); 
            session.setAttribute("bsdLocNames", locNames); 
            session.setAttribute("bsdLocAddr1", locAddr1); 
            session.setAttribute("bsdLocAddr2", locAddr2); 
            session.setAttribute("bsdLocAddr3", locAddr3); 
        } catch (SQLException e) {
            writer.print("<html><head><title>Reading BootSale Diary Record</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>SQLException: fail reading bootsalediary database record.</p>" +
                    "<p>SQLException was: " + e + "</p>" +
                    "<h3><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></h3>" +
                    "</body></html>");
        }

        String displayData = "";
        String soldName[] = new String[500];
        String soldCategory[] = new String[500];
        String soldDescription[] = new String[500];
        String soldPrice[] = new String[500];

        String lastInStockName[] = new String[500];
        String lastInStockCategory[] = new String[500];
        String lastInStockDescription[] = new String[500];
        String lastInStockPrice[] = new String[500];

        String name[] = new String[500];
        String category[] = new String[500];
        String description[] = new String[500];
        String price[] = new String[500];

        int count1 = 0;
        int count2 = 0;
        int count3 = 0;

        // Get all stock item records
        try {
            ResultSet rs3 = tdba.getSIFields();
            while(rs3.next()) {
                int stockLevel = rs3.getInt("stocklevel");
                int sold = rs3.getInt("stocksoldlastbootsale");
                // Not interested in out of stock items
                if( stockLevel == 0) {
                } else {
                    // get bestsellers first (ie. sold at last boot sale)
                    if( sold > 0) {
                        soldName[count1] = rs3.getString("stockname");
                        soldCategory[count1] = rs3.getString("stockitemcategory");
                        soldDescription[count1] = rs3.getString("stockitemdescription");
                        int examineNum = rs3.getInt("stockprice");
                        if( examineNum < 10000) {
                            if( examineNum < 1000) {
                                if( examineNum < 100) {
                                    String str = toString(examineNum);
                                    displayData = str + "p";
                                } else {
                                    String str = toString(examineNum);
                                    displayData = str.substring(0,1) + "." + str.substring(1);
                                }    
                            } else {
                                String str = toString(examineNum);
                                displayData = str.substring(0,2) + "." + str.substring(2);
                            }
                        } else {
                            String str = toString(examineNum);
                            displayData = str.substring(0,3) + "." + str.substring(3);
                        }
                        soldPrice[count1] = displayData;
                        count1++;
                    } else {
                        int stockReorderLevel = rs3.getInt("stockreorderlevel");
                        // save last in stock items that were not bestsellers
                        if( stockLevel <= stockReorderLevel) {
                            lastInStockName[count2] = rs3.getString("stockname");
                            lastInStockCategory[count2] = rs3.getString("stockitemcategory");
                            lastInStockDescription[count2] = rs3.getString("stockitemdescription");
                            int examineNum = rs3.getInt("stockprice");
                            if( examineNum < 1000) {
                                if( examineNum < 100) {
                                   String str = toString(examineNum);
                                   displayData = str + "p";
                                } else {
                                   String str = toString(examineNum);
                                   displayData = str.substring(0,1);
                                   displayData += ".";
                                   displayData += str.substring(1);
                                }
                            } else {
                                String str = toString(examineNum);
                                displayData = str.substring(0,2) + "." + str.substring(2);
                            }
                            lastInStockPrice[count2] = displayData;
                            count2++;
                        } else {
                            name[count3] = rs3.getString("stockname");
                            category[count3] = rs3.getString("stockitemcategory");
                            description[count3] = rs3.getString("stockitemdescription");
                            int examineNum = rs3.getInt("stockprice");
                            if( examineNum < 1000) {
                                if( examineNum < 100) {
                                   String str = toString(examineNum);
                                   displayData = str + "p";
                                } else {
                                   String str = toString(examineNum);
                                   displayData = str.substring(0,1);
                                   displayData += ".";
                                   displayData += str.substring(1);
                                }
                            } else {
                                String str = toString(examineNum);
                                displayData = str.substring(0,2) + "." + str.substring(2);
                            }
                            price[count3] = displayData;
                            count3++;
                        }
                    }
                }
            }

            // Store html in a file for use in mass email
            BufferedWriter storeHTML = new BufferedWriter(new FileWriter("C:\\tomcat\\trunk\\webapps\\bstrader\\CustomerReport.html"));
            storeHTML.write("<!DOCTYPE html><html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'><title>Customer Report</title>");
            storeHTML.write("<style type='text/css'>.style1{background-color:orange;border:1px solid black;font-size:medium;}");
            storeHTML.write(".style2{border-style:solid;border-width:1px;}.style3{text-align: center;font-size: large;}");
            storeHTML.write(".style4{font-size: xx-large;}.style5{background-color: orange;font-size: medium;}");
            storeHTML.write(".style6{font-size: medium;}h2 {margin-top:0px;margin-bottom:10px;font-size:x-large;}");
            storeHTML.write("h3{margin-top:0px;margin-bottom:10px;font-size:large;}</style></head>");
            storeHTML.write("<div style='position:absolute;width:800px;height:112px;z-index:1;left:10px;top:9px;' class='style5'>");
            storeHTML.write("<table class='style2'><tr><td><img src='http://localhost:8080/bstrader/images/carboot.jpg' width='150' height='100'></td>");
            storeHTML.write("<td style='width:800px;height:90px' class='style3'><span class='style4'>Kevin's Boot Sales</span>");
            storeHTML.write("<br><br><em>'Everything You Need From The Boot of a Car'</em></td></tr></table></div>");
            storeHTML.write("<div style='position: absolute; width: 621px; height: 673px; z-index: 2; left: 13px; top: 128px'>");
            storeHTML.write("<h2>Contact Information:</h2><h3>Contact us by email at alf@jsptutor.co.uk</h3>");
            storeHTML.write("<h3>Visit Our Website: <a href='/bstrader/home.html'>Kevin's Boot Sales</a></h3>");
            storeHTML.write("<p><strong><h2>Our Diary:</h2></strong></p><table border='2'>");
            storeHTML.write("<tr><td><b>Date:</b></td><td><b>Boot Sale Name:</b></td><td><b>Boot Sale Address:</b></td></tr>");

            for (int i=0;i<count;i++) {
                storeHTML.write("<tr><td valign='top' rowspan='3' style='width: 110px' valign='top'>" + dates[i] + "</td>");
                storeHTML.write("<td valign='top' rowspan='3' style='width: 200px' valign='top'>" + locNames[i] + "</td>");
                storeHTML.write("<td style='width: 300px' valign='top'>" + locAddr1[i] + "</td></tr>");
                storeHTML.write("<tr><td style='width: 300px' valign='top'>" + locAddr2[i] + "</td></tr>");
                storeHTML.write("<tr><td style='width: 300px' valign='top'>" + locAddr3[i] + "</td></td></tr>");
            }
            storeHTML.write("</table><p><strong><h2>Best Sellers:</h2></strong></p><table border='2'><tr><td><b>Stock Item Name:</b></td>");
            storeHTML.write("<td><b>Stock Category:</b></td><td><b>Stock Descripton:</b></td><td><b>Price:</b></td></tr>");
            
            for (int i=0;i<count1;i++) {
                storeHTML.write("<tr><td style='width: 200px' valign='top'>" + soldName[i] + "</td>");
                storeHTML.write("<td style='width: 160px' valign='top'>" + soldCategory[i] + "</td>");
                storeHTML.write("<td style='width: 160px' valign='top'>" + soldDescription[i] + "</td>");
                storeHTML.write("<td style='width: 80px' valign='top'>" + soldPrice[i] + "</td></tr>");
            }
            storeHTML.write("</table><p><strong><h2>Last Few remaining:</h2></strong></p><table border='2'><tr><td><b>Stock Item Name:</b></td>");
            storeHTML.write("<td><b>Stock Category:</b></td><td><b>Stock Descripton:</b></td><td><b>Price:</b></td></tr>");
            
            for (int i=0;i<count2;i++) {
                storeHTML.write("<tr><td style='width: 200px' valign='top'>" + lastInStockName[i] + "</td>");
                storeHTML.write("<td style='width: 160px' valign='top'>" + lastInStockCategory[i] + "</td>");
                storeHTML.write("<td style='width: 160px' valign='top'>" + lastInStockDescription[i] + "</td>");
                storeHTML.write("<td style='width: 80px' valign='top'>" + lastInStockPrice[i] + "</td></tr>");
            }
            storeHTML.write("</table><p><strong><h2>Other Products:</h2></strong></p><table border='2'><tr><td><b>Stock Item Name:</b></td>");
            storeHTML.write("<td><b>Stock Category:</b></td><td><b>Stock Descripton:</b></td><td><b>Price:</b></td></tr>");
            
            for (int i=0;i<count3;i++) {
                storeHTML.write("<tr><td style='width: 200px' valign='top'>" + name[i] + "</td>");
                storeHTML.write("<td style='width: 160px' valign='top'>" + category[i] + "</td>");
                storeHTML.write("<td style='width: 160px' valign='top'>" + description[i] + "</td>");
                storeHTML.write("<td style='width: 80px' valign='top'>" + price[i] + "</td></tr>");
            }
            storeHTML.write("</table></form></div></body></html>");
            storeHTML.close();

            session.setAttribute("siSoldName", soldName); 
            session.setAttribute("siSoldCategory", soldCategory); 
            session.setAttribute("siSoldDescription", soldDescription); 
            session.setAttribute("siSoldPrice", soldPrice); 
            session.setAttribute("siLastInStockName", lastInStockName); 
            session.setAttribute("siLastInStockCategory", lastInStockCategory); 
            session.setAttribute("siLastInStockDescription", lastInStockDescription); 
            session.setAttribute("siLastInStockPrice", lastInStockPrice); 
            session.setAttribute("siOPName", name); 
            session.setAttribute("siOPCategory", category); 
            session.setAttribute("siOPDescription", description); 
            session.setAttribute("siOPPrice", price); 
            session.setAttribute("countbsdDates", -- count); 
            session.setAttribute("countbestsellers", -- count1); 
            session.setAttribute("countlastinstock", -- count2); 
            session.setAttribute("countother", -- count3); 
        } catch (SQLException e) {
            writer.print("<html><head><title>Reading BootSale Stock Item Record</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>SQLException: fail reading stockitem database record.</p>" +
                    "<p>SQLException was: " + e + "</p>" +
                    "<h3><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></h3>" +
                    "</body></html>");
        }
        try {
            tdba.disconnect();
        } catch(Exception e) {
            System.out.println("Problem closing the database" + e);
            writer.print("<html><head><title>Close Database</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>Database Connection Issue: Problem closing the database</p>" + e +
                    "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                    "</body></html>");
        }
        gotoJSPPage("/WEB-INF/jsp/CustomerReport.jsp", request, response);
    }

    // process stock item action for Post
    public void processSI(String action, ServletRequest request, ServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();

        TraderDBAccess tdba = new TraderDBAccess();  
        try {
            tdba.connect();
        } catch(Exception e) {
            System.out.println("Problem opening the database" + e);
            writer.print("<html><head><title>Open Database</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>Database Connection Issue: Problem opening the database</p>" +
                    "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                    "</body></html>");
        }
        if ("AddSI".equals(action)) {
            String stockName = request.getParameter("stockName");
            String selectCat = request.getParameter("selectCat");
            String stockDesc = request.getParameter("stockDesc");
            String stockPrice = request.getParameter("stockPrice");
            String stockLevel = request.getParameter("stockLevel");
            String stockReorderLevel = request.getParameter("stockReorderLevel");
            String displayData = request.getParameter("displayData");
            try {
                tdba.addSI(stockName, selectCat, stockDesc, stockPrice, stockLevel, stockReorderLevel);
                writer.print("<html><head><title>BootSale Stock Item Record Added</title></head>" + 
                        "<body><h3>This record added to the stockitem database table</h3>" +
                        displayData + "<p></p>" +
                        "<p><a href='/bstrader/traderfacilities?Facility=ADD+a+Stock+Item'>" +
                        "Return to Add Stock Item Page</a></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            } catch (SQLException e) {
                request.setAttribute("action", "AddSI"); 
                request.setAttribute("label", "ADD a Stock Item"); 
                writer.print("<html><head><title>BootSale Stock Item Record Added</title></head>" + 
                        "<body><h3>Error Report</h3>" +
                        "<p>SQLException: add failed for stock item name: " + stockName + "</p>" +
                        "<p>SQLException was: " + e + "</p>" +
                        "<p><a href='/bstrader/traderfacilities?Facility=ADD+a+Stock+Item'>" +
                        "Return to Add Stock Item Page</a></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            }
        } else if ("SelectSI".equals(action)) {
            String stockitemname = request.getParameter("stockitemname");
            try {
                ResultSet rs = tdba.getSIRecord(stockitemname);
                while(rs.next()) {
                    request.setAttribute("stockName", rs.getString("stockname")); 
                    request.setAttribute("selectCat", rs.getString("stockitemcategory")); 
                    request.setAttribute("stockDesc", rs.getString("stockitemdescription")); 
                    request.setAttribute("stockPrice", rs.getString("stockprice")); 
                    request.setAttribute("stockLevel", rs.getString("stocklevel")); 
                    request.setAttribute("stockReorderLevel", rs.getString("stockreorderlevel")); 
                    request.setAttribute("stockSoldLastBootsale", rs.getString("stocksoldlastbootsale")); 
                    request.setAttribute("customerName", rs.getString("customername")); 
                    request.setAttribute("feedbackText", rs.getString("feedbacktext")); 
                    request.setAttribute("feedbackRating", rs.getString("feedbackrating")); 
                    request.setAttribute("first", "firsttimein"); 
                }
                gotoJSPPage("/WEB-INF/jsp/ModifySI.jsp", request, response);
            } catch (SQLException e) {
                request.setAttribute("action", "SelectSI"); 
                request.setAttribute("label", "MODIFY a Stock Item"); 
                writer.print("<html><head><title>Get Stock Item Record</title></head>" + 
                        "<body><h3>Error Report</h3>" +
                        "<p>SQLException: get failed for stock item name: " + stockitemname + "</p>" +
                        "<p>SQLException was: " + e + "</p>" +
                        "<p><a href='/bstrader/traderfacilities?Facility=MODIFY+a+Stock+Item'>" +
                        "Return to Select Stock Item Page</a></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            }
        } else if ("ModifySI".equals(action)) {
            String stockName = request.getParameter("stockName");
            String selectCat = request.getParameter("selectCat");
            String stockDesc = request.getParameter("stockDesc");
            String stockPrice = request.getParameter("stockPrice");
            String stockLevel = request.getParameter("stockLevel");
            String stockReorderLevel = request.getParameter("stockReorderLevel");
            String stockSoldLastBootsale = request.getParameter("stockSoldLastBootsale");
            String customerName = request.getParameter("customerName");
            String feedbackText = request.getParameter("feedbackText");
            String feedbackRating = request.getParameter("feedbackRating");
            String displayData = request.getParameter("displayData");
            try {
                tdba.modifySI(stockName, selectCat, stockDesc, stockPrice, stockLevel, stockReorderLevel, 
                        stockSoldLastBootsale, customerName, feedbackText, feedbackRating);
                writer.print("<html><head><title>Stock Item Record Modified</title></head>" + 
                        "<body><h3>This record modified in the stockitem database table</h3>" +
                        displayData + "<p></p>" +
                        "<p><a href='/bstrader/traderfacilities?Facility=MODIFY+a+Stock+Item'>" +
                        "Return to Select Stock Item Page</a></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            } catch (SQLException e) {
                request.setAttribute("action", "SelectSI"); 
                request.setAttribute("label", "Select a Stock Item"); 
                writer.print("<html><head><title>Stock Item Record Modified</title></head>" + 
                        "<body><h3>Error Report</h3>" +
                        "<p>SQLException: modify failed for stock item name: " + stockName + "</p>" +
                        "<p>SQLException was: " + e + "</p>" +
                        "<p><a href='/bstrader/traderfacilities?Facility=MODIFY+a+Stock+Item'>" +
                        "Return to Select Stock Item Page</a></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            }
        } else if ("DeleteSI".equals(action)) {
            String commaSeparated = request.getParameter("name");
            String[] splitArray = new String[500];
            try {
                splitArray = commaSeparated.split(",");
            } catch (PatternSyntaxException ex) {
                // 
            }
            try {
                tdba.deleteSI(splitArray);
                writer.print("<html><head><title>Stock Item Record Records Deleted</title></head>" + 
                        "<body><h3>Records deleted from the stockitem database table</h3>" +
                        request.getParameter("name") + "<p></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            } catch (SQLException e) {
                writer.print("<html><head><title>Delete Stock Item Record</title></head>" + 
                        "<body><h3>Error Report</h3>" +
                        "<p>SQLException: get failed for stock item name: " + request.getParameter("name") + "</p>" +
                        "<p>SQLException was: " + e + "</p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            }
        }
        try {
            tdba.disconnect();
        } catch(Exception e) {
            System.out.println("Problem closing the database" + e);
            writer.print("<html><head><title>Close Database</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>Database Connection Issue: Problem closing the database</p>" +
                    "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                    "</body></html>");
        }
    }

    // process bootsale location action for Post
    public void processBSLoc(String action, ServletRequest request, ServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();

        TraderDBAccess tdba = new TraderDBAccess();  
        try {
            tdba.connect();
        } catch(Exception e) {
            System.out.println("Problem opening the database" + e);
            writer.print("<html><head><title>Open Database</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>Database Connection Issue: Problem opening the database</p>" + e +
                    "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                    "</body></html>");
        }
        if ("AddBSLoc".equals(action)) {
            String name = request.getParameter("name");
            String addr1 = request.getParameter("addr1");
            String addr2 = request.getParameter("addr2");
            String addr3 = request.getParameter("addr3");
            String addr4 = request.getParameter("addr4");
            String postCode = request.getParameter("postCode");
            String displayData = request.getParameter("displayData");
            try {
                tdba.addBSLoc(name, addr1, addr2, addr3, addr4, postCode);
                writer.print("<html><head><title>BootSale Location Record Added</title></head>" + 
                        "<body><h3>This record added to the bootsalelocation database table</h3>" +
                        displayData + "<p></p>" +
                        "<p><a href='/bstrader/traderfacilities?Facility=ADD+a+Location'>" +
                        "Return to Add BootSale Location Page</a></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            } catch (SQLException e) {
                request.setAttribute("action", "AddBSLoc"); 
                request.setAttribute("label", "ADD a Location"); 
                writer.print("<html><head><title>BootSale Location Record Added</title></head>" + 
                        "<body><h3>Error Report</h3>" +
                        "<p>SQLException: add failed for boot sale name: " + name + "</p>" +
                        "<p>SQLException was: " + e + "</p>" +
                        "<p><a href='/bstrader/traderfacilities?Facility=ADD+a+Location'>" +
                        "Return to Add BootSale Location Page</a></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            }
        } else if ("SelectBSLoc".equals(action)) {
            String name = request.getParameter("name");
            try {
                ResultSet rs = tdba.getBSLocRecord(name);
                while(rs.next()) {
                    request.setAttribute("name", rs.getString("name")); 
                    request.setAttribute("addr1", rs.getString("address1")); 
                    request.setAttribute("addr2", rs.getString("address2")); 
                    request.setAttribute("addr3", rs.getString("address3")); 
                    request.setAttribute("addr4", rs.getString("address4")); 
                    request.setAttribute("postCode", rs.getString("postcode")); 
                    request.setAttribute("first", "firsttimein"); 
                }
                gotoJSPPage("/WEB-INF/jsp/ModifyBSLoc.jsp", request, response);
            } catch (SQLException e) {
                request.setAttribute("action", "ModifyBSLoc"); 
                request.setAttribute("label", "MODIFY a Location"); 
                writer.print("<html><head><title>Get BootSale Location Record</title></head>" + 
                        "<body><h3>Error Report</h3>" +
                        "<p>SQLException: get failed for boot sale name: " + name + "</p>" +
                        "<p>SQLException was: " + e + "</p>" +
                        "<p><a href='/bstrader/traderfacilities?Facility=MODIFY+a+Location'>" +
                        "Return to Select BootSale Location Page</a></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            }
        } else if ("ModifyBSLoc".equals(action)) {
            String name = request.getParameter("name");
            String addr1 = request.getParameter("addr1");
            String addr2 = request.getParameter("addr2");
            String addr3 = request.getParameter("addr3");
            String addr4 = request.getParameter("addr4");
            String postCode = request.getParameter("postCode");
            String displayData = request.getParameter("displayData");

            try {
                tdba.modifyBSLoc(name, addr1, addr2, addr3, addr4, postCode);
                writer.print("<html><head><title>BootSale Location Record Modified</title></head>" + 
                        "<body><h3>This record modified in the bootsalelocation database table</h3>" +
                        displayData + "<p></p>" +
                        "<p><a href='/bstrader/traderfacilities?Facility=MODIFY+a+Location'>" +
                        "Return to Select BootSale Location Page</a></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            } catch (SQLException e) {
                request.setAttribute("action", "SelectBSLoc"); 
                request.setAttribute("label", "MODIFY a Location"); 
                writer.print("<html><head><title>BootSale Location Record Modified</title></head>" + 
                        "<body><h3>Error Report</h3>" +
                        "<p>SQLException: modify failed for boot sale name: : " + name + "</p>" +
                        "<p>SQLException was: " + e + "</p>" +
                        "<p><a href='/bstrader/traderfacilities?Facility=MODIFY+a+Location'>" +
                        "Return to Select BootSale Location Page</a></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            }
        } else if ("DeleteBSLoc".equals(action)) {
            String commaSeparated = request.getParameter("name");
            String[] splitArray = new String[500];
            try {
                splitArray = commaSeparated.split(",");
            } catch (PatternSyntaxException ex) {
                // 
            }
            try {
                tdba.deleteBSLoc(splitArray);
                writer.print("<html><head><title>BootSale Location Records Deleted</title></head>" + 
                        "<body><h3>Records deleted from the bootsalelocation database table</h3>" +
                        request.getParameter("name") + "<p></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            } catch (SQLException e) {
                writer.print("<html><head><title>Delete BootSale Location Record</title></head>" + 
                        "<body><h3>Error Report</h3>" +
                        "<p>SQLException: get failed for boot sale name: " + request.getParameter("name") + "</p>" +
                        "<p>SQLException was: " + e + "</p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            }
        }
        try {
            tdba.disconnect();
        } catch(Exception e) {
            System.out.println("Problem closing the database" + e);
            writer.print("<html><head><title>Close Database</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>Database Connection Issue: Problem closing the database</p>" +
                    "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                    "</body></html>");
        }
    }

    // process boot sale diary action for Post
    public void updateBSDiary(String action, HttpSession session, ServletRequest request, ServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();

        TraderDBAccess tdba = new TraderDBAccess();  
        try {
            tdba.connect();
        } catch(Exception e) {
            System.out.println("Problem opening the database" + e);
            writer.print("<html><head><title>Open Database</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>Database Connection Issue: Problem opening the database</p>" +
                    "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                    "</body></html>");
        }
        if ("AddBSDiary".equals(action)) {
            String date = request.getParameter("date");
            String dateYYYYMMDD = date.substring(6,10) + "/" + date.substring(3,5) + "/" + date.substring(0,2);
            String name = request.getParameter("name");
            String displayData = request.getParameter("displayData");
            try {
                tdba.addBSDiary(dateYYYYMMDD, name);
                writer.print("<html><head><title>BootSale Diary Added</title></head>" + 
                        "<body><h3>This record added to the bootsalediary database table</h3>" +
                        displayData + "<p></p>" +
                        "<p><a href='/bstrader/traderfacilities?Facility=ADD+to+Diary'>" +
                        "Return to Add Boot Sale Diary Page</a></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            } catch (SQLException e) {
                request.setAttribute("action", "AddBSDiary"); 
                request.setAttribute("label", "ADD to Diary"); 
                writer.print("<html><head><title>BootSale Dairy Record Added</title></head>" + 
                        "<body><h3>Error Report</h3>" +
                        "<p>SQLException: add failed for date: " + date + "</p>" +
                        "<p>SQLException was: " + e + "</p>" +
                        "<p><a href='/bstrader/traderfacilities?Facility=ADD+to+Diary'>" +
                        "Return to Add Boot Sale Diary Page</a></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            }
        } else if ("SelectBSDiary".equals(action)) {
            String date = request.getParameter("date");
            String dateYYYYMMDD = date.substring(6,10) + "/" + date.substring(3,5) + "/" + date.substring(0,2);
            try {
                ResultSet rs = tdba.getBSDiaryRecord(dateYYYYMMDD);
                while(rs.next()) {
                    String ascDate = rs.getString("date");
                    String dateDDMMYYYY = ascDate.substring(8,10) + "/" + ascDate.substring(5,7) + "/" + ascDate.substring(0,4);
                    request.setAttribute("date", dateDDMMYYYY); 
                }
            } catch (SQLException e) {
                request.setAttribute("action", "SelectBSDiary"); 
                request.setAttribute("label", "MODIFY Diary"); 
                writer.print("<html><head><title>Get BootSale Diary Record</title></head>" + 
                        "<body><h3>Error Report</h3>" +
                        "<p>SQLException: get failed for date: " + date + "</p>" +
                        "<p>SQLException was: " + e + "</p>" +
                        "<p><a href='/bstrader/traderfacilities?Facility=MODIFY+Diary'>" +
                        "Return to Select Boot Sale Diary Page</a></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            }
            int count = 0;
            String[] locNames = new String[500];
            try {
                ResultSet rs = tdba.getBSLocFields();
                while(rs.next()) {
                   locNames[count] = rs.getString("name");
                   count ++;
                }
                request.setAttribute("first", "firsttimein"); 
                session.setAttribute("bslocNames", locNames); 
                session.setAttribute("countlocnames", -- count); 
                gotoJSPPage("/WEB-INF/jsp/ModifyBSDiary.jsp", request, response);
            } catch (SQLException e) {
                writer.print("<html><head><title>Reading BootSale Location Record</title></head>" + 
                        "<body><h3>Error Report</h3>" +
                        "<p>SQLException: fail reading bootsalelocation database record.</p>" +
                        "<p>SQLException was: " + e + "</p>" +
                        "<h3><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></h3>" +
                       "</body></html>");
            }
        } else if ("ModifyBSDiary".equals(action)) {
            String date = request.getParameter("date");
            String dateYYYYMMDD = date.substring(6,10) + "/" + date.substring(3,5) + "/" + date.substring(0,2);
            String name = request.getParameter("name");
            String displayData = request.getParameter("displayData");
            try {
                tdba.modifyBSDiary(dateYYYYMMDD, name);
                writer.print("<html><head><title>BootSale Diary Record Modified</title></head>" + 
                        "<body><h3>This record modified in the bootsalediary database table</h3>" +
                        displayData + "<p></p>" +
                        "<p><a href='/bstrader/traderfacilities?Facility=MODIFY+Diary'>" +
                        "Return to Select Boot Sale Diary Page</a></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            } catch (SQLException e) {
                request.setAttribute("action", "ModifyBSDiary"); 
                request.setAttribute("label", "MODIFY Diary"); 
                writer.print("<html><head><title>BootSale Diary Record Modified</title></head>" + 
                        "<body><h3>Error Report</h3>" +
                        "<p>SQLException: modify failed for date: " + date + "</p>" +
                        "<p>SQLException was: " + e + "</p>" +
                        "<p><a href='/WEB-INF/jsp/ModifyBSDiary.jsp'>Return to Modify Boot Sale Diary Page</a></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            }
        } else if ("DeleteBSDiary".equals(action)) {
            String commaSeparated = request.getParameter("date");
            String[] splitArray = new String[500];
            try {
                splitArray = commaSeparated.split(",");
            } catch (PatternSyntaxException ex) {
                System.out.println("PatternSyntaxException:" + ex);
            }
            try {
                tdba.deleteBSDiary(splitArray);
                writer.print("<html><head><title>BootSale Diary Records Deleted</title></head>" + 
                        "<body><h3>Records deleted from the bootsalediary database table</h3>" +
                        request.getParameter("date") + "<p></p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            } catch (SQLException e) {
                writer.print("<html><head><title>Delete BootSale Diary Record</title></head>" + 
                        "<body><h3>Error Report</h3>" +
                        "<p>SQLException: get failed for date: " + request.getParameter("date") + "</p>" +
                        "<p>SQLException was: " + e + "</p>" +
                        "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                        "</body></html>");
            }
        }
        try {
            tdba.disconnect();
        } catch(Exception e) {
            System.out.println("Problem closing the database" + e);
            writer.print("<html><head><title>Close Database</title></head>" + 
                    "<body><h3>Error Report</h3>" +
                    "<p>Database Connection Issue: Problem closing the database</p>" +
                    "<p><a href='/bstrader/trader_facilities.html'>Return to Trader Facilities Page</a></p>" +
                    "</body></html>");
        }
    }
    
    public String toString(int number) {
        return ("" + number);
    }

    // go to requested JSP facilities page
    public void gotoJSPPage(String pageName, ServletRequest request, ServletResponse response)
            throws ServletException, IOException {
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(pageName);
        dispatcher.forward(request, response);
    }

    public String gerServletInfo() {
        return "A servlet that checks trader facility button pressed and redirects appropriately";
    }

}

Compiling Our Source File With the -cp and -d Options

Open your command line editor:

Change to directory  cd c:\_ServletsJSP_Case_Study\bstrader\src\controller

Compile TraderProcessInput.java using the java compiler with the -cp and -d options as below, making sure you change apache-tomcat-6.0.37 to wherever you downloaded Tomcat to.

  javac -cp c:\apache-tomcat-6.0.37\lib\servlet-api.jar;..\..\classes -d ..\..\classes TraderProcessInput.java

The following screenshot shows that we get a clean compile and also the TraderProcessInput class is now compiled into the classes\controller directory.

compile trader TraderProcessInput

Compiling The EmailUtility ClassTop

The EmailUtility utility java class is used to dispatch emails to our customers.

To use various features of this class we need to get the javax.mail jar. For this purpose I am using javax.mail-1.5.5.jar which I add to the -cp option.


package controller;

import java.util.Properties;

import javax.activation.*;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * A utility class for sending e-mail messages
 * @author www.codejava.net
 *
 */
public class EmailUtility {
    public static void sendEmail(String host, String port,
            final String userName, final String password, String toAddress,
            String subject, String message) throws AddressException,
            MessagingException {

        // sets SMTP server properties
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");

        // creates a new session with an authenticator
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName, password);
            }
        };

        Session session = Session.getInstance(properties, auth);

        // creates a new e-mail message
        MimeMessage  msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(userName));
        msg.addRecipients(Message.RecipientType.TO, 
                InternetAddress.parse(toAddress));
        msg.setSubject(subject);
        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setText("This is message body");
        
        // Create a multipart message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = "C:\\tomcat\\trunk\\webapps\\bstrader\\CustomerReport.html";
        DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        msg.setContent(multipart );

        // sends the e-mail
        Transport.send(msg);
    }
}

Compiling Our Source File With the -cp and -d Options

Open your command line editor:

Change to directory  cd c:\_ServletsJSP_Case_Study\bstrader\src\controller

Compile EmailUtility.java using the java compiler with the -cp and -d options as below, making sure you change apache-tomcat-6.0.37 to wherever you downloaded Tomcat to.

  javac -cp c:\apache-tomcat-6.0.37\lib\servlet-api.jar;c:\_ServletsJSP_Case_Study\bstrader\lib\javax.mail-1.5.5.jar -d ..\..\classes EmailUtility.java

The following screenshot shows that we get a clean compile and also the EmailUtility class is now compiled into the classes\controller directory.

compile trader EmailUtility

Compiling The SendEmails ClassTop

We also need to email customers who have registered on the site with the latest customer reports when the mass email function has been processed and for this purpose we will create the SendEmails Java servlet class to format our mail.

To use various features of this class we need to get the javax.mail jar. For this purpose I am using javax.mail-1.5.5.jar which I add to the -cp option.


package controller;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 * A servlet that takes message details from trader and sends 
 * mass e-mails through an SMTP server.
 * 
 * 
 */

public class SendEmails extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private String host;
    private String port;
    private String user;
    private String pass;

    public void init() {
        // reads SMTP server settings from web.xml file
        ServletContext context = getServletContext();
        host = context.getInitParameter("host");
        port = context.getInitParameter("port");
        user = context.getInitParameter("user");
        pass = context.getInitParameter("pass");
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        // reads form fields
        String recipient = request.getParameter("email");
        String subject = request.getParameter("subject");
        String content = request.getParameter("custReport");

        String resultMessage = "";

        try {
            EmailUtility.sendEmail(host, port, user, pass, recipient, subject,
                    content);
            resultMessage = "The e-mail was sent successfully";
        } catch (Exception ex) {
            ex.printStackTrace();
            resultMessage = "There was an error: " + ex.getMessage();
        } finally {
            request.setAttribute("emailmessage", resultMessage);
            getServletContext().getRequestDispatcher("/WEB-INF/jsp/Result.jsp").forward(
                    request, response);
        }
    }

}

Compiling Our Source File With the -cp and -d Options

Open your command line editor:

Change to directory  cd c:\_ServletsJSP_Case_Study\bstrader\src\controller

Compile SendEmails.java using the java compiler with the -cp and -d options as below, making sure you change apache-tomcat-6.0.37 to wherever you downloaded Tomcat to.

  javac -cp c:\apache-tomcat-6.0.37\lib\servlet-api.jar;..\..\classes;c:\_ServletsJSP_Case_Study\bstrader\lib\javax.mail-1.5.5.jar -d ..\..\classes SendEmails.java

The following screenshot shows that we get a clean compile and also the SendEmails class is now compiled into the classes\controller directory.

compile trader SendEmails

Lesson 8 Complete

In this lesson we took a first look at the controller part of the MVC paradigm and coded the controller components for the trader.

What's Next?

In the next lesson we take a final look at the controller part of the MVC paradigm and code the controller components for the visitor.

go to home page Homepage go to top of page Top