/*
 * Created on 17-Feb-2005
 *
 *
 *
 */
package org.jboss.cache.optimistic;

import org.jboss.cache.*;
import org.jboss.cache.interceptors.Interceptor;
import org.jboss.cache.interceptors.OptimisticCreateIfNotExistsInterceptor;
import org.jboss.cache.interceptors.OptimisticLockingInterceptor;
import org.jboss.cache.interceptors.OptimisticNodeInterceptor;
import org.jboss.cache.loader.SamplePojo;
import org.jboss.cache.lock.IdentityLock;
import org.jboss.cache.marshall.MethodCallFactory;
import org.jboss.cache.marshall.MethodDeclarations;
import org.jboss.cache.transaction.DummyTransactionManager;
import org.jgroups.blocks.MethodCall;

import javax.transaction.Transaction;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author xenephon
 */
public class OpLockingInterceptorTest extends AbstractOptimisticTestCase
{


    /**
     * @param name
     */
    public OpLockingInterceptorTest(String name)
    {
        super(name);

    }

    public void testTransactionPrepareMethod() throws Exception
    {

        TestListener listener = new TestListener();
        final TreeCache cache = createCacheWithListener(listener);

        Interceptor lockingInterceptor = new OptimisticLockingInterceptor();
        lockingInterceptor.setCache(cache);
        Interceptor interceptor = new OptimisticCreateIfNotExistsInterceptor();
        interceptor.setCache(cache);
        Interceptor nodeInterceptor = new OptimisticNodeInterceptor();
        nodeInterceptor.setCache(cache);
        MockInterceptor dummy = new MockInterceptor();
        dummy.setCache(cache);
        lockingInterceptor.setNext(interceptor);
        interceptor.setNext(nodeInterceptor);
        nodeInterceptor.setNext(dummy);

        cache.setInterceptorChain(lockingInterceptor);

//		 first set up a node with a pojo
        DummyTransactionManager mgr = DummyTransactionManager.getInstance();
        mgr.begin();
        Transaction tx = mgr.getTransaction();

        // inject InvocationContext
        cache.getInvocationContext().setTransaction(tx);
        cache.getInvocationContext().setGlobalTransaction(cache.getCurrentTransaction(tx));

        SamplePojo pojo = new SamplePojo(21, "test");
        Map temp = new HashMap();
        temp.put("key1", pojo);
        cache.put("/one/two", temp);

        assertEquals(null, dummy.getCalled());
        TransactionTable table = cache.getTransactionTable();

        GlobalTransaction gtx = table.get(tx);

        OptimisticTransactionEntry entry = (OptimisticTransactionEntry) table.get(gtx);

        TransactionWorkspace workspace = entry.getTransactionWorkSpace();

        /*GlobalTransaction.class,
        List.class,
        Address.class,
        boolean.class*/

        assertEquals(3, workspace.getNodes().size());
        assertNotNull(workspace.getNode(Fqn.fromString("/one/two")));
        assertEquals(pojo, workspace.getNode(Fqn.fromString("/one/two")).get("key1"));
        assertEquals(1, workspace.getNode(Fqn.fromString("/one/two")).getMergedData().size());
        assertTrue(entry.getLocks().isEmpty());
        assertEquals(1, entry.getModifications().size());
        assertTrue(!cache.exists("/one/two"));
        assertEquals(null, dummy.getCalled());

        //now let us do a prepare
        MethodCall prepareMethod = MethodCallFactory.create(MethodDeclarations.optimisticPrepareMethod, new Object[]{gtx, entry.getModifications(), gtx.getAddress(), Boolean.FALSE});
        try
        {
            cache._replicate(prepareMethod);
        }
        catch (Throwable t)
        {

        }


        assertEquals(3, workspace.getNodes().size());
        assertNotNull(workspace.getNode(Fqn.fromString("/one/two")));
        assertEquals(pojo, workspace.getNode(Fqn.fromString("/one/two")).get("key1"));
        assertEquals(1, workspace.getNode(Fqn.fromString("/one/two")).getMergedData().size());
        assertEquals(3, entry.getLocks().size());
        for (Iterator it = entry.getLocks().iterator(); it.hasNext();)
        {
            IdentityLock lock = (IdentityLock) it.next();
            assertTrue(lock.isWriteLocked());
            assertEquals(gtx, lock.getWriterOwner());
        }
        assertEquals(1, entry.getModifications().size());
        assertTrue(!cache.exists("/one/two"));
        //assertEquals(null,dummy.getCalled());


        mgr.commit();

        cache.stopService();

    }

    public void testTransactionCommitMethod() throws Exception
    {

        TestListener listener = new TestListener();
        final TreeCache cache = createCacheWithListener(listener);

        Interceptor lockingInterceptor = new OptimisticLockingInterceptor();
        lockingInterceptor.setCache(cache);
        Interceptor interceptor = new OptimisticCreateIfNotExistsInterceptor();
        interceptor.setCache(cache);
        Interceptor nodeInterceptor = new OptimisticNodeInterceptor();
        nodeInterceptor.setCache(cache);
        MockInterceptor dummy = new MockInterceptor();
        dummy.setCache(cache);
        lockingInterceptor.setNext(interceptor);
        interceptor.setNext(nodeInterceptor);
        nodeInterceptor.setNext(dummy);

        cache.setInterceptorChain(lockingInterceptor);

//		 first set up a node with a pojo
        DummyTransactionManager mgr = DummyTransactionManager.getInstance();
        mgr.begin();
        Transaction tx = mgr.getTransaction();

        // inject InvocationContext
        cache.getInvocationContext().setTransaction(tx);
        cache.getInvocationContext().setGlobalTransaction(cache.getCurrentTransaction(tx));

        SamplePojo pojo = new SamplePojo(21, "test");
        Map temp = new HashMap();
        temp.put("key1", pojo);
        cache.put("/one/two", temp);

        assertEquals(null, dummy.getCalled());
        TransactionTable table = cache.getTransactionTable();

        GlobalTransaction gtx = table.get(tx);

        OptimisticTransactionEntry entry = (OptimisticTransactionEntry) table.get(gtx);

        TransactionWorkspace workspace = entry.getTransactionWorkSpace();

        /*GlobalTransaction.class,
        List.class,
        Address.class,
        boolean.class*/

        assertEquals(3, workspace.getNodes().size());
        assertNotNull(workspace.getNode(Fqn.fromString("/one/two")));
        assertEquals(pojo, workspace.getNode(Fqn.fromString("/one/two")).get("key1"));
        assertEquals(1, workspace.getNode(Fqn.fromString("/one/two")).getMergedData().size());
        assertTrue(entry.getLocks().isEmpty());
        assertEquals(1, entry.getModifications().size());
        assertTrue(!cache.exists("/one/two"));
        assertEquals(null, dummy.getCalled());

        //now let us do a prepare
        MethodCall prepareMethod = MethodCallFactory.create(MethodDeclarations.optimisticPrepareMethod, new Object[]{gtx, entry.getModifications(), gtx.getAddress(), Boolean.FALSE});
        try
        {
            cache._replicate(prepareMethod);
        }
        catch (Throwable t)
        {

        }


        assertEquals(3, workspace.getNodes().size());
        assertNotNull(workspace.getNode(Fqn.fromString("/one/two")));
        assertEquals(pojo, workspace.getNode(Fqn.fromString("/one/two")).get("key1"));
        assertEquals(1, workspace.getNode(Fqn.fromString("/one/two")).getMergedData().size());
        assertEquals(3, entry.getLocks().size());
        for (Iterator it = entry.getLocks().iterator(); it.hasNext();)
        {
            IdentityLock lock = (IdentityLock) it.next();
            assertTrue(lock.isWriteLocked());
            assertEquals(gtx, lock.getWriterOwner());
        }
        assertEquals(1, entry.getModifications().size());
        assertTrue(!cache.exists("/one/two"));
        //assertEquals(null,dummy.getCalled());
        assertEquals(MethodDeclarations.optimisticPrepareMethod, dummy.getCalled());


        MethodCall commitMethod = MethodCallFactory.create(MethodDeclarations.commitMethod, new Object[]{gtx});
        try
        {
            cache._replicate(commitMethod);
        }
        catch (Throwable t)
        {
            fail();
        }
        assertEquals(3, entry.getLocks().size());
        for (Iterator it = entry.getLocks().iterator(); it.hasNext();)
        {
            IdentityLock lock = (IdentityLock) it.next();
            assertEquals(false, lock.isLocked());

        }
        //make sure the nodes and locks are the same order
        int i = 0;
        for (Iterator it = workspace.getNodes().values().iterator(); it.hasNext();)
        {
            DataNode node = ((WorkspaceNode) it.next()).getNode();
            assertEquals(node.getLock(), entry.getLocks().get(i));
            i++;
        }
        assertEquals(MethodDeclarations.commitMethod, dummy.getCalled());
        mgr.commit();

        cache.stopService();

    }

    public void testTransactionRollbackMethod() throws Exception
    {

        TestListener listener = new TestListener();
        final TreeCache cache = createCacheWithListener(listener);

        Interceptor lockingInterceptor = new OptimisticLockingInterceptor();
        lockingInterceptor.setCache(cache);
        Interceptor interceptor = new OptimisticCreateIfNotExistsInterceptor();
        interceptor.setCache(cache);
        Interceptor nodeInterceptor = new OptimisticNodeInterceptor();
        nodeInterceptor.setCache(cache);
        MockInterceptor dummy = new MockInterceptor();
        dummy.setCache(cache);
        lockingInterceptor.setNext(interceptor);
        interceptor.setNext(nodeInterceptor);
        nodeInterceptor.setNext(dummy);

        cache.setInterceptorChain(lockingInterceptor);

//		 first set up a node with a pojo
        DummyTransactionManager mgr = DummyTransactionManager.getInstance();
        mgr.begin();
        Transaction tx = mgr.getTransaction();

        // inject InvocationContext
        cache.getInvocationContext().setTransaction(tx);
        cache.getInvocationContext().setGlobalTransaction(cache.getCurrentTransaction(tx));

        SamplePojo pojo = new SamplePojo(21, "test");
        Map temp = new HashMap();
        temp.put("key1", pojo);
        cache.put("/one/two", temp);

        assertEquals(null, dummy.getCalled());
        TransactionTable table = cache.getTransactionTable();

        GlobalTransaction gtx = table.get(tx);

        OptimisticTransactionEntry entry = (OptimisticTransactionEntry) table.get(gtx);

        TransactionWorkspace workspace = entry.getTransactionWorkSpace();

        /*GlobalTransaction.class,
        List.class,
        Address.class,
        boolean.class*/

        assertEquals(3, workspace.getNodes().size());
        assertNotNull(workspace.getNode(Fqn.fromString("/one/two")));
        assertEquals(pojo, workspace.getNode(Fqn.fromString("/one/two")).get("key1"));
        assertEquals(1, workspace.getNode(Fqn.fromString("/one/two")).getMergedData().size());
        assertTrue(entry.getLocks().isEmpty());
        assertEquals(1, entry.getModifications().size());
        assertTrue(!cache.exists("/one/two"));
        assertEquals(null, dummy.getCalled());

        //now let us do a prepare
        MethodCall prepareMethod = MethodCallFactory.create(MethodDeclarations.optimisticPrepareMethod, new Object[]{gtx, entry.getModifications(), gtx.getAddress(), Boolean.FALSE});
        try
        {
            cache._replicate(prepareMethod);
        }
        catch (Throwable t)
        {

        }


        assertEquals(3, workspace.getNodes().size());
        assertNotNull(workspace.getNode(Fqn.fromString("/one/two")));
        assertEquals(pojo, workspace.getNode(Fqn.fromString("/one/two")).get("key1"));
        assertEquals(1, workspace.getNode(Fqn.fromString("/one/two")).getMergedData().size());
        assertEquals(3, entry.getLocks().size());
        for (Iterator it = entry.getLocks().iterator(); it.hasNext();)
        {
            IdentityLock lock = (IdentityLock) it.next();
            assertTrue(lock.isWriteLocked());
            assertEquals(gtx, lock.getWriterOwner());
        }
        assertEquals(1, entry.getModifications().size());
        assertTrue(!cache.exists("/one/two"));
        assertEquals(MethodDeclarations.optimisticPrepareMethod, dummy.getCalled());


        MethodCall rollbackMethod = MethodCallFactory.create(MethodDeclarations.rollbackMethod, new Object[]{gtx});
        try
        {
            cache._replicate(rollbackMethod);
        }
        catch (Throwable t)
        {
            fail();
        }
        assertEquals(3, entry.getLocks().size());
        for (Iterator it = entry.getLocks().iterator(); it.hasNext();)
        {
            IdentityLock lock = (IdentityLock) it.next();
            assertEquals(false, lock.isLocked());

        }
        //make sure the nodes and locks are the same order
        int i = 0;
        for (Iterator it = workspace.getNodes().values().iterator(); it.hasNext();)
        {
            DataNode node = ((WorkspaceNode) it.next()).getNode();
            assertEquals(node.getLock(), entry.getLocks().get(i));
            i++;
        }
        assertEquals(MethodDeclarations.rollbackMethod, dummy.getCalled());
        mgr.commit();

        cache.stopService();

    }

}
