package weblogic.taglib.sql;

import java.io.*;
import java.sql.*;
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 ResultsTag extends BodyTagSupport {
  
  String rName;
  ResultSet results;
  
  public void setFrom_query(String r) { rName = r; }
  public String getFrom_query() { return rName; }
  
  public int doStartTag() throws javax.servlet.jsp.JspException {
    results = (ResultSet)pageContext.getAttribute(rName);
    
    if (results != null) {
      try {
        if (results.next())
        {
          // Instruct the JSP engine to evaluate the tag body.
          return EVAL_BODY_TAG;
        } 
        else 
        {
          // The ResultSet was empty, so we 
          // instruct the JSP engine to skip the tag body. 
          return BodyTag.SKIP_BODY;
        }
      } catch(Exception e) {
        throw new JspException("Failed to use ResultSet. Exception thrown"+e);
      }
    }
    
    return SKIP_BODY;
  }
  
  public int doAfterBody() throws javax.servlet.jsp.JspException {
    try {
      if (results.next()) {
        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
        getPreviousOut().print(getBodyContent().getString());
        //getBodyContent().writeOut(getPreviousOut());
        return SKIP_BODY;
      } 
    } catch (Exception ioe) {
      throw new JspTagException(ioe.toString());
      
    }
  }
  
}  
