package moreservlets;

import javax.servlet.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import java.text.*;

/** Tag that outputs a Web-app-specific hit count.
 *  For boats example.
 *  <P>
 *  The actual name of the tag is not defined here;
 *  that is given by the Tag Library Descriptor (TLD)
 *  file that is referenced by the taglib directive
 *  in the JSP file.
 *  <P>
 *  Taken from More Servlets and JavaServer Pages
 *  from Prentice Hall and Sun Microsystems Press,
 *  http://www.moreservlets.com/.
 *  &copy; 2002 Marty Hall; may be freely used or adapted.
 */

public class CounterTag extends TagSupport {
  public int doStartTag() {
    try {
      ServletContext application =
        pageContext.getServletContext();
      Count count = (Count)application.getAttribute("count");
      if (count == null) {
        count = new Count();
        application.setAttribute("count", count);
      }
      DateFormat formatter =
        DateFormat.getDateInstance(DateFormat.MEDIUM);
      JspWriter out = pageContext.getOut();
      out.println("<BR CLEAR=\"ALL\"><BR><HR>");
      out.println("This site has received " +
                  count.getCount() + " hits since " +
                  formatter.format(count.getStartDate()) +
                  ".");
      count.incrementCount();
    } catch(IOException ioe) {
      System.out.println("Error in CounterTag: " + ioe);
    }
    return(SKIP_BODY);
  }
}
