package org.jboss.cache.options;

import junit.framework.TestCase;
import org.jboss.cache.DummyTransactionManagerLookup;
import org.jboss.cache.Fqn;
import org.jboss.cache.TreeCache;
import org.jboss.cache.config.Option;

import javax.transaction.TransactionManager;

/**
 * To test memory leak reported in http://www.jboss.com/index.html?module=bb&op=viewtopic&p=4112143#4112143
 *
 * @author Manik Surtani (<a href="mailto:manik@jboss.org">manik@jboss.org</a>)
 */
public class OptimisticMemLeakTest extends TestCase
{
   private TreeCache cache;
   private TransactionManager tm;
   private Fqn fqn = Fqn.fromString("/a/b/c");
   private Fqn fqn1 = Fqn.fromString("/c/d/e");
   private String key = "key", value = "value";

   protected void tearDown()
   {
      cache.stop();
   }

   protected void setUp() throws Exception
   {
      cache = new TreeCache();
      cache.setNodeLockingScheme("OPTIMISTIC");
      cache.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
      cache.startService();
      tm = cache.getTransactionManager();
   }

   public void testLeakWithFailSilently() throws Exception
   {
      tm.begin();
      Option option = new Option();
      option.setFailSilently(true);
      cache.put(fqn, key, value, option);
      tm.commit();

      int gtxCnt = cache.getTransactionTable().getNumGlobalTransactions();
      int txCnt = cache.getTransactionTable().getNumLocalTransactions();
      assertEquals("Global transaction count is > 0", 0, gtxCnt);
      assertEquals("Local transaction count is > 0", 0, txCnt);
      
      tm.begin();
      cache.put(fqn1, key, value);
      option = new Option();
      option.setFailSilently(true);
      cache.put(fqn, key, value, option);
      tm.commit();

      gtxCnt = cache.getTransactionTable().getNumGlobalTransactions();
      txCnt = cache.getTransactionTable().getNumLocalTransactions();
      assertEquals("Global transaction count is > 0", 0, gtxCnt);
      assertEquals("Local transaction count is > 0", 0, txCnt);
      
      tm.begin();
      option = new Option();
      option.setFailSilently(true);
      cache.put(fqn, key, value, option);
      cache.put(fqn1, key, value);
      tm.commit();

      gtxCnt = cache.getTransactionTable().getNumGlobalTransactions();
      txCnt = cache.getTransactionTable().getNumLocalTransactions();
      assertEquals("Global transaction count is > 0", 0, gtxCnt);
      assertEquals("Local transaction count is > 0", 0, txCnt);
      
      tm.begin();
      cache.put(fqn1, key, value);
      option = new Option();
      option.setFailSilently(true);
      cache.put(fqn, key, value, option);
      cache.put(fqn1, key, value);
      tm.commit();

      gtxCnt = cache.getTransactionTable().getNumGlobalTransactions();
      txCnt = cache.getTransactionTable().getNumLocalTransactions();
      assertEquals("Global transaction count is > 0", 0, gtxCnt);
      assertEquals("Local transaction count is > 0", 0, txCnt);
   }
}
