Lights On example for the HTML and servlet classes

This example shows you how the HTML and servlet classes work. It is a general overview. To view this example, compile and run it with a webserver and browser running.

import java.io.IOException;
import java.io.CharArrayWriter;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.servlet.*;
import javax.servlet.http.*;

import com.ibm.as400.util.html.*;
import com.ibm.as400.util.servlet.*;
import com.ibm.as400.access.*;

/*
An example of using IBM Toolbox for Java classes in a servlet.

Schemas of SQL databases on the server:

File . . . . . .   LICENSES
Library  . . .     LIGHTSON

 Field            Type          Length   Nulls
 LICENSE          CHARACTER         10   NOT NULL
 USER_ID          CHARACTER         10   NOT NULL WITH DEFAULT
 E_MAIL           CHARACTER         20   NOT NULL
 WHEN_ADDED       DATE                   NOT NULL WITH DEFAULT
 TIME_STAMP       TIMESTAMP              NOT NULL WITH DEFAULT


File . . . . . .   REPORTS
Library  . . .     LIGHTSON

 Field            Type          Length   Nulls
 LICENSE          CHARACTER         10   NOT NULL
 REPORTER         CHARACTER         10   NOT NULL WITH DEFAULT
 DATE_ADDED       DATE                   NOT NULL WITH DEFAULT
 TIME_ADDED       TIME                   NOT NULL WITH DEFAULT
 TIME_STAMP       TIMESTAMP              NOT NULL WITH DEFAULT
 LOCATION         CHARACTER         10   NOT NULL
 COLOR            CHARACTER         10   NOT NULL
 CATEGORY         CHARACTER         10   NOT NULL
*/

public class LightsOn extends javax.servlet.http.HttpServlet

{
  private AS400  system_;
  private String password_;  // password for the server and for the SQL database
  private java.sql.Connection databaseConnection_;



  public void destroy (ServletConfig config)
  {
    try {
      if (databaseConnection_ != null) {
        databaseConnection_.close();
      }
    }
    catch (Exception e) { e.printStackTrace (); }
  }

  public void doGet (HttpServletRequest request,
                     HttpServletResponse response)
    throws IOException, ServletException
  {
    HttpSession session = request.getSession();

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

    out.println(showHtmlMain());

    out.close();
  }

  public void doPost (HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    HttpSession session = request.getSession(true);
    ServletOutputStream out = response.getOutputStream();
    response.setContentType("text/html");

    Hashtable parameters = getRequestParameters (request);

    if (parameters.containsKey("askingToReport"))
      out.println (showHtmlForReporting ());
    else if (parameters.containsKey("askingToRegister"))
      out.println (showHtmlForRegistering ());
    else if (parameters.containsKey("askingToUnregister"))
      out.println(showHtmlForUnregistering());
    else if (parameters.containsKey("askingToListRegistered"))
      out.println (showHtmlForListingAllRegistered ());
    else if (parameters.containsKey("askingToListReported"))
      out.println (showHtmlForListingAllReported ());
    else if (parameters.containsKey("returningToMain"))
      out.println (showHtmlMain ());


    else { // None of the above, so assume the user has filled out a form
           // and is submitting information.  Grab the incoming info
           // and do the requested action.

      if (parameters.containsKey("submittingReport")) {
        String acknowledgement = reportLightsOn (parameters, out);
        out.println (showAcknowledgement(acknowledgement));
      }

      else if (parameters.containsKey("submittingRegistration")) {
        String acknowledgement = registerLicense (parameters, out);
        out.println (showAcknowledgement(acknowledgement));
      }

      else if (parameters.containsKey("submittingUnregistration")) {
        String acknowledgement = unregisterLicense (parameters, out);
        out.println (showAcknowledgement(acknowledgement));
      }

      else {
        out.println (showAcknowledgement("Error (internal): " +
                           "Neither Report, Register, " +
                           "Unregister, ListRegistered, or ListReported."));
      }
    }

    out.close(); // Close the output stream.

  }

  // Gets the parameters from an HTTP servlet request, and packages them
  // into a hashtable for convenience.
  private static Hashtable getRequestParameters (HttpServletRequest request)
  {
    Hashtable parameters = new Hashtable ();
    Enumeration enum = request.getParameterNames();
    while (enum.hasMoreElements()) {
      String key = (String) enum.nextElement();
      String value = request.getParameter (key);
      parameters.put (key, value);
    }
    return parameters;
  }


  // Removes blanks and hyphens from a String, and sets it to all uppercase.
  private static String normalize (String oldString)
  {
    if (oldString == null || oldString.length() == 0) return null;
    StringBuffer newString = new StringBuffer ();
    for (int i=0; i<oldString.length(); i++) {
      if (oldString.charAt(i) != ' ' && oldString.charAt(i) != '-')
        newString.append (oldString.charAt(i));
    }
    return newString.toString().toUpperCase();
  }

  // Composes a list of single-quoted strings.
  private static String quoteList (String[] inList)
  {
    StringBuffer outList = new StringBuffer();
    for (int i=0; i<inList.length; i++)
    {
      outList.append ("'" + inList[i] + "'");
      if (i<inList.length-1)
        outList.append (",");
    }
    return outList.toString();
  }


  public String getServletInfo ()
  {
    return "Lights-On Servlet";
  }

  private AS400 getSystem ()
  {
    try
    {
      if (system_ == null)
      {
        system_ = new AS400();

        // Note: It would be better to get these values
        // from a properties file.
        String sysName  = "MYSYSTEM";    // TBD
        String userId   = "MYUSERID";    // TBD
        String password = "MYPASSWD";    // TBD

        system_.setSystemName(sysName);
        system_.setUserId(userId);
        system_.setPassword(password);
        password_ = password;

        system_.connectService(AS400.DATABASE);
        system_.connectService(AS400.FILE);
        system_.addPasswordCacheEntry(sysName, userId, password_);
      }
    }
    catch (Exception e) { e.printStackTrace (); system_ = null; }

    return system_;
  }


  public void init (ServletConfig config)
  {
    boolean rc;

    try {
      super.init(config);

      // Register the JDBC driver.
      try {
        java.sql.DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver());
      }
      catch (Exception e)
      {
        System.out.println("JDBC Driver not found");
      }


    }
    catch (Exception e) { e.printStackTrace(); }
  }

  private void getDatabaseConnection ()
  {
    if (databaseConnection_ == null) {
      try {
        databaseConnection_ = java.sql.DriverManager.getConnection(
                  "jdbc:as400://" + getSystem().getSystemName() + "/" +
                  "LIGHTSON", getSystem().getUserId(), password_ );

      }
      catch (Exception e) { e.printStackTrace (); }
    }
  }


  private String registerLicense (Hashtable parameters, ServletOutputStream out)
  {
    String licenseNum = normalize ((String)parameters.get("licenseNum"));
    String eMailAddress = (String)parameters.get("eMailAddress");
    StringBuffer acknowledgement = new StringBuffer();

    if (licenseNum == null || licenseNum.length() == 0)
      acknowledgement.append ("Error: License number not specified.\n");

    if (eMailAddress == null || eMailAddress.length() == 0)
      acknowledgement.append ("Error: Notification e-mail address not specified.\n");

    if (acknowledgement.length() == 0)
    {
      try
      {
        // Insert the new license number and e-mail address into the database.
        getDatabaseConnection ();
        Statement sqlStatement = databaseConnection_.createStatement();

        // Issue the request.
        String cmd = "INSERT INTO LICENSES (LICENSE, E_MAIL) VALUES (" +
          quoteList(new String[] {licenseNum, eMailAddress}) + ")";
        sqlStatement.executeUpdate(cmd);
        sqlStatement.close();

        // Acknowledge the request.
        acknowledgement.append ("License number " + licenseNum + " has been registered.");
        acknowledgement.append ("Notification e-mail address is: " + eMailAddress);
      }
      catch (Exception e) { e.printStackTrace (); }
    }
    return acknowledgement.toString();
  }


  private String unregisterLicense (Hashtable parameters, ServletOutputStream out)
  {
    String licenseNum = normalize ((String)parameters.get("licenseNum"));
    StringBuffer acknowledgement = new StringBuffer();

    if (licenseNum == null || licenseNum.length() == 0)
      acknowledgement.append ("Error: License number not specified.\n");

    if (acknowledgement.length() == 0)
    {
      try
      {
        // Remove the specified license number and e-mail address from database.
        getDatabaseConnection ();
        Statement sqlStatement = databaseConnection_.createStatement();

        // Delete the row(s) from the LICENSES database.
        String cmd = "DELETE FROM LICENSES WHERE LICENSE = '" + licenseNum + "'";
        sqlStatement.executeUpdate(cmd);
        sqlStatement.close();

        // Acknowledge the request.
        acknowledgement.append ("License number " + licenseNum + " has been unregistered.");
      }
      catch (Exception e) { e.printStackTrace (); }
    }
    return acknowledgement.toString();
  }


  private String reportLightsOn (Hashtable parameters, ServletOutputStream out)
  {
    String licenseNum = normalize ((String)parameters.get("licenseNum"));
    String location = (String)parameters.get("location");
    String color = (String)parameters.get("color");
    String category = (String)parameters.get("category");
    StringBuffer acknowledgement = new StringBuffer();
    if (licenseNum == null || licenseNum.length() == 0)
      acknowledgement.append ("Error: License number not specified.");

    if (acknowledgement.length() == 0)
    {
      try
      {
        // Report "lights on" for a specified vehicle.
        getDatabaseConnection ();
        Statement sqlStatement = databaseConnection_.createStatement();

        // Add an entry to the REPORTS database.
        String cmd = "INSERT INTO REPORTS (LICENSE, LOCATION, COLOR, CATEGORY) VALUES (" +
          quoteList(new String[] {licenseNum, location, color, category}) + ")";
        sqlStatement.executeUpdate(cmd);
        sqlStatement.close();

        // Acknowledge the request.
        acknowledgement.append ("License number " + licenseNum + " has been reported.  Thanks!");
      }
      catch (Exception e) { e.printStackTrace (); }
    }
    return acknowledgement.toString();
  }


  private String showHeader (String title)
  {
    StringBuffer page = new StringBuffer();
    page.append("<html><head><title>" + title + "</title>");
    page.append("</head><body bgcolor=\"blanchedalmond\">");
    return page.toString ();
  }


  private String showAcknowledgement (String acknowledgement)
  {
    String title = "Acknowledgement";
    StringBuffer page = new StringBuffer();
    page.append (showHeader (title));

    try {
      HTMLForm form = new HTMLForm("LightsOn");
      GridLayoutFormPanel grid = new GridLayoutFormPanel();
      HTMLText text = new HTMLText(acknowledgement);
      if (acknowledgement.startsWith("Error"))
        text.setBold(true);
      grid.addElement(text);
      grid.addElement(new SubmitFormInput("returningToMain", "Home"));
      form.addElement(grid);
      page.append(form.toString());
    }
    catch (Exception e) { e.printStackTrace (); }
    page.append("</body></html>");
    return page.toString();
  }


  private String showHtmlMain ()
  {
    String title = "Lights-On tool";
    StringBuffer page = new StringBuffer();
    page.append (showHeader (title));

    page.append("<h1>" + title + "</h1>");


    // Create the HTML Form object.
    HTMLForm mainForm = new HTMLForm("LightsOn");
    GridLayoutFormPanel grid = new GridLayoutFormPanel();

    try {
      // Set up so that doPost() gets called when the form is submitted.
      mainForm.setMethod(HTMLForm.METHOD_POST);

      // Create some buttons.
      grid.addElement(new SubmitFormInput("askingToReport", "Report a vehicle with lights on"));
      grid.addElement(new SubmitFormInput("askingToRegister", "Register my license number"));
      grid.addElement(new SubmitFormInput("askingToUnregister", "Unregister my license number"));
      grid.addElement(new SubmitFormInput("askingToListRegistered", "List all registered licenses"));
      grid.addElement(new SubmitFormInput("askingToListReported", "List all vehicles with lights on"));

      mainForm.addElement(grid);
    }
    catch (Exception e) { e.printStackTrace (); }

    page.append(mainForm.toString());
    page.append("</body></html>");

    return page.toString();
  }


  private String showHtmlForReporting ()
  {
    String title = "Report a vehicle with lights on";
    StringBuffer page = new StringBuffer();
    page.append (showHeader (title));

    page.append("<h1>" + title + "</h1>");

    // Create the HTML Form object.
    HTMLForm reportForm = new HTMLForm("LightsOn");
    GridLayoutFormPanel grid = new GridLayoutFormPanel(2);

    try {
      // Set up so that doPost() gets called when the form is submitted.
      reportForm.setMethod(HTMLForm.METHOD_POST);

      TextFormInput licenseNum = new TextFormInput("licenseNum");
      licenseNum.setSize(10);
      licenseNum.setMaxLength(10);

      // Add elements to the line form
      grid.addElement(new LabelFormElement("Vehicle license number:"));
      grid.addElement(licenseNum);

      // Create a radio button group and add the radio buttons.
      RadioFormInputGroup colorGroup = new RadioFormInputGroup("color");

      colorGroup.add("color", "white", "white", true);
      colorGroup.add("color", "black", "black", false);
      colorGroup.add("color", "gray", "gray", false);
      colorGroup.add("color", "red", "red", false);
      colorGroup.add("color", "yellow", "yellow", false);
      colorGroup.add("color", "green", "green", false);
      colorGroup.add("color", "blue", "blue", false);
      colorGroup.add("color", "brown", "brown", false);

      // Create a selection list for category of vehicle.
      SelectFormElement category = new SelectFormElement("category");
      category.addOption("sedan", "sedan", true);
      category.addOption("convertible", "convertibl"); // 10-char field in DB
      category.addOption("truck", "truck");
      category.addOption("van", "van");
      category.addOption("SUV", "SUV");
      category.addOption("motorcycle", "motorcycle");
      category.addOption("other", "other");

      // Create a selection list for vehicle location (building number).
      SelectFormElement location = new SelectFormElement("location");
      location.addOption("001", "001", true);
      location.addOption("002", "002");
      location.addOption("003", "003");
      location.addOption("005", "005");
      location.addOption("006", "006");
      location.addOption("015", "015");

      grid.addElement(new LabelFormElement("Color:"));
      grid.addElement(colorGroup);

      grid.addElement(new LabelFormElement("Vehicle type:"));
      grid.addElement(category);

      grid.addElement(new LabelFormElement("Building:"));
      grid.addElement(location);

      grid.addElement(new SubmitFormInput("submittingReport", "Submit report"));
      grid.addElement(new SubmitFormInput("returningToMain", "Home"));

      reportForm.addElement(grid);
    }
    catch (Exception e) { e.printStackTrace (); }

    page.append(reportForm.toString());

    page.append("</body></html>");

    return page.toString();
  }


  private String showHtmlForRegistering ()
  {
    String title = "Register my license number";
    StringBuffer page = new StringBuffer();
    page.append (showHeader (title));

    page.append("<h1>" + title + "</h1>");

    // Create the HTML Form object.
    HTMLForm registrationForm = new HTMLForm("LightsOn");

    // Set up a two-column panel layout, within which to arrange
    // the generated HTML elements.
    GridLayoutFormPanel grid = new GridLayoutFormPanel(2);

    try {
      // Set up so that doPost() gets called when the form is submitted.
      registrationForm.setMethod(HTMLForm.METHOD_POST);

      TextFormInput licenseNum = new TextFormInput("licenseNum");
      licenseNum.setSize(10);
      licenseNum.setMaxLength(10);

      TextFormInput eMailAddress = new TextFormInput("eMailAddress");
      eMailAddress.setMaxLength(20);

      grid.addElement(new LabelFormElement("License number:"));
      grid.addElement(licenseNum);

      grid.addElement(new LabelFormElement("E-mail notification address:"));
      grid.addElement(eMailAddress);

      grid.addElement(new SubmitFormInput("submittingRegistration", "Register"));
      grid.addElement(new SubmitFormInput("returningToMain", "Home"));

      registrationForm.addElement(grid);
    }
    catch (Exception e) { e.printStackTrace (); }

    page.append(registrationForm.toString());

    page.append("</body></html>");

    return page.toString();
  }


  private String showHtmlForUnregistering ()
  {
    String title = "Unregister my license number";
    StringBuffer page = new StringBuffer();
    page.append (showHeader (title));

    page.append("<h1>" + title + "</h1>");

    // Create the HTML Form object.
    HTMLForm unregistrationForm = new HTMLForm("LightsOn");
    GridLayoutFormPanel grid = new GridLayoutFormPanel(2);

    try {
      // Set up so that doPost() gets called when the form is submitted.
      unregistrationForm.setMethod(HTMLForm.METHOD_POST);

      // Create the LineLayoutFormPanel object.
      TextFormInput licenseNum = new TextFormInput("licenseNum");
      licenseNum.setSize(10);
      licenseNum.setMaxLength(10);

      grid.addElement(new LabelFormElement("Vehicle license number:"));
      grid.addElement(licenseNum);

      grid.addElement(new SubmitFormInput("submittingUnregistration", "Unregister"));
      grid.addElement(new SubmitFormInput("returningToMain", "Home"));

      unregistrationForm.addElement(grid);
    }
    catch (Exception e) {
      e.printStackTrace ();
      CharArrayWriter cWriter = new CharArrayWriter();
      PrintWriter pWriter = new PrintWriter (cWriter, true);
      e.printStackTrace (pWriter);
      page.append (cWriter.toString());
    }

    page.append(unregistrationForm.toString());

    page.append("</body></html>");

    return page.toString();
  }


  private String showHtmlForListingAllRegistered ()
  {
    String title = "All registered licenses";
    StringBuffer page = new StringBuffer();
    page.append (showHeader (title));

    try
    {
      // Create the HTML Form object.
      HTMLForm mainForm = new HTMLForm("LightsOn");

      // Set up a single-column panel layout, within which to arrange
      // the generated HTML elements.
      GridLayoutFormPanel grid = new GridLayoutFormPanel();

      // Specify the layout for the generated table.
      HTMLTable table = new HTMLTable();
      table.setAlignment(HTMLConstants.LEFT);
      table.setBorderWidth(3);

      // Create and add the table caption and header.
      HTMLTableCaption caption = new HTMLTableCaption();
      caption.setAlignment(HTMLConstants.TOP);
      caption.setElement(title);
      table.setCaption(caption);
      table.setHeader(new String[] { "License", "Date added" } );

      // Create the converter, which will generate table HTML from
      // the result set that comes back from the database query.
      HTMLTableConverter converter = new HTMLTableConverter();
      converter.setTable(table);

      getDatabaseConnection ();
      Statement sqlStatement = databaseConnection_.createStatement();

      // First pre-query the database to verify that it's not empty.
      String query = "SELECT COUNT(*) FROM LICENSES";
      ResultSet rs = sqlStatement.executeQuery (query);
      rs.next();  // position cursor to first row
      int rowCount = rs.getInt(1);

      if (rowCount == 0) {
        page.append ("<font size=4 color=red>No vehicles have been reported.</font>");
      } 
      else {
        query = "SELECT LICENSE,WHEN_ADDED FROM LICENSES";
        rs = sqlStatement.executeQuery (query);
        SQLResultSetRowData rowData = new SQLResultSetRowData (rs);
        HTMLTable[] generatedHtml = converter.convertToTables(rowData);
        grid.addElement(generatedHtml[0]);
      }
      sqlStatement.close();
      // Note: Mustn't close statement before we're done using result set.

      grid.addElement(new SubmitFormInput("returningToMain", "Home"));

      mainForm.addElement(grid);
      page.append(mainForm.toString());
    }
    catch (Exception e) { e.printStackTrace (); }
    page.append("</body></html>");
    return page.toString();
  }


  private String showHtmlForListingAllReported ()
  {
    String title = "All vehicles with lights on";
    StringBuffer page = new StringBuffer();
    page.append (showHeader (title));

    try
    {
      // Create the HTML Form object.
      HTMLForm form = new HTMLForm("LightsOn");

      // Set up a single-column panel layout, within which to arrange
      // the generated HTML elements.
      GridLayoutFormPanel grid = new GridLayoutFormPanel();

      // Specify the layout for the generated table.
      HTMLTable table = new HTMLTable();
      table.setAlignment(HTMLConstants.LEFT);
      table.setBorderWidth(3);

      // Create and add the table caption and header.
      HTMLTableCaption caption = new HTMLTableCaption();
      caption.setAlignment(HTMLConstants.TOP);
      caption.setElement(title);
      table.setCaption(caption);
      table.setHeader(new String[] { "License", "Color", "Category", "Date", "Time" } );

      // Create the converter, which will generate table HTML from
      // the result set that comes back from the database query.
      HTMLTableConverter converter = new HTMLTableConverter();
      converter.setTable(table);

      getDatabaseConnection ();
      Statement sqlStatement = databaseConnection_.createStatement();

      // First pre-query the database to verify that it's not empty.
      String query = "SELECT COUNT(*) FROM REPORTS";
      ResultSet rs = sqlStatement.executeQuery (query);
      rs.next();  // position cursor to first row
      int rowCount = rs.getInt(1);

      if (rowCount == 0) {
        page.append ("<font size=4 color=red>No vehicles have been reported.</font>");
      } 
      else {
        query = "SELECT LICENSE,COLOR,CATEGORY,DATE_ADDED,TIME_ADDED FROM REPORTS";
        rs = sqlStatement.executeQuery (query);
        SQLResultSetRowData rowData = new SQLResultSetRowData (rs);
        HTMLTable[] generatedHtml = converter.convertToTables(rowData);
        grid.addElement(generatedHtml[0]);
      }
      sqlStatement.close();
      // Note: Mustn't close statement before we're done using result set.

      grid.addElement(new SubmitFormInput("returningToMain", "Home"));
      form.addElement(grid);
      page.append(form.toString());
    }
    catch (Exception e) { e.printStackTrace (); }
    page.append("</body></html>");
    return page.toString();
  }

}