package server.servlets;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpUtils;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.Hashtable;

/*
     PhoneBook.java:
    Example of a middle-tier Java application - a servlet
    accessing a back-end database.

     Copyright (c) 1999 Nathan Meyers
     $Id: PhoneBook.java,v 1.6 1999/11/10 03:44:25 nathanm Exp $

     Permission is hereby granted, free of charge, to any person obtaining
     a copy of this software and associated documentation files (the
     "Software"), to deal in the Software without restriction, including
     without limitation the rights to use, copy, modify, merge, publish,
     distribute, sublicense, and/or sell copies of the Software, and to
     permit persons to whom the Software is furnished to do so, subject
     to the following conditions:

     The above copyright notice and this permission notice shall be
     included in all copies or substantial portions of the Software.

     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
     KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
     WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
     NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
     BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
     AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
     IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
     THE SOFTWARE.
*/

public class PhoneBook extends HttpServlet {
    Connection connection = null;

    public void init(ServletConfig config) throws ServletException {
        // Servlet initialization
        super.init(config);
        try {
            // Load the MySQL JDBC driver
            Class.forName("org.gjt.mm.mysql.Driver");
        } catch (ClassNotFoundException e) {
            throw new ServletException(e.toString());
        }
    }

    private void doOutput1(PrintWriter writer) {
        writer.println(
                "<HTML>\n" +
                "<HEAD>\n" +
                "<TITLE>Phone Book</TITLE>" +
                "</HEAD>\n" +
                "<BODY>\n" +
                "<CENTER>\n" +
                "<H1>Telephone Book</H1>\n" +
                "<FORM ACTION=\"PhoneBook\" METHOD=\"POST\">" +
                "<TABLE>\n" +
                "<TR>\n" +
                "  <TD>Last Name</TD>\n" +
                "  <TD><INPUT TYPE=\"TEXT\" SIZE=20 NAME=\"LastName\"></TD>" +
                "</TR><TR>\n" +
                "  <TD>First Name</TD>\n" +
                "  <TD><INPUT TYPE=\"TEXT\" SIZE=20 NAME=\"FirstName\"></TD>" +
                "</TR><TR>\n" +
                "  <TD>Country Code</TD>\n" +
                "  <TD><INPUT TYPE=\"TEXT\" SIZE=5 NAME=\"CountryCode\"></TD>" +
                "</TR><TR>\n" +
                "  <TD>Area Code</TD>\n" +
                "  <TD><INPUT TYPE=\"TEXT\" SIZE=5 NAME=\"AreaCode\"></TD>" +
                "</TR><TR>\n" +
                "  <TD>Phone Number</TD>\n" +
                "  <TD><INPUT TYPE=\"TEXT\" SIZE=15 NAME=\"PhoneNum\"></TD>" +
                "</TR>\n" +
                "</TABLE>" +
                "<INPUT TYPE=\"Submit\" NAME=\"Query\" VALUE=\"Query\">\n" +
                "<INPUT TYPE=\"Submit\" NAME=\"Add\" VALUE=\"Add New Entry\">\n" +
                "<INPUT TYPE=\"Reset\" VALUE=\"Reset\">\n" +
                "</FORM><BR>"
        );
    }

    private void doOutput2(PrintWriter writer) {
        writer.println("</BODY></HTML>");
    }

    public void doGet(HttpServletRequest req, HttpServletResponse resp) {
        // Get action puts up the query form.
        resp.setContentType("text/html");
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
        } catch (IOException e) {
            return;
        }
        doOutput1(writer);
        doOutput2(writer);
        writer.close();
    }

    public synchronized void doPost(HttpServletRequest req,
                                    HttpServletResponse resp) {
        // Post action puts up the query form and responds to the post
        resp.setContentType("text/html");
        PrintWriter writer = null;
        try {
            writer = resp.getWriter();
        } catch (IOException e) {
            return;
        }

        // Output the form
        doOutput1(writer);

        // Open or reopen the connection if needed
        try {
            // Open a connection to the server - no login or password.
            // The form of the URL (first parameter) is dictated by the
            // MySQL jdbc driver. Default MySQL TCP port is 3306
            if (connection == null || connection.isClosed())
                connection = DriverManager.getConnection(
                        "jdbc:mysql://localhost:3306/test", "lyon", null);
        } catch (SQLException e) {
            writer.println("Error: Cannot open database connection\n");
            doOutput2(writer);
            writer.close();
            return;
        }

        // Open input from the POST data
        Hashtable postData = null;
        try {
            // Build a hashtable of the posted data
            postData = HttpUtils.parsePostData(
                    req.getContentLength(), req.getInputStream());
        } catch (IOException e) {
            writer.println("Error: Cannot read post data\n");
        }
        if (postData.containsKey("Add")) {
            // User requested to add a new entry... make sure
            // at least last name is non-empty
            if (((String[]) postData.get("LastName"))[0].length() == 0)
                writer.println("Error: No last name specified for Add");
            else
                try {
                    // Construct and execute an SQL statement to insert
                    Statement stmt = connection.createStatement();
                    stmt.executeUpdate(
                            "INSERT INTO phonelist VALUES (" +
                            "'" +
                            ((String[]) postData.get("LastName"))[0] +
                            "','" +
                            ((String[]) postData.get("FirstName"))[0] +
                            "','" +
                            ((String[]) postData.get("CountryCode"))[0] +
                            "','" +
                            ((String[]) postData.get("AreaCode"))[0] +
                            "','" +
                            ((String[]) postData.get("PhoneNum"))[0] +
                            "');");
                    writer.println("New entry added for " +
                            ((String[]) postData.get("LastName"))[0]);
                } catch (SQLException e) {
                    writer.println("Error: " + e.toString());
                } catch (NullPointerException e) {
                    // This will trigger if a form field is missing from
                    // the post.
                    writer.println("Error: " + e.toString());
                }
        } else {
            // User requested a query...
            ResultSet results = null;
            try {
                // Construct an SQL query string. First figure out
                // the qualifiers based on form input
                StringBuffer queryQualifiers = new StringBuffer();
                appendQueryQualifiers(queryQualifiers, "lastname",
                        (postData.get("LastName")));
                appendQueryQualifiers(queryQualifiers, "firstname",
                        (postData.get("FirstName")));
                appendQueryQualifiers(queryQualifiers, "countrycode",
                        (postData.get("CountryCode")));
                appendQueryQualifiers(queryQualifiers, "areacode",
                        (postData.get("AreaCode")));
                appendQueryQualifiers(queryQualifiers, "number",
                        (postData.get("PhoneNum")));

                Statement stmt = connection.createStatement();
                results = stmt.executeQuery(
                        "SELECT * FROM phonelist" +
                        queryQualifiers +
                        ";"
                );

                if (results == null)
                    writer.println("Null result from query");
                else {
                    // Print headers
                    writer.println(
                            "<TABLE BORDER=\"2\">\n" +
                            "<TR>\n" +
                            "  <TD><CENTER><B>Last Name</B></CENTER></TD>\n" +
                            "  <TD><CENTER><B>First Name</B></CENTER></TD>\n" +
                            "  <TD><CENTER><B>Country Code</B></CENTER></TD>\n" +
                            "  <TD><CENTER><B>Area Code</B></CENTER></TD>\n" +
                            "  <TD><CENTER><B>Phone Number</B></CENTER></TD>\n" +
                            "</TR>");

                    while (results.next()) {
                        writer.println(
                                "<TR>" +
                                "  <TD>" + results.getString(1) + "</TD>\n" +
                                "  <TD>" + results.getString(2) + "</TD>\n" +
                                "  <TD>" + results.getString(3) + "</TD>\n" +
                                "  <TD>" + results.getString(4) + "</TD>\n" +
                                "  <TD>" + results.getString(5) + "</TD>\n" +
                                "</TR>");
                    }
                    writer.println("</TABLE>");
                }
            } catch (SQLException e) {
                writer.println("Error: " + e.toString());
            }
        }
        doOutput2(writer);
        writer.close();
    }

    // appendQueryQualifiers: A utility to assist in constructing
    // the query string
    private void appendQueryQualifiers(StringBuffer qualifiers,
                                       String dbfield,
                                       Object formdata) {
        if (formdata == null) return;
        String forminfo = ((String[]) formdata)[0];
        // Was anything specified for this form field?
        if (forminfo.length() > 0) {
            // Yes
            if (qualifiers.length() == 0)
                qualifiers.append(" WHERE");
            else
                qualifiers.append(" AND");
            qualifiers.append(" " + dbfield + " = \"" +
                    forminfo + "\"");
        }
    }

    public String getServletInfo() {
        return "PhoneBook";
    }
}