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

import junit.framework.TestCase;
import org.jboss.cache.Fqn;
import org.jboss.cache.PropertyConfigurator;
import org.jboss.cache.TreeCache;
import org.jboss.cache.misc.TestingUtil;
import org.jboss.cache.lock.IsolationLevel;

/**
 * Unit tests for LFU Policy.
 *
 * @author Daniel Huang (dhuang@jboss.org)
 * @version $Revision: 1838 $
 */
public class LFUPolicyTest extends TestCase
{
   TreeCache cache;
   int wakeupIntervalMillis = 0;
   final String ROOT_STR = "/test";
   Throwable t1_ex, t2_ex;
   final long DURATION = 10000;
   boolean isTrue;

   public LFUPolicyTest(String s)
   {
      super(s);
   }

   public void setUp() throws Exception
   {
      super.setUp();
      initCaches();
      wakeupIntervalMillis = cache.getEvictionThreadWakeupIntervalSeconds() * 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;
   }

   void initCaches() throws Exception
   {
      cache = new TreeCache();
      PropertyConfigurator config = new PropertyConfigurator();
      config.configure(cache, "META-INF/local-lfu-eviction-service.xml"); // read in generic local xml
      cache.setTransactionManagerLookupClass("org.jboss.cache.DummyTransactionManagerLookup");
      cache.setIsolationLevel(IsolationLevel.SERIALIZABLE);
      cache.startService();
   }

   public void tearDown() throws Exception
   {
      super.tearDown();
      cache.stopService();
   }

   public void testEviction() throws Exception
   {
      String rootStr = "/org/jboss/data/";
      for (int i = 0; i < 8000; i++)
      {
         String str = rootStr + i;
         Fqn fqn = Fqn.fromString(str);
         try
         {
            cache.put(fqn, str, str);
         }
         catch (Exception e)
         {
            fail("Failed to insert data" + e);
            e.printStackTrace();
         }

         // visit odd numbered nodes an extra time to make them get evicted last.
         if (i % 2 != 0)
         {
            cache.get(fqn, str);
         }
      }

      long period = wakeupIntervalMillis + 500;
      TestingUtil.sleepThread(period);

      for (int i = 0; i < 8000; i++)
      {
         String str = rootStr + i;
         Fqn fqn = Fqn.fromString(str);

         if (i % 2 == 0)
         {
            assertNull(cache.get(fqn, str));
         }
         else
         {
            assertNotNull(cache.get(fqn, str));
         }
      }
   }

   public void testNodeVisited()
   {
      String rootStr = "/org/jboss/test/data/";
      for (int i = 0; i < 10; i++)
      {
         String str = rootStr + i;
         Fqn fqn = Fqn.fromString(str);
         try
         {
            cache.put(fqn, str, str);
         }
         catch (Exception e)
         {
            fail("Failed to insert data" + e);
            e.printStackTrace();
         }
      }
      System.out.println("cache is:\n" + cache.toString(true));

      int period = wakeupIntervalMillis + 500;

      log("sleeping for " + period + "ms");
      TestingUtil.sleepThread(period);  // it really depends the eviction thread time.

      System.out.println("cache is:\n" + cache.toString(true));

      try
      {
         for (int i = 0; i < 5; i++)
         {
            String str = rootStr + Integer.toString(i);
            Fqn fqn = Fqn.fromString(str);
            assertNull(cache.get(fqn, str));
         }
         for (int i = 5; i < 10; i++)
         {
            String str = rootStr + Integer.toString(i);
            Fqn fqn = Fqn.fromString(str);
            assertNotNull(cache.get(fqn, str));
         }

         TestingUtil.sleepThread(period);

         System.out.println(cache.toString(true));

         // since min is 5 the cache won't deplete past 5 nodes left in the cache.
         for (int i = 5; i < 10; i++)
         {
            String str = rootStr + Integer.toString(i);
            Fqn fqn = Fqn.fromString(str);
            assertNotNull(cache.get(fqn, str));
         }

         // now we add some more nodes and we selectively visit some older nodes but not all. they should not get
         // evicted when the thread next runs.
         for (int i = 5; i < 7; i++)
         {
            String str = rootStr + Integer.toString(i);
            Fqn fqn = Fqn.fromString(str);
            cache.get(fqn, str);
         }

         // add 2 more to push the limit to 5 so we cause the old unvisited nodes to get evicted.
         for (int i = 10; i < 13; i++)
         {
            String str = rootStr + Integer.toString(i);
            Fqn fqn = Fqn.fromString(str);
            cache.put(fqn, str, str);

            // now bring up their hit count for LFU purposes (cache hit count based eviction).
            for (int k = 0; k < 10; k++)
            {
               cache.get(fqn, str);
            }
         }

         TestingUtil.sleepThread(period);

         System.out.println(cache.toString(true));

         // now make sure we still only have 5 nodes and they are the ones we expect based on LFU
         for (int i = 5; i < 7; i++)
         {
            String str = rootStr + Integer.toString(i);
            Fqn fqn = Fqn.fromString(str);
            assertNotNull(cache.get(fqn, str));
         }

         for (int i = 7; i < 10; i++)
         {
            String str = rootStr + Integer.toString(i);
            Fqn fqn = Fqn.fromString(str);
            assertNull(cache.get(fqn, str));
         }

         for (int i = 10; i < 13; i++)
         {
            String str = rootStr + Integer.toString(i);
            Fqn fqn = Fqn.fromString(str);
            assertNotNull(cache.get(fqn, str));
         }

      }
      catch (Exception e)
      {
         e.printStackTrace();
         fail("Failed to evict" + e);
      }
   }

   public void testNodeRemoved() throws Exception
   {
      String rootStr = "/org/jboss/data/";
      for (int i = 0; i < 5000; i++)
      {
         String str = rootStr + i;
         Fqn fqn = Fqn.fromString(str);
         try
         {
            cache.put(fqn, str, str);
         }
         catch (Exception e)
         {
            fail("Failed to insert data" + e);
            e.printStackTrace();
         }
      }

      int period = (wakeupIntervalMillis + 500);
      log("period is " + period);
      TestingUtil.sleepThread(period);

      for (int i = 0; i < 1000; i++)
      {
         String str = rootStr + i;
         Fqn fqn = Fqn.fromString(str);
         assertNull(cache.get(fqn, str));
      }

      for (int i = 1000; i < 5000; i++)
      {
         String str = rootStr + i;
         Fqn fqn = Fqn.fromString(str);
         assertNotNull(cache.get(fqn, str));
      }

      for (int i = 1000; i < 5000; i++)
      {
         if (i % 2 == 0)
         {
            String str = rootStr + i;
            Fqn fqn = Fqn.fromString(str);
            cache.remove(fqn);
         }
      }

      TestingUtil.sleepThread(period);


      for (int i = 1000; i < 5000; i++)
      {
         if (i % 2 == 0)
         {
            String str = rootStr + i;
            Fqn fqn = Fqn.fromString(str);
            assertNull(cache.get(fqn));
         }
      }
   }


   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", new Integer(i));
               sleep(1);
            }
            catch (Throwable e)
            {
               e.printStackTrace();
               if (t1_ex == null)
                  t1_ex = e;
            }
         }
      }
   }


   public void testConcurrentPutAndEvict() throws Exception
   {
      cache.setIsolationLevel(IsolationLevel.REPEATABLE_READ);
      cache.put(ROOT_STR + "/concurrentPutAndEvict", "value", new Integer(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;
         }
      }
   }

   void log(String msg)
   {
      System.out.println("-- " + msg);
   }

}
