package weblogic.taglib.sql;

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

public class QueryTag extends BodyTagSupport {
  
  Connection conn;
  Statement stat;
  String sql;
  
  public void setSql(String qStr) { sql = qStr; }
  public String getSql() { return sql; }
  
  public int doStartTag() throws javax.servlet.jsp.JspException {
    
    if (id == null) {
      throw new JspException("id attribure for ResultSet was not defined");
    }
    
    try {
      ConnectionTag connTag = (ConnectionTag)
           findAncestorWithClass(this, 
                                 Class.forName("weblogic.taglib.sql.ConnectionTag"));
      if (connTag != null) {
        conn = connTag.getConnection();
      }
    } catch(ClassNotFoundException cnfe) {
      throw new JspException("Query tag connection attribute not set AND not nested within connection tag");
    }
    
    if (conn == null) {
      throw new JspException("This query tag must be nested within a connection tag");
    }
    
    try {
      stat = conn.createStatement();
      
      ResultSet results = stat.executeQuery(sql);
      pageContext.setAttribute(id, results);
      return EVAL_BODY_TAG;
    } catch (Exception e) {
      throw new JspException("Failed to execute query in QueryTag. Exception caught: "+e);
    } 
  }
  
  public int doAfterBody() throws javax.servlet.jsp.JspException
  {
    try {
      getBodyContent().writeOut(getPreviousOut());
    } catch(java.io.IOException ioe) {
      throw new JspException("Failed to write body content");
    }
    return SKIP_BODY;
  }
  
  public int doEndTag() throws javax.servlet.jsp.JspException
  {
    if (stat != null) {
      try {
        stat.close();
      } catch(Exception e) {
        throw new JspException("Failed to close statement");
      }
    }
    return EVAL_PAGE;
  }
  
  public void release() {
    super.release();
    stat = null;
    conn = null;
    sql = null;
  }
}
