/*
 * 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.DataNode;
import org.jboss.cache.Fqn;
import org.jboss.cache.PropertyConfigurator;
import org.jboss.cache.TreeCache;
import org.jboss.cache.lock.IsolationLevel;

/**
 * @author Daniel Huang
 * @version $Revison: $
 */
public class ElementSizePolicyTest extends TestCase
{
   TreeCache cache;
   int wakeupIntervalMillis = 0;
   final String ROOT_STR = "/test";
   Throwable t1_ex, t2_ex;
   final long DURATION = 10000;
   boolean isTrue;

   public ElementSizePolicyTest(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-elementsize-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/test/data/";
      for (int i = 0; i < 10; i++)
      {
         String str = rootStr + i;
         Fqn fqn = Fqn.fromString(str);
         try
         {
            cache.put(fqn, str, str);
            if (i % 2 == 0)
            {
               for (int k = 0; k < i; k++)
               {
                  cache.put(fqn, new Integer(k), Integer.toString(k));
               }
            }
         }
         catch (Exception e)
         {
            fail("Failed to insert data" + e);
            e.printStackTrace();
         }
      }

      System.out.println(cache.toString(true));
      _sleep(wakeupIntervalMillis + 500);
      System.out.println(cache.toString(true));

      for (int i = 0; i < 10; i++)
      {
         DataNode node = cache.get("/org/jboss/test/data/" + Integer.toString(i));
         System.out.println(node);
         if (i % 2 == 0)
         {
            if (i < 6)
            {
               int numElements = node.numAttributes();
               assertEquals(i + 1, numElements);
            }
            else
            {
               assertNull(node);
            }
         }
         else
         {
            assertEquals(1, node.numAttributes());
         }
      }
   }

   public void testEviction2() throws Exception
   {
      String rootStr = "/org/jboss/data/";
      for (int i = 0; i < 20; i++)
      {
         String str = rootStr + Integer.toString(i);
         Fqn fqn = Fqn.fromString(str);
         cache.put(fqn, new Integer(i), str);
         for (int k = 0; k < i; k++)
         {
            cache.put(fqn, new Integer(k), str);
         }
      }

      System.out.println(cache.toString(true));
      _sleep(wakeupIntervalMillis + 500);
      System.out.println(cache.toString(true));

      for (int i = 0; i < 20; i++)
      {
         String str = rootStr + Integer.toString(i);
         Fqn fqn = Fqn.fromString(str);
         DataNode node = cache.get(fqn);
         System.out.println(i + " " + node);
         if (i > 9)
         {
            assertNull("Testing at " + i, node);
         }
         else
         {
            assertEquals(1 + i, node.numAttributes());
         }
      }

      for (int i = 0; i < 17; i++)
      {
         cache.put("/org/jboss/data/" + Integer.toString(3), new Integer(100 + i), "value");
      }

      DataNode node = cache.get("/org/jboss/data/" + Integer.toString(3));
      assertEquals(21, node.numAttributes());
      _sleep(wakeupIntervalMillis + 500);

      assertNull(cache.get("/org/jboss/data/" + Integer.toString(3)));
   }

   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());
         _sleep(1000);
         if (counter > 10)
         { // run for 10 seconds
            isTrue = false;
            break;
         }
      }
   }

   void _sleep(long msecs)
   {
      try
      {
         Thread.sleep(msecs);
      }
      catch (InterruptedException e)
      {
         e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
      }
   }

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

}
