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

import javax.jms.JMSException;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TemporaryQueue;
import javax.naming.Context;

import org.jboss.test.JBossTestCase;

/**
 * Tests for temporaries and session/connection consumer construction
 *
 * @author <a href="mailto:adrian@jboss.org>Adrian Brock</a>
 * @version <tt>$Revision: 1.1.2.1 $</tt>
 */
public class TemporarySessionConnectionUnitTestCase extends JBossTestCase
{
   static String QUEUE_FACTORY = "ConnectionFactory";

   QueueConnection queueConnection;

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

   public void testTemporaryDifferentSession() throws Exception
   {
      connect();
      try
      {
         QueueSession session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
         TemporaryQueue temp = session.createTemporaryQueue(); 
         session.createConsumer(temp);
         session.close();
         session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
         session.createConsumer(temp).close();
      }
      finally
      {
         disconnect();
      }
   }

   public void testTemporaryDifferentConnection() throws Exception
   {
      connect();
      try
      {
         QueueSession session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
         TemporaryQueue temp = session.createTemporaryQueue(); 
         session.createConsumer(temp);
         disconnect();
         connect();
         session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
         try
         {
            session.createConsumer(temp).close();
            fail("Should not be able to consume a temporary on different connection");
         }
         catch (JMSException expected)
         {
         }
      }
      finally
      {
         disconnect();
      }
   }

   protected void connect() throws Exception
   {
      Context context = getInitialContext();
      QueueConnectionFactory queueFactory = (QueueConnectionFactory) context.lookup(QUEUE_FACTORY);
      queueConnection = queueFactory.createQueueConnection();
      queueConnection.start();

      getLog().debug("Connection established.");
   }

   protected void disconnect()
   {
      try
      {
         if (queueConnection != null)
            queueConnection.close();
      }
      catch (Exception ignored)
      {
      }

      getLog().debug("Connection closed.");
   }
}
