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

import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.naming.InitialContext;

import org.jboss.test.JBossTestCase;

/**
 * Reconnect stress
 *
 * @author
 * @version
 */

public class JBossMQReconnectStressTestCase extends JBossTestCase
{
   static String QUEUE_FACTORY = "ConnectionFactory";

   public JBossMQReconnectStressTestCase(String name) throws Exception
   {
      super(name);
   }

   public void testReconnectStress() throws Throwable
   {
      InitialContext ctx = new InitialContext();
      QueueConnectionFactory qcf = (QueueConnectionFactory) ctx.lookup(QUEUE_FACTORY);
      
      ReconnectThread[] threads = new ReconnectThread[getThreadCount()];
      for (int i = 0; i < threads.length; ++i)
         threads[i] = new ReconnectThread(qcf, "Reconnect-"+i);
      for (int i = 0; i < threads.length; ++i)
         threads[i].start();
      for (int i = 0; i < threads.length; ++i)
         threads[i].join();
      for (int i = 0; i < threads.length; ++i)
      {
         if (threads[i].error != null)
            throw threads[i].error;
      }
   }
   
   public class ReconnectThread extends Thread
   {
      public Throwable error;
      public QueueConnectionFactory qcf;
      
      public ReconnectThread(QueueConnectionFactory qcf, String name)
      {
         super(name);
         this.qcf = qcf;
      }
      
      public void run()
      {
         QueueConnection c = null;
         try
         {
            for (int i = 0; i < getIterationCount(); ++i)
            {
               log.info(Thread.currentThread() + " connect " + i);
               c = qcf.createQueueConnection();
               log.info(Thread.currentThread() + " close " + i);
               c.close();
               c = null;
            }
         }
         catch (Throwable t)
         {
            if (c != null)
            {
               try
               {
                  c.close();
               }
               catch (Throwable ignored)
               {
                  log.warn("Ignored: ", ignored);
               }
            }
         }
      }
   }
}