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

public class ServletJDBC extends HttpServlet
{ 
     /* Handle the HTTP GET method by building a simple web page. */
     public void doGet (HttpServletRequest request,
                        HttpServletResponse response)
     throws ServletException, IOException
     {
         PrintWriter         out;
         String              title = "Simple Servlet Output";

         // set content type and other response header fields first
         response.setContentType("text/html");

         // then write the data of the response
         out = response.getWriter();

         out.println("<HTML><HEAD><TITLE>");
         out.println(title);
         out.println("</TITLE></HEAD><BODY>");
         out.println("<H1>" + title + "</H1>");
         out.println("<P>This is output from SimpleServlet.");

         String str = request.getParameter("str");      
         if (str == null) {
            out.println("<P>GET: Something didn't work! Nothing to log.");
         }
         else  {
            out.println("<P>GET: " + str );
   	    if (0 == log_to_database(str, out)) 
		out.println("<P> Logging NOT succesfull" );
 	    else
		out.println("<P>" + str + " logged" );
	 }
         out.println("</BODY></HTML>");
         out.close();
     }


  public int log_to_database (String s, PrintWriter out)
  {
    Connection conn = null;
    int count = 0;
    try
    {
      // BAD PROGRAMMING: THIS SHOULD GO INTO init()  !!!
      System.err.println("calling Class.forName");
      Class.forName("oracle.jdbc.OracleDriver").newInstance();
      System.err.println("passed Class.forName");
      String url = "jdbc:oracle:thin:@limani.cs.uchicago.edu:1521:cs51024";
      Properties p = new Properties();
      p.put("user", "matei");
      p.put("password", "matei");

      System.err.println("Calling getConnection");
      conn = DriverManager.getConnection(url, p);
      System.err.println("Connection established");

      Statement stmt = conn.createStatement();
      count = stmt.executeUpdate("INSERT INTO log VALUES ('"+ s +"')");
      stmt.close();
    }
    catch( SQLException e) {
      System.err.println(e);
      out.println(e);
    }
    catch (ClassNotFoundException e) {
      System.err.println(e);
      out.println(e);
    }
    catch (Exception e) {
      System.err.println(e);
      out.println(e);
    }
    finally {
      try { conn.close(); }
      catch(SQLException e) {
         System.err.println(e);
         out.println(e);
      }
    }
    return count;
  }
}
