package org.jboss.cache.loader;

import org.jboss.cache.Cache;
import org.jboss.cache.CacheSPI;
import org.jboss.cache.DefaultCacheFactory;
import org.jboss.cache.Fqn;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.sql.Connection;

/**
 * To test the closing of JDBC connections
 */
@Test(groups = "functional")
public class JDBCCacheLoaderConnectionTest extends AbstractCacheLoaderTestBase
{
   private Cache cache;

   @BeforeMethod
   public void setUp() throws Exception
   {
      String props = "               cache.jdbc.table.name=jbosscache_engine_cache\n" +
            "                        cache.jdbc.table.create=true\n" +
            "                        cache.jdbc.table.drop=true\n" +
            "                        cache.jdbc.table.primarykey=jbosscache_engine_cache_pk\n" +
            "                        cache.jdbc.fqn.column=fqn\n" +
            "                        cache.jdbc.fqn.type=varchar(255)\n" +
            "                        cache.jdbc.node.column=node\n" +
            "                        cache.jdbc.node.type=blob\n" +
            "                        cache.jdbc.parent.column=parent\n" +
            "                        cache.jdbc.sql-concat=1 || 2\n" +
            "                        cache.jdbc.driver=org.apache.derby.jdbc.EmbeddedDriver\n" +
            "                        cache.jdbc.url=jdbc:derby:jbossdb;create=true\n" +
            "                        cache.jdbc.user=user1\n" +
            "                        cache.jdbc.password=user1";

      cache = new DefaultCacheFactory().createCache(false);
      cache.getConfiguration().setCacheLoaderConfig(getSingleCacheLoaderConfig("", JDBCCacheLoader.class.getName(), props, false, false, true, false));
      cache.start();
   }

   @AfterMethod
   public void tearDown()
   {
      cache.stop();
   }

   public void testConnectionRelease() throws Exception
   {
      cache.removeNode(Fqn.fromString("C"));
      for (int i = 0; i < 100; i++)
      {
         cache.put(Fqn.fromElements("C", Integer.toString(i)), "Blah", Integer.toString(i));
         System.out.println("added " + i + " dummy node to Jboss cache.");
      }

      assertConnectionsClosed();
   }

   private void assertConnectionsClosed() throws Exception
   {
      JDBCCacheLoader loader = (JDBCCacheLoader) ((CacheSPI) cache).getCacheLoaderManager().getCacheLoader();
      NonManagedConnectionFactory cf = (NonManagedConnectionFactory) loader.cf;
      Connection conn = cf.connection.get();
      if (conn != null)
      {
         // make sure it is closed/released!
         assert conn.isClosed();
      }
   }
}
