/*
 * 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 FIFOPolicy.
 *
 * @author Daniel Huang (dhuang@jboss.org)
 * @version $Revision: 1.3 $
 */
public class FIFOPolicyTest extends TestCase
{
   TreeCache cache;
   int wakeupIntervalMillis = 0;
   final String ROOT_STR = "/test";
   Throwable t1_ex, t2_ex;
   final long DURATION = 10000;
   boolean isTrue;

   public FIFOPolicyTest(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-fifo-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()
   {
      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.toString(true));
      TestingUtil.sleepThread(wakeupIntervalMillis + 500);

      System.out.println(cache.toString(true));
      try
      {
         String val = (String) cache.get(rootStr + "3", rootStr + "3");
         assertNull("DataNode should be empty ", val);
         assertNull(cache.get(rootStr + "1", rootStr + "1"));
         assertNull(cache.get(rootStr + "2", rootStr + "2"));
         assertNull(cache.get(rootStr + "0", rootStr + "0"));
         assertNull(cache.get(rootStr + "4", rootStr + "4"));

         assertNotNull(cache.get(rootStr + "5", rootStr + "5"));
      }
      catch (Exception e)
      {
         e.printStackTrace();
         fail("Failed to get" + e);
      }
   }

   public void testEviction2()
   {
      String rootStr = "/org/jboss/data";
      for (int i = 0; i < 10000; 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();
         }
      }

      TestingUtil.sleepThread(wakeupIntervalMillis + 500);
      try
      {
         for (int i = 0; i < 5000; i++)
         {
            assertNull("DataNode should be empty ",
                  cache.get(rootStr + Integer.toString(i), rootStr + Integer.toString(i)));
         }

         for (int i = 5000; i < 10000; i++)
         {
            assertNotNull(cache.get(rootStr + Integer.toString(i), rootStr + Integer.toString(i)));
         }

         // add another node to cache. this should push node 5000 out of cache.
         cache.put(rootStr + "a", rootStr + "a", rootStr + "a");
         for (int i = 5001; i < 10000; i++)
         {
            assertNotNull(cache.get(rootStr + Integer.toString(i), rootStr + Integer.toString(i)));
         }

         assertNotNull(cache.get(rootStr + "a", rootStr + "a"));
      }
      catch (Exception e)
      {
         e.printStackTrace();
         fail("Failed to get" + e);
      }
   }

   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.
      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);
         // since it is FIFO if we leave it alone and revisit, cache should remain the same.
        for (int i = 5; i < 10; i++)
        {
           String str = rootStr + Integer.toString(i);
           Fqn fqn = Fqn.fromString(str);
           cache.get(fqn, str);   // just to keep it fresh
           System.out.println("-- sleeping for " + period + "ms");
        }
      }
      catch (Exception e)
      {
         e.printStackTrace();
         fail("Failed to evict" + e);
      }
   }

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

      int period = (wakeupIntervalMillis + 500);
      log("period is " + period);
      TestingUtil.sleepThread(period);
      String str1 = rootStr + "7";
      Fqn fqn1 = Fqn.fromString(str1);
      String str2 = rootStr + "7/7";
      Fqn fqn2 = Fqn.fromString(str2);
      try
      {
         assertNotNull(cache.get(fqn2, str2));
         assertNotNull(cache.get(fqn1, str1));
         cache.remove(fqn2);
         TestingUtil.sleepThread(period);
         assertNull(cache.get(fqn2, str2));
         assertNotNull(cache.get(fqn1, str1));
         cache.remove(fqn1);
         TestingUtil.sleepThread(period);
         assertNull(cache.get(fqn1, str1));
         assertNull(cache.get(fqn2, str2));

         String str3 = rootStr + "5/5";
         String str4 = rootStr + "5";
         Fqn fqn3 = Fqn.fromString(str3);
         Fqn fqn4 = Fqn.fromString(str4);
         assertNotNull(cache.get(fqn3, str3));
         assertNotNull(cache.get(fqn4, str4));

         TestingUtil.sleepThread(period);

         // remove the node above fqn4 /org/jboss/test/5 will cascade the delete into /org/jboss/test/5/5
         cache.remove(fqn4);

         TestingUtil.sleepThread(period);
         assertNull(cache.get(fqn3, str3));
         assertNull(cache.get(fqn4, str4));
      }
      catch (Exception e)
      {
         e.printStackTrace();
         fail("Failed to evict" + e);
      }
   }


   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);
   }

}
