/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package org.jboss.test.cache.test.eviction;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jboss.cache.Fqn;
import org.jboss.cache.PropertyConfigurator;
import org.jboss.cache.TreeCache;
import org.jboss.cache.Node;

/**
 * @author Ben Wang, Feb 11, 2004
 */
public class LRUPolicyUnitTestCase extends TestCase
{
   TreeCache cache_;
   int wakeupIntervalMillis_ = 0;
   final String ROOT_STR = "/test";
   Throwable t1_ex, t2_ex;
   final long DURATION = 10000;
   boolean isTrue;

   public LRUPolicyUnitTestCase(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
   {
//      _sleep(10000);
      cache_ = new TreeCache();
      PropertyConfigurator config = new PropertyConfigurator();
      config.configure(cache_, "META-INF/local-eviction-service.xml"); // read in generic local xml
      cache_.setTransactionManagerLookupClass("org.jboss.cache.DummyTransactionManagerLookup");
      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();
         }
      }

      _sleep(2 * wakeupIntervalMillis_);
      try {
         String val = (String) cache_.get(rootStr + "3", rootStr + "3");
         assertNull("Node should be empty ", val);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

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

      int period = (wakeupIntervalMillis_ / 2 + 1000);
      log("period is " + period);
      _sleep(period);  // it really depends the eviction thread time.
      String str = rootStr + "7";
      Fqn fqn = Fqn.fromString(str);
      try {
         cache_.get(fqn, str);   // just to keep it fresh
         _sleep(period);  // it really depends the eviction thread time.
         cache_.get(fqn, str);   // just to keep it fresh
         _sleep(period);  // it really depends the eviction thread time.
         String val = (String) cache_.get(rootStr + "3", rootStr + "3");
         assertNull("Node should be empty ", val);
         val = (String) cache_.get(rootStr + "7", rootStr + "7");
         assertNotNull("Node should not be empty ", val);
         _sleep(wakeupIntervalMillis_ * 2 + 2000);
         val = (String) cache_.get(rootStr + "7", rootStr + "7");
         assertNull("Node should be empty ", val);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public void testNodeRemoved()
   {
      String rootStr = "/org/jboss/test/data/";
      for (int i = 0; i < 10; i++) {
         String str = rootStr + i + "/" + 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_ / 2 + 1000);
      log("period is " + period);
      _sleep(period);  // it really depends the eviction thread time.
      String str1 = rootStr + "7";
      Fqn fqn1 = Fqn.fromString(str1);
      String str2 = rootStr + "7/7";
      Fqn fqn2 = Fqn.fromString(str2);
      try {
         cache_.get(fqn1, str1);   // just to keep it fresh
         cache_.get(fqn2, str2);   // just to keep it fresh
         _sleep(period);  // it really depends the eviction thread time.
         cache_.get(fqn1, str1);   // just to keep it fresh
         cache_.get(fqn2, str2);   // just to keep it fresh
         _sleep(period);  // it really depends the eviction thread time.
         String val = (String) cache_.get(rootStr + "7/7", rootStr + "7/7");
         assertNotNull("Node should not be empty ", val);
         cache_.remove(fqn1);
         _sleep(wakeupIntervalMillis_ * 2 + 2000);
         val = (String) cache_.get(rootStr + "7/7", rootStr + "7/7");
         assertNull("Node should be empty ", val);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

    /*
   public void testConcurrentPutAndEvict() throws Exception
   {
      cache_.put(ROOT_STR+ "/test1", "value", new Integer(1));

      for (int i = 0; i < 10; i++) {
         new Thread()
         {
            public void run()
            {
               while (isTrue) {
                  int i = (int) (Math.random() * 10000000);
                  try {
                     cache_.put(ROOT_STR+ "/test1/node" + i, "value", new Integer(i));
                  } catch (Exception e) {
                     e.printStackTrace();
                     t1_ex = e;
                  }
               }
            }
         }.start();
      }

      int counter = 0;
      while (true) {
         counter++;
         Node node = cache_.get(ROOT_STR+ "/test1");
         int count = node == null || node.getChildren() == null ? 0 : node.getChildren().size();
         log("Nodes: " + count);
         Thread.sleep(1000);
         if(t1_ex != null) {
            fail("Exception generated in put " +t1_ex);
         }
         if(counter > 10) { // run for 10 seconds
            isTrue = false;
            Thread.sleep(1000);
            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);
   }

   public static Test suite()
   {
      return new TestSuite(LRUPolicyUnitTestCase.class);
   }

   public static void main(String[] args)
   {
      junit.textui.TestRunner.run(suite());
   }

}
