/*
 *
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */
package org.apache.taglibs.dbtags.statement;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
import java.io.IOException;

import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTagSupport;

/**
 * <p>JSP tag statement.  According to the TEI, the java.sql.Statement
 * object specified in the "id" attribute is available within the scope
 * of the statement tags.  </p>
 *
 * <p>JSP Tag Lib Descriptor
 * <pre>
 * &lt;name>statement&lt;/name>
 * &lt;tagclass>org.apache.taglibs.dbtags.statement.StatementImplTag&lt;/tagclass>
 * &lt;teiclass>org.apache.taglibs.dbtags.connection.StatementTEI&lt;/teiclass>
 * &lt;bodycontent>JSP&lt;/bodycontent>
 * &lt;info>JSP tag statement, uses the enclosed query and resultset/execute
 * tags to perform a database operation.&lt;/info>
 *   &lt;attribute>
 *     &lt;name>id&lt;/name>
 *     &lt;required>true&lt;/required>
 *     &lt;rtexprvalue>false&lt;/rtexprvalue>
 *   &lt;/attribute>
 *   &lt;attribute>
 *     &lt;name>conn&lt;/name>
 *     &lt;required>true&lt;/required>
 *     &lt;rtexprvalue>false&lt;/rtexprvalue>
 *   &lt;/attribute>
 * </pre>
 *
 * @author Morgan Delagrange
 */
public class StatementImplTag extends BodyTagSupport implements StatementTag{

  private Statement _statement = null;
  private String _query        = null;
  private String _connId       = null;
  private int _rowCount = -1;

  // all the public methods are Javadoced
  // in their interfaces

  public void setQuery(String query) {
    _query = query;
  }

  public void setConn(String connId) {
    _connId = connId;
  }

  public void executeUpdate() throws SQLException {
    _statement.executeUpdate(_query);
  }

  public ResultSet executeQuery() throws SQLException {
    return _statement.executeQuery(_query);
  }

  public int getTotalRowCount() {
    return _rowCount;
  }

  public void setTotalRowCount(int rowCount) {
    _rowCount = rowCount;
  }

  public int doStartTag() throws JspTagException {
    if (_connId == null) {
      throw new JspTagException("Connection id has not been set.");
    }

    try {
      Connection conn = (Connection)pageContext.findAttribute(_connId);
      if(conn == null) {
        throw new JspTagException("There is no such connection'"+_connId+"'");
      }
      _statement = createStatement ( conn );
      pageContext.setAttribute(getId(), _statement);
    } catch (SQLException e) {
      throw new JspTagException(e.toString());
    }

    return EVAL_BODY_TAG;
  }


  /**
   * Let subclass redefine how to create the statement
   */
  protected Statement createStatement ( Connection theConnection ) throws SQLException
  {
    return theConnection.createStatement();
  }


  public int doAfterBody() throws JspTagException
  {
      // Automatically trim the contents of this tag
      try {
        getPreviousOut().write(getBodyContent().getString().trim());
      } catch (IOException e) {
        throw new JspTagException(e.toString());
      }
      return EVAL_PAGE;
  }

  public int doEndTag() {
    pageContext.removeAttribute(getId());

    try {
      _statement.close();
    } catch (SQLException e) {
      // it's not a fatal error if we can't close the statement
      e.printStackTrace();
    }

    return EVAL_PAGE;
  }

  public void release() {
    _connId=null;
    _statement = null;
    _query=null;
  }

}
