// Written by Brad Simonin.
// This Java Servlet reads in information from an HTML Form and then 
// loads the data into an Access 97 database using the JDBC:ODBC Bridge.


import java.io.*;
import java.util.*;
import java.sql.*;

import javax.servlet.*;
import javax.servlet.http.*;

public class BradsGuestBookServlet extends HttpServlet	
{
	public void doPost (HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException
	{
	
		
		boolean SessionValue = false;
		HttpSession session = req.getSession(true);
		Integer count = (Integer)session.getValue("tracker.count");
		if (count == null)
			count = new Integer(1);
		else
			count = new Integer(count.intValue() + 1);
		session.putValue("tracker.count", count);
		
		
		res.setContentType("text/html");
		ServletOutputStream out = res.getOutputStream();
		
		String MyCookie = null;
		boolean FoundCookie = false;
		boolean CreatedCookie = false;

		Cookie[] cookies = req.getCookies();
		if (cookies != null) 
		{
			for (int i = 0; i < cookies.length; i++)
			{
				if (cookies[i].getName().equals("MyCookie"))
				{
					MyCookie = cookies[i].getValue();
					FoundCookie = true;
					break;
				}
			}
		}

		if (MyCookie == null)
		{
			MyCookie = "BradSimonin";
			Cookie c = new Cookie("MyCookie",MyCookie);
			//c.setDomain(".bradleysimonin.com");
			//c.setPath("http://128.123.20.93/Servlet");
			c.setMaxAge(604800);
			CreatedCookie = true;
			res.addCookie(c);
		}
			
		String IPAddress = req.getRemoteAddr();
		if (IPAddress.equals("")) 
			IPAddress = null;
		else 
			IPAddress = "'" + IPAddress + "'";
		
		String RemoteHost = req.getRemoteHost();
		String TheProtocol = req.getProtocol();
		int ThePort = req.getServerPort();
		String TheRemoteUser = req.getRemoteUser();
		
		String Name = null;
		String NameShow = null;
		String Email = null;
		String WebSite= null;
		String CompanyOccupation = null;
		String City = null;
		String State = null;
		String Comment = null;
		
		
		
		Enumeration PostData = req.getParameterNames();	
		
		while (PostData.hasMoreElements())
		{
				String PostDataCheck = (String)PostData.nextElement();
				PostDataCheck.trim();
										
				if (PostDataCheck.equals("strName")) 
				{		
					Name = req.getParameter("strName");	
					Name = Name.trim();
					Name = Name.replace('\'','`');
					Name = Name.replace(',',' ');
					Name = Name.replace('.',' ');
					Name = Name.toUpperCase();
					NameShow = Name;
					if (Name.equals("")) 
						Name = null;
					else 
						Name = "'" + Name + "'";
				}
				
				if (PostDataCheck.equals("strEmail")) 
				{
					Email = req.getParameter("strEmail");
					Email = Email.trim();
					Email = Email.replace('\'','`');
					if (Email.equals("")) 
						Email = null;
					else 
						Email = "'" + Email + "'";
				}
				
				if (PostDataCheck.equals("strWebSite")) 
				{
					WebSite = req.getParameter("strWebSite");
					WebSite = WebSite.trim();
					WebSite = WebSite.replace('\'','`');
					if (WebSite.equals("")) 
						WebSite = null;
					else 
					{
						if (WebSite.indexOf("http://") == -1)
							WebSite = "http://" + WebSite;		
						WebSite = "'" + WebSite + "'";
					}
				}
				
				if (PostDataCheck.equals("strCompanyOccupation"))
				{ 
					CompanyOccupation = req.getParameter("strCompanyOccupation");
					CompanyOccupation = CompanyOccupation.trim();
					CompanyOccupation = CompanyOccupation.replace('\'','`');
					CompanyOccupation = CompanyOccupation.replace(',',' ');
					CompanyOccupation = CompanyOccupation.replace('.',' ');
					CompanyOccupation = CompanyOccupation.toUpperCase();
					if (CompanyOccupation.equals("")) 
						CompanyOccupation = null;
					else 
						CompanyOccupation = "'" + CompanyOccupation + "'";
				}
				
				if (PostDataCheck.equals("strCity")) 
				{
					City = req.getParameter("strCity");
					City = City.trim();
					City = City.replace('\'','`');
					City = City.replace(',',' ');
					City = City.replace('.',' ');
					City = City.toUpperCase();
					if (City.equals("")) 
						City = null;
					else 
						City = "'" + City + "'";
				}
				
				if (PostDataCheck.equals("strState")) 
				{
					State = req.getParameter("strState");
					State = State.trim();
					State = State.replace('\'','`');
					State = State.replace(',',' ');
					State = State.replace('.',' ');
					if (State.equals("")) 
						State = null;
					else 
						State = "'" + State + "'";
				}
				
				if (PostDataCheck.equals("strComment")) 
				{
					Comment = req.getParameter("strComment");
					Comment = Comment.trim();
					Comment = Comment.replace('\'','`');
					if (Comment.equals("")) 
						Comment = null;
					else 
						Comment = "'" + Comment + "'";
				}
				
		} // end while loop
								
		PostData = null;
		String SqlString;
		
		SqlString = "INSERT INTO Brads_GuestBook " +
				"(Name, Company_Occupation, City, State, E_Mail, Web_Page, " +
			    "Comments, Users_IP_Address, Time_Stamp, Type) " +
				"VALUES (" + Name + ", " + CompanyOccupation + ", " +
				City + ", " + State + ", " + Email + ", " + WebSite + ", " +
				Comment + ", " + IPAddress + ", Now(), 'SERVLET')";
		
		
		out.println ("<html><head><title>Brad's Guest Book Java Servlet Processor</title></head><body>");
		out.println ("<p><h2> Thank you <i>" + NameShow + "</i> for signing my Guest Book.</h2></p>");
		
		try
		{
			Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
			String url = "jdbc:odbc:Brad";  // Brad is the name of my ODBC DSN
			Connection con;
			Statement stmt;
			con = DriverManager.getConnection(url);
			stmt = con.createStatement();
			if (count.intValue() <= 1)   
				stmt.executeUpdate(SqlString);
			stmt.close();
			con.close();
		}
		catch(SQLException SQL_ex)
		{
			out.println("SQLException: " + SQL_ex.getMessage());
		}
		catch(ClassNotFoundException Class_ex)
		{
			out.println("ClassException: " + Class_ex.getMessage());
		}
		
		out.println ("<p>&nbsp;</p>");
		
		out.println("SESSION TESTING:  You've visited this page " + count + 
					((count.intValue() == 1) ? " time." : " times."));
		out.println("<p>");
		
		out.println("COOKIE TESTING:  The Cookie is: " + MyCookie + "<br>");
		out.println("Created Cookie: " + CreatedCookie + " FoundCookie is: " + FoundCookie);
		out.println("<p>");
		
		out.println ("<center><form>");
		String BackButton;
		BackButton = "<p><input TYPE=\"button\" VALUE=\"   Click Here to Continue....    \" STYLE=\"font: 10pt Arial Black; background:Teal\" onClick=\"history.go(-2)\"> </p>"; 
		out.println (BackButton);
		out.println ("</center></form>");
		out.println ("<p>&nbsp;</p>");
		out.println("<P>Or to view the source code of this Java Servlet click on the " +
					"following hyperlink: <A HREF=\"http://www.cs.nmsu.edu/~bsimonin/BradsGuestBookServlet.java\">" +
					"BradsGuestBookServlet.java</a><P>");
		out.println ("</body></html>");	
		
		try
		{
			out.close();
		}
		catch(IOException IO_ex)
		{
			out.println("IOException: " + IO_ex.getMessage());
		}
			
	} // end doPost method
	
	
	
	public void doGet (HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException
	{
		res.setContentType("text/html");
		ServletOutputStream out = res.getOutputStream();
		
		/*
		HttpSession session = req.getSession(true);
		Integer count = (Integer)session.getValue("tracker.count");
		if (count == null)
			count = new Integer(1);
		else
			count = new Integer(count.intValue() + 1);
		session.putValue("tracker.count", count);
		*/
		
		String HTMLString;
		
		HTMLString = "<HTML><HEAD><title>Brad's Guest Book Java Servlet Processor</title></head>" +
					 "<body bgcolor=\"#FFFFFF\"></body><META HTTP-EQUIV=\"REFRESH\" CONTENT=\"5;" +
					 " URL=http://www.cs.nmsu.edu/~bsimonin/BradsGuestBookServlet.html" +
					 "\">";
		out.println(HTMLString);
		HTMLString = "Your browser should automatically re-direct to the Guest Book page" +
					 " in 5 seconds.<p>";
		out.println(HTMLString);
		HTMLString = "If your browser does not support re-direction you can click on the " +
					 "following hyperlink for my Guest Book:<br>";
		out.println(HTMLString);
		HTMLString = "<A HREF=\"http://www.cs.nmsu.edu/~bsimonin/BradsGuestBookServlet.html" +
					 "\">http://www.cs.nmsu.edu/~bsimonin/BradsGuestBookServlet.html" +
					 "</A>";
		out.println(HTMLString);
		HTMLString = "<P>Or click on the following hyperlink for the main page on my Web Site:<br>" + 
					"<A HREF=\"http://www.cs.nmsu.edu/~bsimonin/" +
					"\">http://www.cs.nmsu.edu/~bsimonin/" +
					"</A>";
		out.println(HTMLString);
		
		/*
		out.println("<p>SESSION TESTING:  You've visited this page " + count + 
					((count.intValue() == 1) ? " time." : " times."));
		out.println("<p>");
		*/
		
		HTMLString = "</HTML>";
		out.println(HTMLString);
		
		try
		{
			out.close();
		}
		catch(IOException IO_ex)
		{
			out.println("IOException: " + IO_ex.getMessage());
		}
	
	} // end doGet method
	
	
} // end BradsGuestBookServlet
