package moreservlets;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

/** Summarizes information on sessions, the servlet
 *  context and cookies. Illustrates that sessions
 *  and the servlet context are separate for each Web app
 *  but that cookies are shared as long as their path is
 *  set appropriately.
 *  <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 ShowSharedInfo extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Shared Info";
    out.println(ServletUtilities.headWithTitle(title) +
                "<BODY BGCOLOR=\"#FDF5E6\">\n" +
                "<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
                "<UL>\n" +
                "  <LI>Session:");
    HttpSession session = request.getSession(true);
    Enumeration attributes = session.getAttributeNames();
    out.println(getAttributeList(attributes));
    out.println("  <LI>Current Servlet Context:");
    ServletContext application = getServletContext();
    attributes = application.getAttributeNames();
    out.println(getAttributeList(attributes));
    out.println("  <LI>Servlet Context of /shareTest1:");
    application = application.getContext("/shareTest1");
    attributes = application.getAttributeNames();
    out.println(getAttributeList(attributes));
    out.println("  <LI>Cookies:<UL>");
    Cookie[] cookies = request.getCookies();
    if ((cookies == null) || (cookies.length == 0)) {
      out.println("    <LI>No cookies found.");
    } else {
      Cookie cookie;
      for(int i=0; i<cookies.length; i++) {
        cookie = cookies[i];
        out.println("    <LI>" + cookie.getName());
      }
    }
    out.println("    </UL>\n" +
                "</UL>\n" +
                "</BODY></HTML>");
  }

  private String getAttributeList(Enumeration attributes) {
    StringBuffer list = new StringBuffer("  <UL>\n");
    if (!attributes.hasMoreElements()) {
      list.append("    <LI>No attributes found.");
    } else {
      while(attributes.hasMoreElements()) {
        list.append("    <LI>");
        list.append(attributes.nextElement());
        list.append("\n");
      }
    }
    list.append("  </UL>");
    return(list.toString());
  }
}
