/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.cache.loader;

import org.apache.derby.jdbc.EmbeddedXADataSource;
import org.jboss.cache.Fqn;
import org.jboss.cache.transaction.DummyTransactionManager;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameNotFoundException;
import java.util.Properties;

/**
 * This test runs cache loader tests using Database as the cache loader store.
 * The default test is configured using MySQL.
 * The server and database configuration is read from a properties file located at
 * /etc/cache-jdbc.properties.
 * <p/>
 * The appropriate JDBC driver (i.e mysql-connector-java-3.0.10-stable-bin.jar)
 * must be in the lib directory for this test to run successfuly
 *
 * @author <a href="hmesha@novell.com">Hany Mesha</a>
 * @version <tt>$Revision: 6072 $</tt>
 */
@Test(groups = {"functional"})
public class JDBCCacheLoaderDerbyDSTest
      extends CacheLoaderTestsBase
{
   private String old_factory = null;
   private final String FACTORY = "org.jboss.cache.transaction.DummyContextFactory";
   private final String JNDI_NAME = "java:/DerbyDS";

   protected void configureCache() throws Exception
   {
      old_factory = System.getProperty(Context.INITIAL_CONTEXT_FACTORY);
      System.setProperty(Context.INITIAL_CONTEXT_FACTORY, FACTORY);
      DummyTransactionManager.getInstance();

      Context context = new InitialContext();
      try
      {
         Object obj = context.lookup(JNDI_NAME);
         assertNull(JNDI_NAME + " not bound", obj);
      }
      catch (NameNotFoundException n)
      {
         // expected
      }

      Properties prop = new Properties();
      try
      {
         prop.load(this.getClass().getClassLoader().getResourceAsStream("cache-jdbc.properties"));
      }
      catch (Exception e)
      {
         System.out.println("Error loading jdbc properties ");
      }

      //MysqlDataSource ds = new MysqlDataSource();
      EmbeddedXADataSource ds = new EmbeddedXADataSource();
      ds.setDatabaseName("jbossdb");
      ds.setCreateDatabase("create");
      ds.setUser(prop.getProperty("cache.jdbc.user"));
      ds.setPassword(prop.getProperty("cache.jdbc.password"));


      String props = "cache.jdbc.datasource =" + JNDI_NAME + "\n" +
            "cache.jdbc.node.type=" + prop.getProperty("cache.jdbc.node.type") + "\n" +
            "cache.jdbc.sql-concat= 1 || 2";


      cache.getConfiguration().setCacheLoaderConfig(getSingleCacheLoaderConfig("", "org.jboss.cache.loader.JDBCCacheLoader", props, false, true, false));
      cache.create();


      context.bind(JNDI_NAME, ds);
      assertNotNull(JNDI_NAME + " bound", context.lookup(JNDI_NAME));
   }

   public void testLargeObject()
   {
      try
      {
         String key = "LargeObj";
         // create an object with size bigger than 4k (k=1024 bytes)
         StringBuilder text = new StringBuilder("LargeObject");
         while (text.toString().getBytes().length < (1024 * 100))
         {
            text.append(text);
         }
         String initialValue = text.toString();
         // insert it into the cache loader
         loader.remove(Fqn.fromString("/"));

         Object retVal = loader.put(FQN, key, initialValue);
         assertNull(retVal);
         addDelay();
         // load the object from the cache loader and validate it
         assertEquals(initialValue, (String) loader.get(FQN).get(key));
         // update the object and validate it
         String updatedValue = initialValue.concat(("UpdatedValue"));
         retVal = loader.put(FQN, key, updatedValue);
         assertEquals(initialValue, (String) retVal);
         assertEquals(updatedValue, (String) loader.get(FQN).get(key));
      }
      catch (Exception e)
      {
         fail(e.toString());
      }
   }

   public void testTransactionRollback() throws Exception
   {
      // no-op
   }

   public void testIntegratedTransactionRollback() throws Exception
   {
      // no-op
   }

   @AfterMethod(alwaysRun = true)
   public void tearDown() throws Exception
   {
      super.tearDown();
      Context ctx = new InitialContext();
      ctx.unbind(JNDI_NAME);
      if (old_factory != null)
      {
         System.setProperty(Context.INITIAL_CONTEXT_FACTORY, old_factory);
      }
      else
      {
         System.getProperties().remove(Context.INITIAL_CONTEXT_FACTORY);
      }
   }
}
