package weblogic.taglib.session;

import java.io.*;
import java.util.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

/**
 * This class defines a custom JSP tag that enumerates through
 * the contents of the current session. 
 */

public class ListTag extends BodyTagSupport {
  static final boolean debug = true;
  Enumeration names;
  HttpSession session;
  
  public int doStartTag() throws javax.servlet.jsp.JspException {
    // Get the session for the JSP page. The pageContext is our
    // link to everything we need to know about the JSP page. 
    session = pageContext.getSession();
    
    names = session.getAttributeNames();
    if (names.hasMoreElements())
    {
      // Retrieve the first name/value pair from the session.
      String name = (String)names.nextElement();
      String value = (String)session.getAttribute(name);
      // Make the name and value available as nested scripting variables
      // within the next evaluation of the body. 
      pageContext.setAttribute("name", name);
      pageContext.setAttribute("value", value);
      // Instruct the JSP engine to evaluate the tag body.
      return BodyTag.EVAL_BODY_TAG;
    } 
    else 
    {
      // Since no name/value pairs were found in the session, 
      // instruct the JSP engine to skip the tag body. 
      return BodyTag.SKIP_BODY;
    }
  }
  
  public int doAfterBody() throws javax.servlet.jsp.JspException {
    // Get the processed body content of the tag
    if (names.hasMoreElements()) {
      // Retrieve the next name/value pair from the session.
      String name = (String)names.nextElement();
      String value = (String)session.getAttribute(name);
      // Make the name and value available as nested scripting variables
      // within the next evaluation of the body. 
      pageContext.setAttribute("name", name);
      pageContext.setAttribute("value", value);
      
      return EVAL_BODY_TAG;
    }
    else {
      // Note that the bodyContent is progressively built up at each
      // iteration. We only print the entire evaluated body to the 
      // enclosing output stream on the final iteration
      try {
        getBodyContent().writeOut(getPreviousOut());
      } catch (IOException ioe) {
        throw new JspTagException(ioe.toString());
      }
      return SKIP_BODY;
    }
  }
}

