/*
 * JBoss, Home of Professional Open Source
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.cache.optimistic;

import org.jboss.cache.Fqn;
import org.jboss.cache.OptimisticTreeNode;
import org.jboss.cache.TreeCache;

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

/**
 *
 * @author <a href="mailto:manik@jboss.org">Manik Surtani (manik@jboss.org)</a>
 */
public class ConcurrentTransactionTest extends AbstractOptimisticTestCase
{
    private TreeCache cache;

    public ConcurrentTransactionTest(String name)
    {
        super(name);
    }

    public void setUp()
    {
        try
        {
            cache = createCache();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void tearDown()
    {
        if (cache != null)
        {
            cache.stopService();
            cache = null;
        }
    }

    public void testConcurrentTransactions() throws Exception
    {
        TransactionManager tm = cache.getTransactionManager();
        cache.put("/a/b/c/d", key, value);

        assertEquals(value, cache.get("/a/b/c/d", key));

        tm.begin();
        Transaction tx = tm.getTransaction();

        cache.put("/a/b/x/y", key, value);
        tm.suspend();

        // a number of random puts in unrelated sub nodes.
        cache.put("/a/b/c/d", key, value+value);
        cache.put("/a/b/c/e", key, value);
        cache.put("/a/b/c/f", key, value);
        cache.put("/a/b/c/g", key, value);

        assertEquals(value+value, cache.get("/a/b/c/d", key));
        assertEquals(value, cache.get("/a/b/c/e", key));
        assertEquals(value, cache.get("/a/b/c/f", key));
        assertEquals(value, cache.get("/a/b/c/g", key));

        tm.resume(tx);
        tx.commit();

        assertEquals(value, cache.get("/a/b/x/y", key));

        OptimisticTreeNode n = (OptimisticTreeNode) cache.get(Fqn.ROOT);
        System.out.println(n.getVersion());
    }
}
