package org.jboss.cache.transaction;

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

import javax.transaction.Transaction;
import javax.transaction.TransactionManager;

/**
 * Based on a contribution by Owen Taylor
 * @author otaylor@redhat.com
 * @author Manik Surtani (manik@jboss.org)
 */
public class SuspendTxTest extends TestCase {
   TreeCache cache;
   TransactionManager mgr;

   protected void setUp() throws Exception {
      super.setUp();
      cache=new TreeCache();
      cache.setCacheMode("local");
      cache.setTransactionManagerLookupClass("org.jboss.cache.DummyTransactionManagerLookup");
      cache.createService();
      cache.startService();
      mgr = cache.getTransactionManager();
   }

   protected void tearDown() throws Exception {
      super.tearDown();
      cache.stopService();
      cache.destroyService();
      if (mgr.getTransaction() != null)
      {
            mgr.rollback();
      }
      mgr = null;
   }

   /**
    * Tests that locks created when a transaction is suspended are independent
    * from the transaction.
    */
   public void testSuspendedLocks() throws Exception {

      // create /one first
      cache.put("/one", null);
      cache.put("/a", null);

      mgr.begin();
	   
      cache.put("/one/two", "key1", "val1");
      int numLocksBefore = cache.getNumberOfLocksHeld();
      
      Transaction tx = mgr.suspend();

      cache.put("/a/b", "key1", "val1");
      mgr.resume(tx);
      
      assertEquals(numLocksBefore, cache.getNumberOfLocksHeld());
   }

   /**
    * Tests that locks created when a transaction is suspended are independent
    * from the transaction.
    */
   public void testSuspendedUsingOptionsLocks() throws Exception {
      mgr.begin();

      cache.put("/one/two", "key1", "val1");
      int numLocksBefore = cache.getNumberOfLocksHeld();

      Option o = new Option();
      o.setFailSilently(true); // will cause any current txs to be suspended for the duration of this call.

      cache.put(Fqn.fromString("/a/b"), "key1", "val1", o);

      assertEquals(numLocksBefore, cache.getNumberOfLocksHeld());
   }



   public static Test suite() {
      return new TestSuite(SuspendTxTest.class);
   }

   public static void main(String[] args) {
      junit.textui.TestRunner.run(suite());
   }

}
