package examples.servlets;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
 * This simple servlet demonstrates how to create and retrieve a cookie, and
 * how to set a maximum age on a cookie. 
 * It displays how many times it has been visited by all clients since 
 * the server was started, and displays how many times each client has visited
 * successively within 10 seconds of each visit. 
   
 * <p> Compile the servlet using the following line:
 * <pre>    javac -d WEBLOGICHOME\classes CookieCounter.java</pre>
 * where <tt>WEBLOGICHOME\classes</tt> is in your WebLogic Server's classpath. 
 * 
 * <p> Copy the file "cookie.jpg" to 
 * 
 * <pre>doc_root/images/cookie.jpg</pre> 
 * 
 * Where <tt>doc_root</tt> is the document root of your WebLogic Server. This
 * is usually set to the "public_html" directory in your "myserver" directory. 
 * See <a href="../../admindocs/properties.html#documentroot">
 * Setting the document root</a> for more details. 
 * 
 * <p>Register the servlet in the <tt>weblogic.properties</tt> file by adding 
 * (or uncommenting) the following lines:
 * <pre>   
 *    weblogic.httpd.register.cookies=examples.servlets.CookieCounter
 * </pre>
 * 
 * <p> Start (or restart) the WebLogic Server, and use a web browser to visit 
 * the following URL: <b>http://localhost:7001/cookies</b>
 * 
 * <p>Although this is an unusually
 * short-lived cookie, you may easily see the cookie count up, then expire by
 * reloading the page several times, waiting more than 10 seconds, then 
 * reloading the page again. Try turning off cookies in your browser, the
 * servlet no longer works. For a failsafe way to handle non-cookie-friendly
 * web browsers, see the <b>SessionServlet</b> example. 
 *
 * @author Copyright (c) 1996-98 by WebLogic, Inc. All Rights Reserved.
 * @author Copyright (c) 1999-2000 by BEA Systems, Inc. All Rights Reserved.
 */
public class CookieCounter extends HttpServlet {
  private int pageCount = 0;

  /**
   * Initializes the servlet. Looks for the property "initial" to set the 
   * pageCount variable. 
   */
  public void init(ServletConfig config) throws ServletException  {
    super.init(config);
    String s = getInitParameter("initial");
    if (s == null)
      pageCount = 0;
    else
      pageCount = Integer.parseInt(s);
  }

  /**
   * Implements the service method of the servlet. 
   */
  public void service(HttpServletRequest req, HttpServletResponse res)
       throws IOException
  {
    boolean cookieFound = false;
    Cookie thisCookie = null;
    
    // We must set the content type before calling getWriter()
    res.setContentType("text/html");
    // Now we can call getWriter()
    PrintWriter out = res.getWriter();
    
    // Try to retrieve the cookie from the request.
    Cookie[] cookies = req.getCookies();
    for(int i=0; i < cookies.length; i++) {
      thisCookie = cookies[i];
      if (thisCookie.getName().equals("CookieCount")) {
        cookieFound = true;
        break;
      }
    }
    
    if (cookieFound == false) {
      // Create a new Cookie and set it's age. 
      thisCookie = new Cookie("CookieCount", "1");
      thisCookie.setMaxAge(60*1);
      // Add the new cookie to the response
      res.addCookie(thisCookie);
    }
    
    out.println("<html><head>\n" +
                "<title>Cookie Counter</title>\n" +
                "</head>\n" +
                "<body bgcolor=#ffffff> <font face=\"Comic Sans MS\" size+=4 color=red>" +
                "<center><h1>Cookie Counter</h1></center>");
    pageCount++;
    out.println("<p><img src=\"/images/cookie.jpg\" align=left>");
    out.println("<font color=blue>");
    out.println("<p><br><br><br>This page has been visited " + pageCount +
                (pageCount==1?" time":" times") + 
                " before.\n");
    
    // Display client specific count details
    if (cookieFound) {
      int cookieCount = Integer.parseInt(thisCookie.getValue());
      cookieCount++;
      // Set the new value of the cookie, and add it to the response
      thisCookie.setValue(String.valueOf(cookieCount));
      thisCookie.setMaxAge(10);
      res.addCookie(thisCookie);
      
      out.println("<p>You have visited this page " +
                  thisCookie.getValue() +
                  (cookieCount==1?" time":" times") +
                  " within the past 10 seconds.\n");
      
    } else {
      out.println("<p>Either you haven't visited this page recently, "+
                  "or your browser doesn't like cookies!\n");
    }
    out.println("</body></html>");
  }
}

