/*
 *
 * Copyright 2002 Sun Microsystems, Inc. All Rights Reserved.
 *
 * This software is the proprietary information of Sun Microsystems, Inc.
 * Use is subject to license terms.
 *
 */
package samples.jdbc.simple.servlet;


import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.naming.*;

import javax.servlet.http.*;

import java.sql.*;

import javax.sql.*;


/**
 * This servlet is responsible for generating the pages which asks for a String input
 * It will generate a Greeting and save it in a database.
 */
public class GreeterDBServlet extends HttpServlet {

    /**
      * The doGet method of the servlet. Handles all http GET request.
          * Required by the servlet specification.
          * @exception throws ServletException and IOException.
          */
    public void doGet(
            HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

        InitialContext initContext = null;
        Hashtable      env         = new java.util.Hashtable(1);

        try {
            initContext = new javax.naming.InitialContext();
        } catch(Exception e) {
            System.out.println("- Exception creating InitialContext: "
                               + e.toString());

            return;
        }

        String       theMessage = getGreeting();
        String       name       = request.getParameter("name");
        StringBuffer timeStamp  = new StringBuffer();
        Calendar     rightNow   = Calendar.getInstance();

        timeStamp.append(rightNow.get(Calendar.MONTH) + 1);
        timeStamp.append("/");
        timeStamp.append(rightNow.get(Calendar.DAY_OF_MONTH));
        timeStamp.append("/");
        timeStamp.append(rightNow.get(Calendar.YEAR));
        timeStamp.append(" ");
        timeStamp.append(rightNow.get(Calendar.HOUR_OF_DAY));
        timeStamp.append(":");
        timeStamp.append(rightNow.get(Calendar.MINUTE));
        timeStamp.append(":");
        timeStamp.append(rightNow.get(Calendar.SECOND));
        timeStamp.append(":");
        timeStamp.append(rightNow.get(Calendar.MILLISECOND));

        StringBuffer query =
            new StringBuffer(
                "insert into Greeting (timeStamp,name,message) values ");

        query.append("('");
        query.append(timeStamp.toString());
        query.append("','");
        query.append(name);
        query.append("','");
        query.append("Good " + theMessage);
        query.append("')");

        try {
            String     dsName = "java:comp/env/jdbc/jdbc-simple";
            DataSource ds = (javax.sql.DataSource) initContext.lookup(dsName);
            Connection conn   = ds.getConnection();
            Statement  stmt   = conn.createStatement();
            int        nRows  = stmt.executeUpdate(query.toString());

            stmt.close();
            conn.close();
        } catch(Exception ex) {
            System.out.println("- Could not interact with the database");
            System.out.println("Exception: " + ex.toString());
        }

        request.setAttribute("message", theMessage);
        response.setContentType("text/html");

        RequestDispatcher dispatcher =
            getServletContext().getRequestDispatcher("/GreeterDBView.jsp");

        dispatcher.include(request, response);

        return;
    }

    /**
      * The doPost method of the servlet. Handles all http POST request.
          * Required by the servlet specification.
          * @exception throws ServletException and IOException.
          */
    public void doPost(
            HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
        doGet(request, response);
    }

    public String getGreeting() {

        String   message     = null;
        Calendar calendar    = new GregorianCalendar();
        int      currentHour = calendar.get(Calendar.HOUR_OF_DAY);

        if(currentHour < 12) {
            message = "morning";
        } else {
            if((currentHour >= 12)
                    && (calendar.get(Calendar.HOUR_OF_DAY) < 18)) {
                message = "afternoon";
            } else {
                message = "evening";
            }
        }

        return message;
    }
}