/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.test.jca.ejb;

import java.security.CodeSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.ejb.SessionBean;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import javax.ejb.EJBException;
import javax.ejb.SessionContext;

import org.jboss.resource.adapter.jdbc.WrappedConnection;
import org.jboss.ejb.plugins.cmp.jdbc.WrappedStatement;
import org.jboss.test.jca.jdbc.TestConnection;
import org.jboss.logging.Logger;

/**
 * JDBCStatementTestsConnectionSessionBean.java
 *
 *
 * Created: Fri Feb 14 15:01:38 2003
 *
 * @author <a href="mailto:d_jencks@users.sourceforge.net">David Jencks</a>
 * @version
 *
 * @ejb:bean   name="JDBCStatementTestsConnectionSession"
 *             jndi-name="JDBCStatementTestsConnectionSession"
 *             local-jndi-name="JDBCStatementTestsConnectionSessionLocal"
 *             view-type="both"
 *             type="Stateless"
 */

public class JDBCStatementTestsConnectionSessionBean implements SessionBean
{
   /** The serialVersionUID */
   private static final long serialVersionUID = -1677243200661191437L;
   
   private static final Logger log = Logger.getLogger(JDBCStatementTestsConnectionSessionBean.class);

   public JDBCStatementTestsConnectionSessionBean()
   {
   }

   /**
    * The <code>testConnectionObtainable</code> method gets
    * connections from the TestDriver after setting fail to true.
    * This causes the test sql to throw an exception when the
    * connection is retrieved from a pool, which closes the
    * connection, forcing the connectionmanager to get a new one.  We
    * check this by counting how many connections have been closed.
    *
    *
    * @ejb:interface-method
    */
   public void testConnectionObtainable()
   {
      try
      {
         DataSource ds = (DataSource)new InitialContext().lookup("java:StatementTestsConnectionDS");
         Connection c = ds.getConnection();
         WrappedConnection wc = (WrappedConnection)c;
         Connection uc = wc.getUnderlyingConnection();
         CodeSource cs1 = TestConnection.class.getProtectionDomain().getCodeSource();
         CodeSource cs2 = uc.getClass().getProtectionDomain().getCodeSource();
         log.debug("CS1: "+cs1);
         log.debug("CS2: "+cs2);
         TestConnection tc = (TestConnection) uc;
         c.close();
         tc.setFail(true);
         int closeCount1 = tc.getClosedCount();
         c = ds.getConnection();
         if (closeCount1 == tc.getClosedCount())
         {
            throw new EJBException("no connections closed!, closedCount: " + closeCount1);
         } // end of if ()
         c.close();
         for (int i = 0; i < 10; i++)
         {

            int closeCount = tc.getClosedCount();
            c = ds.getConnection();
            if (closeCount == tc.getClosedCount())
            {
               throw new EJBException("no connections closed! at iteration: " + i + ", closedCount: " + closeCount);
            } // end of if ()
            c.close();
         } // end of for ()

      }
      catch (SQLException e)
      {
         throw new EJBException(e);
      } // end of try-catch
      catch (NamingException e)
      {
         throw new EJBException(e);
      } // end of try-catch

   }

   /**
    * Test cached prepared statement gets reset
    *
    * @ejb:interface-method
    */
   public void testPreparedStatementReset()
   {
      Connection c = null;
      try
      {
         DataSource ds = (DataSource)new InitialContext().lookup("java:StatementTestsConnectionDS");
         c = ds.getConnection();
         PreparedStatement ps = c.prepareStatement("dummy");
         Statement s = getWrappedStatement(ps);

         int maxFieldSize = ps.getMaxFieldSize();
         int maxRows = ps.getMaxRows();
         int queryTimeout = ps.getQueryTimeout();
         int fetchDirection = ps.getFetchDirection();
         int fetchSize = ps.getFetchSize();

         ps.setMaxFieldSize(1);
         ps.setMaxRows(2);
         ps.setQueryTimeout(3);
         ps.setFetchDirection(ResultSet.FETCH_REVERSE);
         ps.setFetchSize(4);

         ps.close();

         ps = c.prepareStatement("dummy");

         if (s != getWrappedStatement(ps))
            throw new EJBException("No ps cache, expected=" + s + " actual = " + getWrappedStatement(ps));

         if (maxFieldSize != ps.getMaxFieldSize())
            throw new EJBException("maxFieldSize not reset, expected=" + maxFieldSize + " actual=" + ps.getMaxFieldSize());
         if (maxRows != ps.getMaxRows())
            throw new EJBException("maxRows not reset, expected=" + maxRows + " actual=" + ps.getMaxRows());
         if (queryTimeout != ps.getQueryTimeout())
            throw new EJBException("queryTimeout not reset, expected=" + queryTimeout + " actual=" + ps.getQueryTimeout());
         if (fetchDirection != ps.getFetchDirection())
            throw new EJBException("fetchDirection not reset, expected=" + fetchDirection + " actual=" + ps.getFetchDirection());
         if (fetchSize != ps.getFetchSize())
            throw new EJBException("fetchSize not reset, expected=" + fetchSize + " actual=" + ps.getFetchSize());

         ps.close();

      }
      catch (SQLException e)
      {
         e.printStackTrace();
         throw new EJBException(e);
      } // end of try-catch
      catch (NamingException e)
      {
         throw new EJBException(e);
      } // end of try-catch
      finally
      {
         try
         {
            c.close();
         }
         catch (Throwable ignored)
         {
         }
      }

   }

   public Statement getWrappedStatement(Statement s) throws SQLException
   {
      while (s instanceof WrappedStatement)
         s = ((WrappedStatement) s).getUnderlyingStatement();
      return s;
   }

   public void ejbCreate()
   {
   }

   public void ejbActivate()
   {
   }

   public void ejbPassivate()
   {
   }

   public void ejbRemove()
   {
   }

   public void setSessionContext(SessionContext ctx)
   {
   }

   public void unsetSessionContext()
   {
   }

}// JDBCStatementTestsConnectionSessionBean
