package org.jboss.cache.manualtests;

import junit.textui.TestRunner;
import org.jboss.cache.CacheException;
import org.jboss.cache.TreeCache;
import org.jboss.cache.loader.AbstractCacheLoaderTestBase;
import org.jboss.cache.loader.JDBCCacheLoaderPerfTest;

public class TcpCacheLoaderTest extends AbstractCacheLoaderTestBase
{
   private TreeCache cache;
   private static final int serverPort = 7500;
   private static final String serverHost = "127.0.0.1";

   protected void setUp() throws Exception
   {
      cache = new TreeCache();
      cache.setCacheLoaderConfiguration(getSingleCacheLoaderConfig("", "org.jboss.cache.loader.tcp.TcpDelegatingCacheLoader", "port=" + serverPort + "\nhost=" + serverHost, false, false, false));
   }

   public void testPerformance() throws Exception
   {
      int n = 5;
      cache.startService();

      Runner r = new Runner(cache, n, "RunnerThread");
      r.start();
      r.join();
      cache.stopService();

      cache.startService();
      for (int i = 0; i < n; i++)
      {
         System.out.println("Getting " + i);
         assertEquals("v", cache.get("/test/fqn/RunnerThread/" + i, "k"));
      }
      cache.stopService();

   }

   public void testPerformanceMT() throws Exception
   {
      int n = 500;
      Runner[] r = new Runner[20];
      cache.startService();

      for (int i = 0; i < r.length; i++)
      {
         r[i] = new Runner(cache, n, "RunnerThread-" + i);
         r[i].start();
      }

      for (int i = 0; i < r.length; i++) r[i].join();
      cache.stopService();

      cache.startService();
      for (int i = 0; i < n; i++)
      {
         //System.out.println("Getting " + i);
         for (int j = 0; j < r.length; j++) assertEquals("v", cache.get("/test/fqn/RunnerThread-" + j + "/" + i, "k"));
      }
      cache.stopService();

      // metrics
      long totalTime = 0;
      for (int i = 0; i < r.length; i++) totalTime += r[i].totalTime;

      System.out.println("Took " + ((double) totalTime / 1000) + " secs to process " + (n * r.length) + " put operations");
   }

   private class Runner extends Thread
   {
      private TreeCache cache;
      private int n;
      long totalTime;

      public Runner(TreeCache cache, int n, String instanceName)
      {
         super(instanceName);
         this.cache = cache;
         this.n = n;
      }

      public void run()
      {
         long st = System.currentTimeMillis();
         for (int i = 0; i < n; i++)
         {
            try
            {
               cache.put("/test/fqn/" + getName() + "/" + i, "k", "v");
            }
            catch (CacheException e)
            {
            }
         }
         totalTime = System.currentTimeMillis() - st;
      }
   }


   public static void main(String[] args)
   {
      TestRunner.run(JDBCCacheLoaderPerfTest.class);
   }
}
