/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.cache.eviction;

import org.jboss.cache.CacheSPI;
import org.jboss.cache.DefaultCacheFactory;
import org.jboss.cache.util.TestingUtil;
import org.jboss.cache.factories.UnitTestCacheConfigurationFactory;
import org.jboss.cache.config.Configuration;
import org.jboss.cache.config.EvictionConfig;
import org.jboss.cache.config.EvictionRegionConfig;
import org.jboss.cache.lock.IsolationLevel;
import static org.testng.AssertJUnit.*;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.util.List;
import java.util.ArrayList;

/**
 * Unit tests for MRUPolicy.
 *
 * @author Daniel Huang (dhuang@jboss.org)
 * @version $Revision: 5906 $
 */
@Test(groups = {"functional"})
public class MRUPolicyTest
{
   CacheSPI<Object, Object> cache;
   int wakeupIntervalMillis = 0;
   final String ROOT_STR = "/test";
   Throwable t1_ex, t2_ex;
   final long DURATION = 10000;
   boolean isTrue;

   @BeforeMethod(alwaysRun = true)
   public void setUp() throws Exception
   {
      initCaches();
      wakeupIntervalMillis = cache.getConfiguration().getEvictionConfig().getWakeupIntervalSeconds() * 1000;
      log("wakeupInterval is " + wakeupIntervalMillis);
      if (wakeupIntervalMillis < 0)
      {
         fail("testEviction(): eviction thread wake up interval is illegal " + wakeupIntervalMillis);
      }

      t1_ex = t2_ex = null;
      isTrue = true;
   }

   @AfterMethod(alwaysRun = true)
   public void tearDown() throws Exception
   {
      cache.stop();
   }

   private void initCaches()
   {
      Configuration config = UnitTestCacheConfigurationFactory.createConfiguration(Configuration.CacheMode.LOCAL, true);
      EvictionConfig evConfig = config.getEvictionConfig();
      evConfig.setWakeupIntervalSeconds(3);
      evConfig.setDefaultEventQueueSize(200000);
      evConfig.setDefaultEvictionPolicyClass("org.jboss.cache.eviction.MRUPolicy");
      List<EvictionRegionConfig> evictionRegionConfigs = new ArrayList<EvictionRegionConfig>();
      evictionRegionConfigs.add(buildEvictionRegionConfig("_default_",100));
      evictionRegionConfigs.add(buildEvictionRegionConfig("/org/jboss/test/data",6));
      evConfig.setEvictionRegionConfigs(evictionRegionConfigs);

      config.setTransactionManagerLookupClass("org.jboss.cache.transaction.DummyTransactionManagerLookup");
      config.setIsolationLevel(IsolationLevel.SERIALIZABLE);
      cache = (CacheSPI)new DefaultCacheFactory().createCache(config);
   }

   private EvictionRegionConfig buildEvictionRegionConfig(String regionName, int maxNodes)
   {
      EvictionRegionConfig erc = new EvictionRegionConfig();
      erc.setRegionName(regionName);
      MRUConfiguration mruConfiguration = new MRUConfiguration();
      mruConfiguration.setMaxNodes(maxNodes);
      erc.setEvictionPolicyConfig(mruConfiguration);
      return erc;
   }

   public void testEviction() throws Exception
   {
      cache.put("/org/jboss/test/data/a", "/org/jboss/test/data/a", "/org/jboss/test/data/a");
      cache.put("/org/jboss/test/data/b", "/org/jboss/test/data/b", "/org/jboss/test/data/b");
      cache.put("/org/jboss/test/data/c", "/org/jboss/test/data/c", "/org/jboss/test/data/c");
      cache.put("/org/jboss/test/data/d", "/org/jboss/test/data/d", "/org/jboss/test/data/d");
      cache.put("/org/jboss/test/data/e", "/org/jboss/test/data/e", "/org/jboss/test/data/e");

      TestingUtil.sleepThread(wakeupIntervalMillis + 500);

      cache.put("/org/jboss/test/data/f", "/org/jboss/test/data/f", "/org/jboss/test/data/f");
      cache.put("/org/jboss/test/data/g", "/org/jboss/test/data/g", "/org/jboss/test/data/g");
      cache.put("/org/jboss/test/data/h", "/org/jboss/test/data/h", "/org/jboss/test/data/h");
      assertNotNull(cache.get("/org/jboss/test/data/a", "/org/jboss/test/data/a"));
      assertNotNull(cache.get("/org/jboss/test/data/b", "/org/jboss/test/data/b"));

      TestingUtil.sleepThread(wakeupIntervalMillis + 500);

      assertNull(cache.get("/org/jboss/test/data/a", "/org/jboss/test/data/a"));
      assertNull(cache.get("/org/jboss/test/data/b", "/org/jboss/test/data/b"));
   }

   public void testNodeRemoved() throws Exception
   {
      cache.put("/org/jboss/test/data/a", "/org/jboss/test/data/a", "/org/jboss/test/data/a");
      cache.put("/org/jboss/test/data/b", "/org/jboss/test/data/b", "/org/jboss/test/data/b");
      cache.put("/org/jboss/test/data/c", "/org/jboss/test/data/c", "/org/jboss/test/data/c");
      cache.put("/org/jboss/test/data/d", "/org/jboss/test/data/d", "/org/jboss/test/data/d");
      cache.put("/org/jboss/test/data/e", "/org/jboss/test/data/e", "/org/jboss/test/data/e");

      TestingUtil.sleepThread(wakeupIntervalMillis + 500);

      cache.removeNode("/org/jboss/test/data/d");
      cache.removeNode("/org/jboss/test/data/e");
      cache.put("/org/jboss/test/data/f", "/org/jboss/test/data/f", "/org/jboss/test/data/f");
      cache.put("/org/jboss/test/data/g", "/org/jboss/test/data/g", "/org/jboss/test/data/g");

      TestingUtil.sleepThread(wakeupIntervalMillis + 500);

      assertNull(cache.get("/org/jboss/test/data/d", "/org/jboss/test/data/d"));
      assertNull(cache.get("/org/jboss/test/data/e", "/org/jboss/test/data/e"));

      assertNotNull(cache.get("/org/jboss/test/data/f", "/org/jboss/test/data/f"));
      assertNotNull(cache.get("/org/jboss/test/data/g", "/org/jboss/test/data/g"));
   }

   class MyPutter extends Thread
   {

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

      public void run()
      {
         int i = 0;
         final String myName = ROOT_STR + "/test1/node" + getName();
         while (isTrue)
         {
            try
            {
               cache.put(myName + i++, "value", i);
               TestingUtil.sleepThread(1);
            }
            catch (Throwable e)
            {
               e.printStackTrace();
               if (t1_ex == null)
               {
                  t1_ex = e;
               }
            }
         }
      }
   }


   public void testConcurrentPutAndEvict() throws Exception
   {
      cache.stop();
      cache.destroy();
      cache.getConfiguration().setIsolationLevel(IsolationLevel.REPEATABLE_READ);
      cache.start();
      cache.put(ROOT_STR + "/concurrentPutAndEvict", "value", 1);

      for (int i = 0; i < 10; i++)
      {
         new MyPutter("Putter" + i).start();
      }

      int counter = 0;
      while (true)
      {
         counter++;
         if (t1_ex != null)
         {
            fail("Exception generated in put() " + t1_ex);
         }
         log("nodes/locks: " + cache.getNumberOfNodes() + "/" + cache.getNumberOfLocksHeld());
         TestingUtil.sleepThread(1000);
         if (counter > 10)
         {// run for 10 seconds
            isTrue = false;
            break;
         }
      }
   }

   private void log(String s)
   {
      System.out.println(s);
   }
}
