/*
 *
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package org.jboss.cache;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.cache.lock.IsolationLevel;
import org.jboss.cache.lock.LockStrategyFactory;
import org.jboss.cache.transaction.DummyTransactionManager;

import javax.naming.Context;
import javax.transaction.Transaction;
import java.util.ArrayList;
import java.util.Properties;
import java.util.Random;


/**
 * Local mode stress test for TreeCache.
 *
 * @version $Id: EvictionLocalStressTest.java 2015 2006-05-31 14:08:39Z msurtani $
 * @author <a href="mailto:bwang@jboss.org">Ben Wang</a> May 20 2003
 */
public class EvictionLocalStressTest extends TestCase
{
   static TreeCache cache_;
   int cachingMode_ = TreeCache.LOCAL;
   final static Properties p_;
   String oldFactory_ = null;
   final String FACTORY = "org.jboss.cache.transaction.DummyContextFactory";
   static ArrayList nodeList_;
   static final int depth_ = 4;
   static final int children_ = 4;
   static final int MAX_LOOP = 500;
   static final int SLEEP_TIME = 20;
   static final String ROOT = "/stress/";
   private static Log log=LogFactory.getLog(EvictionLocalStressTest.class);

   static Exception thread_ex=null;

   static
   {
      p_ = new Properties();
      p_.put(Context.INITIAL_CONTEXT_FACTORY,
            "org.jboss.cache.transaction.DummyContextFactory");
   }

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

   public void setUp() throws Exception
   {
      super.setUp();
      oldFactory_ = System.getProperty(Context.INITIAL_CONTEXT_FACTORY);
      System.setProperty(Context.INITIAL_CONTEXT_FACTORY, FACTORY);
      DummyTransactionManager.getInstance();
      initCaches(TreeCache.LOCAL);
      nodeList_ = nodeGen(depth_, children_);
      log("LocalStressTestCase: cacheMode=TRANSIENT, one cache");
      thread_ex=null;
   }

   public void tearDown() throws Exception
   {
      super.tearDown();
      thread_ex=null;
      destroyCaches();

      if (oldFactory_ != null) {
         System.setProperty(Context.INITIAL_CONTEXT_FACTORY, oldFactory_);
         oldFactory_ = null;
      }
   }



   void initCaches(int caching_mode) throws Exception
   {
      cachingMode_ = caching_mode;
      cache_ = new TreeCache();
      PropertyConfigurator config = new PropertyConfigurator();
      config.configure(cache_, "META-INF/local-lru-eviction-service.xml"); // read in generic local xml
      cache_.setTransactionManagerLookupClass("org.jboss.cache.DummyTransactionManagerLookup");
      cache_.setLockAcquisitionTimeout(10000);
      cache_.createService();
      cache_.startService();
   }

   void destroyCaches() throws Exception
   {
      cache_.stopService();
      cache_ = null;
   }

   protected void setLevelRW()
   {
      log("set lock level to RWUpgrade ...");
      LockStrategyFactory.setIsolationLevel(IsolationLevel.REPEATABLE_READ);
      cache_.setIsolationLevel(IsolationLevel.REPEATABLE_READ);
   }

   protected void setLevelSerial()
   {
      log("set lock level to SimpleLock ...");
      LockStrategyFactory.setIsolationLevel(IsolationLevel.SERIALIZABLE);
      cache_.setIsolationLevel(IsolationLevel.SERIALIZABLE);
   }

   public void testAllTx_RWLock() throws Exception
   {
      setLevelRW();
      allTx();
   }


   private void allTx() throws Exception
   {
      RunThread t1 = new RunThread(1);
      RunThread t2 = new RunThread(2);

      t1.start();
      t2.start();

      t1.join(60000);
      t2.join(60000);

      System.out.println("number of nodes/locks: " + cache_.getNumberOfNodes() + " / " + cache_.getNumberOfLocksHeld());

      if(thread_ex != null)
         throw thread_ex;
   }

   static class RunThread extends Thread
   {
      final int seed_;
      Random random_;
      Transaction tx = null;

      public RunThread(int seed) throws Exception {
         super.setName("RunThread#" + seed);
         seed_ = seed;
         random_ = new Random(seed);
      }

      private Transaction startTransaction() throws Exception {
         DummyTransactionManager mgr=DummyTransactionManager.getInstance();
         mgr.begin();
         return mgr.getTransaction();
      }

      public void run()
      {
         try {
            _run();
         }
         catch(Exception ex) {
            thread_ex=ex;
            // ex.printStackTrace();
         }
      }

      public void _run() throws Exception {
         for (int i = 1; i <= MAX_LOOP && thread_ex == null; i++)
         {
            log(i + "/" + MAX_LOOP);
            sleep_(random_.nextInt(SLEEP_TIME));
            op1();
            sleep_(random_.nextInt(SLEEP_TIME));
            op2();
            sleep_(random_.nextInt(SLEEP_TIME));
            op3();
         }
         log("terminated");
      }

      // Operation 1
      private void op1() throws Exception
      {
         int i = random_.nextInt(nodeList_.size() - 1);
         String key = Integer.toString(i);
         String value = Integer.toString(i);
         String node = (String) nodeList_.get(i);

         // tx=startTransaction();
         //try {
            if(log.isTraceEnabled())
               log.trace("op1.get(" + node + ", " + key + ") thread=" + Thread.currentThread());
            cache_.get(node, key);

            sleep_(random_.nextInt(SLEEP_TIME)); // sleep for max 200 millis

            if(log.isTraceEnabled())
               log.trace("op1.put(" + node + ", " + key + ", " + value + ") thread=" + Thread.currentThread());
            cache_.put(node, key, value);
         //}
         //finally {
           // tx.commit();
         //}
      }

      // Operation 2
      private void op2() throws Exception
      {
         int i = random_.nextInt(nodeList_.size() - 1);
         String key = Integer.toString(i);
         String node = (String) nodeList_.get(i);

         tx=startTransaction();
         try {
            if(log.isTraceEnabled())
               log.trace("op2.get(" + node + ", " + key + ") thread=" + Thread.currentThread());
            cache_.get(node, key);
            sleep_(random_.nextInt(SLEEP_TIME)); // sleep for max 200 millis

            if(log.isTraceEnabled())
               log.trace("op2.get(" + node + ", " + key + ") thread=" + Thread.currentThread());
            cache_.get(node, key);
            sleep_(random_.nextInt(SLEEP_TIME)); // sleep for max 200 millis
         }
         finally {
            tx.commit();
         }
      }

      // Operation 3
      private void op3() throws Exception
      {
         int i = random_.nextInt(nodeList_.size() - 1);
         String key = Integer.toString(i);
         String value = Integer.toString(i);
         String node = (String) nodeList_.get(i);

         tx=startTransaction();
         try {
            if(log.isTraceEnabled())
               log.trace("op3.put(" + node + ", " + key + ", " + value + ") thread=" + Thread.currentThread());
            cache_.put(node, key, value);

            sleep_(random_.nextInt(SLEEP_TIME)); // sleep for max 200 millis

            if(log.isTraceEnabled())
               log.trace("op3.remove(" + node + ", " + key + ") thread=" + Thread.currentThread());
            cache_.remove(node, key);
         }
         finally {
            tx.commit();
         }
      }

      private void sleep_(long msecs)
      {
         try
         {
            Thread.sleep(msecs);
         }
         catch (Exception ex)
         {
         }
      }
   }

   /**
    * Generate the tree nodes quasi-exponentially. I.e., depth is the level
    * of the hierarchy and children is the number of children under each node.
    * This strucutre is used to add, get, and remove for each node.
    */
   private ArrayList nodeGen(int depth, int children)
   {
      ArrayList strList = new ArrayList();
      ArrayList oldList = new ArrayList();
      ArrayList newList = new ArrayList();

      oldList.add(ROOT);
      newList.add(ROOT);
      strList.add(ROOT);

      while (depth > 0) {
         // Trying to produce node name at this depth.
         newList = new ArrayList();
         for (int i = 0; i < oldList.size(); i++) {
            for (int j = 0; j < children; j++) {
               String tmp = (String) oldList.get(i);
               tmp += Integer.toString(j);
               if (depth != 1)
                  tmp += "/";
               newList.add(tmp);
            }
         }
         strList.addAll(newList);
         oldList = newList;
         depth--;
      }

      log("Nodes generated: " + strList.size());
      return strList;
   }

   public static Test suite() throws Exception
   {
      return new TestSuite(EvictionLocalStressTest.class);
   }

   private static void log(String str)
   {
      System.out.println(Thread.currentThread() + ": " + str);
//        System.out.println(str);
   }

}
