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

import org.jboss.cache.TreeCache;
import org.jboss.cache.interceptors.CacheStoreInterceptor;
import org.jboss.cache.interceptors.Interceptor;

import java.util.Iterator;

/**
 * See http://www.jboss.com/index.html?module=bb&op=viewtopic&p=3919374#3919374
 *
 * @author <a href="mailto:manik@jboss.org">Manik Surtani (manik@jboss.org)</a>
 */
public class SharedCacheLoaderTest extends AbstractCacheLoaderTestBase
{
    private TreeCache cache1, cache2;
    private DummyCacheLoader dummyCacheLoader;

    protected void setUp() throws Exception
    {
        if (cache1 != null || cache2 != null) tearDown();

        // set up 2 instances of TreeCache with shared CacheLoaders.
        cache1 = new TreeCache();
        cache2 = new TreeCache();

        cache1.setCacheMode(TreeCache.REPL_SYNC);
        cache2.setCacheMode(TreeCache.REPL_SYNC);

        cache1.setCacheLoaderConfiguration(getSingleCacheLoaderConfig("", DummyCacheLoader.class.getName(), "", false, false, true));
        cache2.setCacheLoaderConfiguration(getSingleCacheLoaderConfig("", DummyCacheLoader.class.getName(), "", false, false, true));

        cache1.startService();
        cache2.startService();

        // force setting up the same cache loader class
        dummyCacheLoader = new DummyCacheLoader();

        cache1.setCacheLoader(dummyCacheLoader);
        cache2.setCacheLoader(dummyCacheLoader);
        findCacheStoreInterceptor(cache1).setCache(cache1);
        findCacheStoreInterceptor(cache2).setCache(cache2);
    }

    protected CacheStoreInterceptor findCacheStoreInterceptor(TreeCache cache)
    {
        Iterator ints = cache.getInterceptors().iterator();
        CacheStoreInterceptor csi = null;
        while (ints.hasNext())
        {
            Interceptor i = (Interceptor) ints.next();
            if (i instanceof CacheStoreInterceptor)
            {
                csi = (CacheStoreInterceptor) i;
                break;
            }
        }
        return csi;
    }

    protected void tearDown()
    {
        if (cache1 != null) cache1.stopService();
        if (cache2 != null) cache2.stopService();
        cache1 = null;
        cache2 = null;
    }

    public void testReplicationWithSharedCL() throws Exception
    {
        cache1.put("/test", "one", "two");

        // should have replicated
        assertEquals("two", cache1.get("/test", "one"));
        assertEquals("two", cache2.get("/test", "one"));

        // only a single put() should have happened on the cache loader though.
        assertEquals(1, dummyCacheLoader.getPutCount());
    }
}
