/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.ejb3.test.service;


import org.jboss.system.ServiceMBeanSupport;

import javax.naming.InitialContext;

import java.io.File;
import java.util.ArrayList;

/**
 * Comment
 *
 * @author <a href="mailto:bill@jboss.org">Bill Burke</a>
 * @version $Revision: 1.2.4.4 $
 */
public class Tester extends ServiceMBeanSupport implements TesterMBean
{
   public static ArrayList creates = new ArrayList();
   public static ArrayList starts = new ArrayList();

   public void testServiceWithDefaultLocalJNDIName() throws Exception
   {
      final int count = 15;
      final InitialContext ctx = new InitialContext();
      ServiceOneLocal test = (ServiceOneLocal) ctx.lookup(ServiceOneLocal.class.getName());
      test.setLocalMethodCalls(0);

      Thread[] threads = new Thread[count];
      for (int i = 0 ; i < count ; i++)
      {
         final int outer = i;
         threads[i] = new Thread(
               new Runnable()
               {
                  public void run()
                  {
                     try
                     {
                        ServiceOneLocal test = (ServiceOneLocal) ctx.lookup(ServiceOneLocal.class.getName());
                        for (int j = 0 ; j < count ; j++)
                        {
                           String s = outer + "_" + j;
                           //System.out.println(s);
                           test.localMethod(s);
                        }
                     }
                     catch(Exception e)
                     {
                        throw new RuntimeException(e);
                     }
                  }
               }
            );
         threads[i].start();
      }

      Thread.sleep(5000);
      for (int i = 0 ; i < count ; i++)
      {
         threads[i].join();
      }

      if (test.getInstances() != 1)
      {
         throw new RuntimeException("There should only ever be one instance of the service. We have " + test.getInstances());
      }

      int localCalls = test.getLocalMethodCalls();
      if (localCalls != (count * count))
      {
         throw new RuntimeException("There should be " + count * count + " local method calls, not " + localCalls);
      }
   }

   public void testServiceWithLocalBinding() throws Exception
   {
      InitialContext ctx = new InitialContext();
      ServiceTwoLocal test = (ServiceTwoLocal) ctx.lookup("serviceTwo/local");
      test.setCalled(false);
      if (test.getCalled()) throw new RuntimeException("Called should be false, not " + test.getCalled());
      test.localMethod();
      if (!test.getCalled()) throw new RuntimeException("Called should be true, not " + test.getCalled());
   }

   public ArrayList getCreates()
   {
      return creates;
   }

   public ArrayList getStarts()
   {
      return starts;
   }

}
