import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class RollYourOwnSecurityServlet extends HttpServlet {
  
  public void init(ServletConfig config)
    throws ServletException {

    super.init(config);
  }

  private boolean validateUser(String id, String password) {

    // This is a dummy method.  If you really implement
    // a method like this, you will need to store id/password
    // combinations somewhere else
    return true;
  }
  
  //Process the HTTP Get request
  public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {

    // Get the current session
    HttpSession session = request.getSession(true);
    // Get the id stored in the session after approval
    String id = (String)session.getValue("id");

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head><title>Roll Your Own</title></head>");
    out.println("<body>");

    out.println("Hello " + id + " how can we help you today?");
    
    out.println("</body></html>");
    out.close();
  }

  //Process the HTTP Post request
  public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {

    // Get the id/password combination from the request
    String id = request.getParameter("id");
    String password = request.getParameter("password");

    HttpSession session = null;

    // Check to see if this is a valid id/password combination.
    boolean valid = validateUser(id, password);

    // If it is valid, get the session
    // and add the id for future transactions
    if ( valid == true ) {

      session = request.getSession(true);
      session.putValue("id", id);
    }

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<html>");
    out.println("<head><title>Roll Your Own</title></head>");
    out.println("<body>");


    if ( valid == true ) {

      // Successful validation, redirect the to the GET method
      // of this servlet
      response.sendRedirect("/servlet/" +
        "RollYourOwnSecurityServlet");
    }
    else {

      out.println("We don't know who you are please leave!");
    }
    out.println("</body></html>");
    out.close();
  }

  //Get Servlet information
  public String getServletInfo() {
  
    return "RollYourOwnSecurityServlet Information";
  }
}
 