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

public class FindFriend extends HttpServlet {

  public void doPost(HttpServletRequest request, 
      HttpServletResponse response) 
      throws ServletException, IOException
  {

    // print formatted information
    PrintWriter out = response.getWriter(); 


    // The newInstance() call is a work around for some broken
    // Java implementations

    try {
      Class.forName("com.mysql.jdbc.Driver").newInstance();
    }

    catch (Exception e) {
      out.println("Unable to load driver.");
      e.printStackTrace();
    }

    try {

      String MYSQL_HOST   = "localhost";
      String MYSQL_DB     = "cs655";
      String MYSQL_USER   = "cs655";
      String MYSQL_PASSWD = "abc123";
 
      // Replace
      //  _server_ with the remote server name
      //  _db_     with the remote database name
      // _user_    with the database user name
      // _pwd_     with the user password

      Connection Conn = DriverManager.getConnection(
        "jdbc:mysql://" + MYSQL_HOST + "/" + MYSQL_DB +
        "?user=" + MYSQL_USER + "&password=" + MYSQL_PASSWD);
                
      Statement Stmt = Conn.createStatement();

      // Replace
      //  _table_ with the remote database table name

      String sql_cmd = "SELECT * from Friend";
      ResultSet RS = Stmt.executeQuery(sql_cmd);

      // set content type to HTML
      response.setContentType("text/html");  

      out.println("<html><head><title>");
      out.println("Find Friend");
      out.println("</title></head><body>");

      while (RS.next()) {
         out.println("First Name: " + RS.getString(1) + "<br>");
         out.println("Last Name: " + RS.getString(2) + "<br>");
         out.println("City: " + RS.getString(3) + "<br>");
         out.println("State: " + RS.getString(4) + "<br>");
         out.println("Age: " + RS.getInt(5) + "<p>");
      }

      out.println("</body></html>");

      // Clean up after ourselves
      out.close();
      RS.close();
      Stmt.close();
      Conn.close();
    }

    catch (SQLException E) {
      out.println("SQLException: " + E.getMessage());
      out.println("SQLState:     " + E.getSQLState());
      out.println("VendorError:  " + E.getErrorCode());
    }
  }
}
