package org.jboss.cache.transaction;



import EDU.oswego.cs.dl.util.concurrent.Latch;
import junit.framework.AssertionFailedError;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jboss.cache.DummyTransactionManagerLookup;
import org.jboss.cache.Fqn;
import org.jboss.cache.TreeCache;
import org.jboss.cache.lock.IsolationLevel;
import org.jboss.cache.lock.TimeoutException;

import javax.transaction.NotSupportedException;
import javax.transaction.SystemException;
import javax.transaction.Transaction;



/**
 * Tests READ_COMMITED isolation level.
 *
 * @author <a href="mailto:ovidiu@jboss.org">Ovidiu Feodorov</a>
 *
 * @version $Id: IsolationLevelSerializableTest.java 3004 2006-11-22 04:02:15Z bstansberry $
 */

public class IsolationLevelSerializableTest extends TestCase
{

   private TreeCache cache = null;
   private final Fqn FQN = Fqn.fromString("/a");
   private final String KEY = "key";
   private final String VALUE = "value";

   private volatile boolean writerFailed;
   private volatile boolean readerFailed;
   private volatile AssertionFailedError writerError;
   private volatile AssertionFailedError readerError;

   protected void setUp() throws Exception
   {
      super.setUp();

      writerFailed = false;
      readerFailed = false;

      writerError = null;
      readerError = null;
      
      cache = new TreeCache();
      cache.setCacheMode(TreeCache.LOCAL);
      cache.setIsolationLevel(IsolationLevel.SERIALIZABLE);
      cache.setTransactionManagerLookupClass(DummyTransactionManagerLookup.class.getName());
      cache.setLockAcquisitionTimeout(1000);
      cache.startService();
   }


   protected void tearDown() throws Exception
   {
      super.tearDown();

      cache.stopService();
      cache.destroyService();
      cache=null;
   }
   
   /**
    * Test creates a cache node then starts a separate thread that removes
    * the node inside a tx. Test confirms that the removal cannot be seen
    * before the test commits.
    * 
    * @throws Exception
    */
   public void testNodeRemoved() throws Exception
   {
      final Latch readerCanRead = new Latch();
      final Latch readerDone = new Latch();
      final Latch writerDone = new Latch();

      cache.put(FQN, KEY, VALUE);
      assertEquals(VALUE, cache.get(FQN, KEY));

      // start a writer thread and a transaction

      Thread writerThread = new Thread(new Runnable()
      {
         public void run()
         {
            try
            {
               Transaction tx = startTransaction();

               // change VALUE in a transaction
               cache.remove(FQN);

               // notify the reading thread
               readerCanRead.release();
               
               readerDone.acquire();
               
               tx.commit();
            }
            catch (AssertionFailedError e)
            {
               writerError = e;
            }
            catch(Throwable t)
            {
               t.printStackTrace();
               writerFailed = true;
            }
            finally
            {
               System.out.println("writer thread exits");
               readerCanRead.release();
               writerDone.release();
            }
         }
      }, "WRITER");
      writerThread.start();
      
      try
      {
         // wait until the writer thread changes the value in a transaction, 
         // but it did not yet commit or roll back.
         readerCanRead.acquire();

         // I shouldn't be able to see the "dirty" value
         assertEquals("2nd thread cannot see uncommitted changes",
                       VALUE, cache.get(FQN, KEY));
      }
      catch (TimeoutException t)
      {
         // ignore, this is good
      }
      finally
      {               
         System.out.println("reader thread exits");
         readerDone.release();
      }

      // wait for the writer to finish
      writerDone.acquire();

      assertNull("Node was removed", cache.get(FQN));

      // If any assertion failed, throw on the AssertionFailedError
      
      if (writerError != null)
      {
         throw writerError;
      }

      if (writerFailed)
      {
         fail("The writer thread exited incorrectly. Watch the log for previous stack traces");
      }
      
   }

   private Transaction startTransaction() throws SystemException, NotSupportedException
   {
      DummyTransactionManager mgr=DummyTransactionManager.getInstance();
      mgr.begin();
      return mgr.getTransaction();
   }

   public static Test suite() {

      return new TestSuite(IsolationLevelSerializableTest.class);

   }

}

