package weblogic.taglib.sql;

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

public class ConnectionTag extends BodyTagSupport {
  
  private static final String DRIVER = "weblogic.jdbc.pool.Driver";
  private static final String POOLPREFIX = "jdbc:weblogic:pool:";
  
  Connection conn;
  String poolName = null;
  
  public void setPool_name(String name) { this.poolName = name; }
  public String getPool_name() { return poolName; }
  
  public Connection getConnection() { return conn; }
  
  public int doStartTag() throws javax.servlet.jsp.JspException {
    // Create a JDBC connection based on the JDBC Pool given by 
    // the dbUrl member variable - configured from the tag's
    // 'dbUrl' attribute. 
    if (poolName == null) {
      throw new JspException("poolName attribute not defined in connection tag");
    }
    try {
      Class.forName(DRIVER).newInstance();
      conn =
           DriverManager.getConnection(POOLPREFIX+poolName, null);
      return EVAL_BODY_TAG;
    } catch(Exception e) {
      throw new JspException("Failed to load JDBC driver: "+DRIVER);
    }
  }
  
  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 (conn != null) {
      try {
        conn.close();
      } catch(Exception e) {
        throw new JspException("Failed to close statement");
      }
    }
    return EVAL_PAGE;
  }

  public void release() {
    super.release();
    conn = null;
    poolName = null;
  }
}
