[jboss-cvs] JBoss Messaging SVN: r5222 - in trunk: examples/messaging/src/org/jboss/messaging/example and 58 other directories.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Thu Oct 30 12:12:29 EDT 2008


Author: timfox
Date: 2008-10-30 12:12:28 -0400 (Thu, 30 Oct 2008)
New Revision: 5222

Added:
   trunk/src/main/org/jboss/messaging/core/remoting/ConnectionManager.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/ConnectionManagerImpl.java
Removed:
   trunk/src/main/org/jboss/messaging/core/remoting/ConnectionRegistry.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/ConnectionRegistryImpl.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/ConnectionRegistryLocatorTest.java
Modified:
   trunk/examples/jms/src/org/jboss/jms/example/MessageGroupingExample.java
   trunk/examples/jms/src/org/jboss/jms/example/ScheduledExample.java
   trunk/examples/jms/src/org/jboss/jms/example/WildcardExample.java
   trunk/examples/messaging/src/org/jboss/messaging/example/SSLClient.java
   trunk/examples/messaging/src/org/jboss/messaging/example/ScheduledMessageExample.java
   trunk/examples/messaging/src/org/jboss/messaging/example/SimpleClient.java
   trunk/examples/messaging/src/org/jboss/messaging/example/SimpleExample.java
   trunk/examples/messaging/src/org/jboss/messaging/example/WildCardClient.java
   trunk/src/main/org/jboss/messaging/core/client/ClientConsumer.java
   trunk/src/main/org/jboss/messaging/core/client/ClientSession.java
   trunk/src/main/org/jboss/messaging/core/client/ClientSessionFactory.java
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientConsumerImpl.java
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientProducerImpl.java
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryImpl.java
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryInternal.java
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionInternal.java
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionPacketHandler.java
   trunk/src/main/org/jboss/messaging/core/config/Configuration.java
   trunk/src/main/org/jboss/messaging/core/config/impl/FileConfiguration.java
   trunk/src/main/org/jboss/messaging/core/exception/MessagingException.java
   trunk/src/main/org/jboss/messaging/core/filter/impl/FilterImpl.java
   trunk/src/main/org/jboss/messaging/core/message/Message.java
   trunk/src/main/org/jboss/messaging/core/message/impl/MessageImpl.java
   trunk/src/main/org/jboss/messaging/core/paging/PagingManager.java
   trunk/src/main/org/jboss/messaging/core/paging/impl/PagingManagerImpl.java
   trunk/src/main/org/jboss/messaging/core/persistence/StorageManager.java
   trunk/src/main/org/jboss/messaging/core/persistence/impl/journal/JournalStorageManager.java
   trunk/src/main/org/jboss/messaging/core/persistence/impl/nullpm/NullStorageManager.java
   trunk/src/main/org/jboss/messaging/core/postoffice/Address.java
   trunk/src/main/org/jboss/messaging/core/postoffice/AddressManager.java
   trunk/src/main/org/jboss/messaging/core/postoffice/PostOffice.java
   trunk/src/main/org/jboss/messaging/core/postoffice/impl/AddressImpl.java
   trunk/src/main/org/jboss/messaging/core/postoffice/impl/FlowControllerImpl.java
   trunk/src/main/org/jboss/messaging/core/postoffice/impl/PostOfficeImpl.java
   trunk/src/main/org/jboss/messaging/core/postoffice/impl/SimpleAddressManager.java
   trunk/src/main/org/jboss/messaging/core/postoffice/impl/WildcardAddressManager.java
   trunk/src/main/org/jboss/messaging/core/remoting/Channel.java
   trunk/src/main/org/jboss/messaging/core/remoting/Packet.java
   trunk/src/main/org/jboss/messaging/core/remoting/RemotingConnection.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingConnectionImpl.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingServiceImpl.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/invm/InVMConnection.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/netty/ChannelBufferWrapper.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/PacketImpl.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionCreateQueueMessage.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionDeleteQueueMessage.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/XidCodecSupport.java
   trunk/src/main/org/jboss/messaging/core/server/MessagingServer.java
   trunk/src/main/org/jboss/messaging/core/server/Queue.java
   trunk/src/main/org/jboss/messaging/core/server/ServerConsumer.java
   trunk/src/main/org/jboss/messaging/core/server/ServerSession.java
   trunk/src/main/org/jboss/messaging/core/server/impl/GroupingRoundRobinDistributionPolicy.java
   trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServerImpl.java
   trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServerPacketHandler.java
   trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServiceImpl.java
   trunk/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java
   trunk/src/main/org/jboss/messaging/core/server/impl/ScheduledDeliveryHandlerImpl.java
   trunk/src/main/org/jboss/messaging/core/server/impl/ServerConsumerImpl.java
   trunk/src/main/org/jboss/messaging/core/server/impl/ServerProducerImpl.java
   trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java
   trunk/src/main/org/jboss/messaging/core/transaction/ResourceManager.java
   trunk/src/main/org/jboss/messaging/core/transaction/Transaction.java
   trunk/src/main/org/jboss/messaging/core/transaction/impl/ResourceManagerImpl.java
   trunk/src/main/org/jboss/messaging/core/transaction/impl/TransactionImpl.java
   trunk/src/main/org/jboss/messaging/jms/client/JBossConnectionFactory.java
   trunk/src/main/org/jboss/messaging/jms/client/JBossConnectionMetaData.java
   trunk/src/main/org/jboss/messaging/jms/client/JBossMessage.java
   trunk/src/main/org/jboss/messaging/jms/client/JBossMessageConsumer.java
   trunk/src/main/org/jboss/messaging/jms/client/JBossMessageProducer.java
   trunk/src/main/org/jboss/messaging/jms/client/JBossQueueBrowser.java
   trunk/src/main/org/jboss/messaging/jms/client/JBossSession.java
   trunk/src/main/org/jboss/messaging/jms/server/JMSServerManager.java
   trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerDeployer.java
   trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerManagerImpl.java
   trunk/src/main/org/jboss/messaging/jms/server/management/JMSServerControlMBean.java
   trunk/src/main/org/jboss/messaging/jms/server/management/impl/JMSServerControl.java
   trunk/src/main/org/jboss/messaging/jms/server/management/impl/TopicControl.java
   trunk/src/main/org/jboss/messaging/jms/server/recovery/MessagingXAResourceRecovery.java
   trunk/src/main/org/jboss/messaging/util/SimpleString.java
   trunk/tests/config/log4j.xml
   trunk/tests/jms-tests/src/org/jboss/test/messaging/JBMServerTestCase.java
   trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/BrowserTest.java
   trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/CTSMiscellaneousTest.java
   trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/JMSTestCase.java
   trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/QueueRequestorTest.java
   trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/ScheduledDeliveryTest.java
   trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/SecurityTest.java
   trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/XARecoveryTest.java
   trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/XAResourceRecoveryTest.java
   trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/XATest.java
   trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/message/JMSXDeliveryCountTest.java
   trunk/tests/jms-tests/src/org/jboss/test/messaging/tools/container/LocalTestServer.java
   trunk/tests/jms-tests/src/org/jboss/test/messaging/tools/container/RMITestServer.java
   trunk/tests/jms-tests/src/org/jboss/test/messaging/tools/container/Server.java
   trunk/tests/src/org/jboss/messaging/tests/integration/basic/AutoGroupClientTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/ClientCrashTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/ClientExitTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/GracefulClient.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/MultiThreadRandomFailoverTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/RandomFailoverTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/SimpleAutomaticFailoverTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/SimpleManualFailoverTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/consumer/ConsumerTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/remoting/DestroyConsumerTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/remoting/PingTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/scheduling/ScheduledMessageTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/ssl/CoreClientOverSSL.java
   trunk/tests/src/org/jboss/messaging/tests/integration/ssl/CoreClientOverSSLTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/xa/BasicXaRecoveryTest.java
   trunk/tests/src/org/jboss/messaging/tests/performance/persistence/FakePostOffice.java
   trunk/tests/src/org/jboss/messaging/tests/performance/persistence/StorageManagerTimingTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/config/impl/ConfigurationImplTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/config/impl/FileConfigurationTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/filter/impl/FilterTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PageManagerImplTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PagingStoreImplTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/postoffice/impl/PostOfficeImplWildcardManagerTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/GroupingRoundRobinDistributionPolicyTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/QueueImplTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/RoundRobinDistributionPolicyTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/settings/impl/QueueSettingsTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/transaction/impl/TransactionImplTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/JBossConnectionFactoryTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/JBossConnectionMetaDataTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/JBossMessageTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/JBossSessionTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/jms/misc/ManifestTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/jms/referenceable/ConnectionFactoryObjectFactoryTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/jms/server/management/impl/JMSManagementServiceImplTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/jms/server/management/impl/JMSServerControlTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/util/SimpleStringTest.java
Log:
More session replication etc


Modified: trunk/examples/jms/src/org/jboss/jms/example/MessageGroupingExample.java
===================================================================
--- trunk/examples/jms/src/org/jboss/jms/example/MessageGroupingExample.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/examples/jms/src/org/jboss/jms/example/MessageGroupingExample.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,12 +21,22 @@
  */
 package org.jboss.jms.example;
 
-import org.jboss.messaging.core.logging.Logger;
+import java.util.concurrent.CountDownLatch;
 
-import javax.jms.*;
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageListener;
+import javax.jms.MessageProducer;
+import javax.jms.Queue;
+import javax.jms.Session;
+import javax.jms.TextMessage;
 import javax.naming.InitialContext;
-import java.util.concurrent.CountDownLatch;
 
+import org.jboss.messaging.core.logging.Logger;
+
 /**
  * This example sends 20 messages setting the groupid so that a specific consumer will receive each message.
  * setting the property 'JMSXGroupID' will bind a consumer to the value given, from this point on the same consumer will

Modified: trunk/examples/jms/src/org/jboss/jms/example/ScheduledExample.java
===================================================================
--- trunk/examples/jms/src/org/jboss/jms/example/ScheduledExample.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/examples/jms/src/org/jboss/jms/example/ScheduledExample.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,7 +21,9 @@
  */
 package org.jboss.jms.example;
 
-import org.jboss.messaging.core.logging.Logger;
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
 
 import javax.jms.Connection;
 import javax.jms.ConnectionFactory;
@@ -33,10 +35,9 @@
 import javax.jms.Session;
 import javax.jms.TextMessage;
 import javax.naming.InitialContext;
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
 
+import org.jboss.messaging.core.logging.Logger;
+
 /**
  * @author <a href="mailto:andy.taylor at jboss.org">Andy Taylor</a>
  */

Modified: trunk/examples/jms/src/org/jboss/jms/example/WildcardExample.java
===================================================================
--- trunk/examples/jms/src/org/jboss/jms/example/WildcardExample.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/examples/jms/src/org/jboss/jms/example/WildcardExample.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,11 +21,19 @@
  */
 package org.jboss.jms.example;
 
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+import javax.jms.Topic;
+import javax.naming.InitialContext;
+
 import org.jboss.messaging.core.logging.Logger;
 
-import javax.jms.*;
-import javax.naming.InitialContext;
-
 /**
  * @author <a href="mailto:andy.taylor at jboss.org">Andy Taylor</a>
  */

Modified: trunk/examples/messaging/src/org/jboss/messaging/example/SSLClient.java
===================================================================
--- trunk/examples/messaging/src/org/jboss/messaging/example/SSLClient.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/examples/messaging/src/org/jboss/messaging/example/SSLClient.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -29,7 +29,6 @@
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.exception.MessagingException;
-import org.jboss.messaging.core.message.Message;
 import org.jboss.messaging.core.remoting.impl.netty.TransportConstants;
 import org.jboss.messaging.jms.client.JBossTextMessage;
 import org.jboss.messaging.util.SimpleString;

Modified: trunk/examples/messaging/src/org/jboss/messaging/example/ScheduledMessageExample.java
===================================================================
--- trunk/examples/messaging/src/org/jboss/messaging/example/ScheduledMessageExample.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/examples/messaging/src/org/jboss/messaging/example/ScheduledMessageExample.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,6 +21,10 @@
  */
 package org.jboss.messaging.example;
 
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+
 import org.jboss.messaging.core.client.ClientConsumer;
 import org.jboss.messaging.core.client.ClientMessage;
 import org.jboss.messaging.core.client.ClientProducer;
@@ -33,10 +37,6 @@
 import org.jboss.messaging.jms.client.JBossTextMessage;
 import org.jboss.messaging.util.SimpleString;
 
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-
 /**
  * @author <a href="mailto:andy.taylor at jboss.org">Andy Taylor</a>
  */

Modified: trunk/examples/messaging/src/org/jboss/messaging/example/SimpleClient.java
===================================================================
--- trunk/examples/messaging/src/org/jboss/messaging/example/SimpleClient.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/examples/messaging/src/org/jboss/messaging/example/SimpleClient.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -29,7 +29,6 @@
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.exception.MessagingException;
-import org.jboss.messaging.core.message.Message;
 import org.jboss.messaging.jms.client.JBossTextMessage;
 import org.jboss.messaging.util.SimpleString;
 

Modified: trunk/examples/messaging/src/org/jboss/messaging/example/SimpleExample.java
===================================================================
--- trunk/examples/messaging/src/org/jboss/messaging/example/SimpleExample.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/examples/messaging/src/org/jboss/messaging/example/SimpleExample.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -30,7 +30,6 @@
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.config.impl.ConfigurationImpl;
 import org.jboss.messaging.core.exception.MessagingException;
-import org.jboss.messaging.core.message.Message;
 import org.jboss.messaging.core.server.MessagingService;
 import org.jboss.messaging.core.server.impl.MessagingServiceImpl;
 import org.jboss.messaging.jms.client.JBossTextMessage;

Modified: trunk/examples/messaging/src/org/jboss/messaging/example/WildCardClient.java
===================================================================
--- trunk/examples/messaging/src/org/jboss/messaging/example/WildCardClient.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/examples/messaging/src/org/jboss/messaging/example/WildCardClient.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,12 +21,15 @@
  */
 package org.jboss.messaging.example;
 
-import org.jboss.messaging.core.client.*;
+import org.jboss.messaging.core.client.ClientConsumer;
+import org.jboss.messaging.core.client.ClientMessage;
+import org.jboss.messaging.core.client.ClientProducer;
+import org.jboss.messaging.core.client.ClientSession;
+import org.jboss.messaging.core.client.ClientSessionFactory;
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.message.Message;
 import org.jboss.messaging.jms.client.JBossTextMessage;
 import org.jboss.messaging.util.SimpleString;
 

Modified: trunk/src/main/org/jboss/messaging/core/client/ClientConsumer.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/ClientConsumer.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/client/ClientConsumer.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -46,4 +46,6 @@
    boolean isClosed();   
    
    boolean isDirect();   
+   
+   Exception getLastException();
 }

Modified: trunk/src/main/org/jboss/messaging/core/client/ClientSession.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/ClientSession.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/client/ClientSession.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,14 +22,14 @@
 
 package org.jboss.messaging.core.client;
 
+import javax.transaction.xa.XAResource;
+
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.remoting.FailureListener;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionBindingQueryResponseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionQueueQueryResponseMessage;
 import org.jboss.messaging.util.SimpleString;
 
-import javax.transaction.xa.XAResource;
-
 /*
  * 
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>

Modified: trunk/src/main/org/jboss/messaging/core/client/ClientSessionFactory.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/ClientSessionFactory.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/client/ClientSessionFactory.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -18,16 +18,15 @@
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */ 
+ */
 
 package org.jboss.messaging.core.client;
 
+import java.util.Map;
+
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
 
-import java.util.Map;
-
-
 /**
  * 
  * A ClientSessionFactory
@@ -36,71 +35,61 @@
  *
  */
 public interface ClientSessionFactory
-{         
-   ClientSession createSession(boolean xa, boolean autoCommitSends, boolean autoCommitAcks,
-                               boolean cacheProducers)
-      throws MessagingException;
-      
-   ClientSession createSession(String username, String password, boolean xa, boolean autoCommitSends, boolean autoCommitAcks,
-                               boolean cacheProducers)
-      throws MessagingException;
-        
+{
+   ClientSession createSession(boolean xa, boolean autoCommitSends, boolean autoCommitAcks, boolean cacheProducers) throws MessagingException;
+
+   ClientSession createSession(String username,
+                               String password,
+                               boolean xa,
+                               boolean autoCommitSends,
+                               boolean autoCommitAcks,
+                               boolean cacheProducers) throws MessagingException;
+
    void setConsumerWindowSize(int size);
-   
+
    int getConsumerWindowSize();
-   
-   void setProducerWindowSize(int size);     
-   
+
+   void setProducerWindowSize(int size);
+
    int getProducerWindowSize();
-   
+
    void setConsumerMaxRate(int rate);
-   
+
    int getConsumerMaxRate();
-   
+
    void setProducerMaxRate(int rate);
-   
+
    int getProducerMaxRate();
-   
+
    boolean isBlockOnPersistentSend();
-   
+
    void setBlockOnPersistentSend(final boolean blocking);
-   
+
    boolean isBlockOnNonPersistentSend();
-   
+
    void setBlockOnNonPersistentSend(final boolean blocking);
-   
+
    boolean isBlockOnAcknowledge();
-   
+
    void setBlockOnAcknowledge(final boolean blocking);
 
-   boolean isAutoGroupId();
+   boolean isAutoGroupID();
 
    void setAutoGroupId(boolean autoGroupId);
-   
+
    ConnectorFactory getConnectorFactory();
 
-   void setConnectorFactory(final ConnectorFactory connectorFactory);
-
    Map<String, Object> getTransportParams();
 
-   void setTransportParams(final Map<String, Object> transportParams);
-   
    ConnectorFactory getBackupConnectorFactory();
 
-   void setBackupConnectorFactory(final ConnectorFactory connectorFactory);
-
    Map<String, Object> getBackupTransportParams();
 
-   void setBackupTransportParams(final Map<String, Object> transportParams);
-
    long getPingPeriod();
+   
+   int getPingPoolSize();
 
-   void setPingPeriod(final long pingPeriod);
-
-   long getCallTimeout();
-
-   void setCallTimeout(final long callTimeout);
+   long getCallTimeout();   
    
-   boolean isFailedOver();
-   
+   int getMaxConnections();
 }

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientConsumerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientConsumerImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientConsumerImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -73,6 +73,8 @@
 
    private volatile int creditsToSend;
 
+   private volatile Exception lastException;
+
    // Constructors
    // ---------------------------------------------------------------------------------
 
@@ -196,7 +198,9 @@
       return handler;
    }
 
-   public void setMessageHandler(final MessageHandler handler) throws MessagingException
+   //Must be synchronized since messages may be arriving while handler is being set and might otherwise end
+   //up not queueing enough executors - so messages get stranded
+   public synchronized void setMessageHandler(final MessageHandler theHandler) throws MessagingException
    {
       checkClosed();
 
@@ -206,12 +210,12 @@
                                       "Cannot set MessageHandler - consumer is in receive(...)");
       }
 
-      waitForOnMessageToComplete();
+      // If no handler before then need to queue them up
+      boolean queueUp = this.handler == null;
 
-      this.handler = handler;
+      this.handler = theHandler;
 
-      // If there are any messages in the buffer, we need to queue up executors for them
-      synchronized (this)
+      if (queueUp)
       {
          for (int i = 0; i < buffer.size(); i++)
          {
@@ -247,6 +251,11 @@
       return direct;
    }
 
+   public Exception getLastException()
+   {
+      return lastException;
+   }
+
    // ClientConsumerInternal implementation
    // --------------------------------------------------------------
 
@@ -287,14 +296,14 @@
          else
          {
             // Execute using executor
-
+        
             buffer.add(message);
 
             queueExecutor();
          }
       }
       else
-      {
+      { 
          // Add it to the buffer
          buffer.add(message);
 
@@ -308,7 +317,7 @@
       {
          buffer.clear();
       }
-      
+
       waitForOnMessageToComplete();
    }
 
@@ -326,7 +335,7 @@
    {
       return creditsToSend;
    }
-   
+
    // Public
    // ---------------------------------------------------------------------------------------
 
@@ -392,21 +401,25 @@
       }
    }
 
-   private void callOnMessage()
+   private void callOnMessage() throws Exception
    {
-      try
+      if (closed)
       {
-         if (closed)
-         {
-            return;
-         }
+         return;
+      }
 
-         // We pull the message from the buffer from inside the Runnable so we can ensure priority
-         // ordering. If we just added a Runnable with the message to the executor immediately as we get it
-         // we could not do that
+      // We pull the message from the buffer from inside the Runnable so we can ensure priority
+      // ordering. If we just added a Runnable with the message to the executor immediately as we get it
+      // we could not do that
 
-         ClientMessage message;
+      ClientMessage message;
 
+      // Must store handler in local variable since might get set to null
+      // otherwise while this is executing and give NPE when calling onMessage
+      MessageHandler theHandler = this.handler;
+
+      if (theHandler != null)
+      {
          synchronized (this)
          {
             message = buffer.poll();
@@ -422,7 +435,7 @@
             {
                onMessageThread = Thread.currentThread();
 
-               handler.onMessage(message);
+               theHandler.onMessage(message);
             }
             else
             {
@@ -430,14 +443,6 @@
             }
          }
       }
-      catch (MessagingException e)
-      {
-         log.error("Failed to execute", e);
-      }
-      catch (RuntimeException e)
-      {
-         log.error("RuntimeException thrown from handler", e);
-      }
    }
 
    private void doCleanUp(final boolean sendCloseMessage) throws MessagingException
@@ -457,7 +462,7 @@
          synchronized (this)
          {
             if (receiverThread != null)
-            {              
+            {
                // Wake up any receive() thread that might be waiting
                notify();
             }
@@ -485,7 +490,16 @@
    {
       public void run()
       {
-         callOnMessage();
+         try
+         {
+            callOnMessage();
+         }
+         catch (Exception e)
+         {
+            log.error("Failed to call onMessage()", e);
+
+            lastException = e;
+         }
       }
    }
 }

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientProducerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientProducerImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientProducerImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -12,6 +12,8 @@
 
 package org.jboss.messaging.core.client.impl;
 
+import java.util.concurrent.Semaphore;
+
 import org.jboss.messaging.core.client.AcknowledgementHandler;
 import org.jboss.messaging.core.client.ClientMessage;
 import org.jboss.messaging.core.exception.MessagingException;
@@ -25,8 +27,6 @@
 import org.jboss.messaging.util.SimpleString;
 import org.jboss.messaging.util.TokenBucketLimiter;
 
-import java.util.concurrent.Semaphore;
-
 /**
  * The client-side Producer connectionFactory class.
  * 

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -11,25 +11,29 @@
  */
 package org.jboss.messaging.core.client.impl;
 
+import static org.jboss.messaging.core.config.impl.ConfigurationImpl.DEFAULT_CALL_TIMEOUT;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.EARLY_RESPONSE;
+
+import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.locks.Lock;
 
 import org.jboss.messaging.core.client.ClientSession;
 import org.jboss.messaging.core.config.TransportConfiguration;
-import org.jboss.messaging.core.config.impl.ConfigurationImpl;
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.Channel;
 import org.jboss.messaging.core.remoting.ChannelHandler;
-import org.jboss.messaging.core.remoting.ConnectionRegistry;
+import org.jboss.messaging.core.remoting.ConnectionManager;
+import org.jboss.messaging.core.remoting.FailureListener;
 import org.jboss.messaging.core.remoting.Packet;
 import org.jboss.messaging.core.remoting.RemotingConnection;
-import org.jboss.messaging.core.remoting.impl.ConnectionRegistryImpl;
+import org.jboss.messaging.core.remoting.impl.ConnectionManagerImpl;
 import org.jboss.messaging.core.remoting.impl.wireformat.CreateSessionMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.CreateSessionResponseMessage;
 import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
 import org.jboss.messaging.core.version.Version;
-import org.jboss.messaging.util.ConcurrentHashSet;
 import org.jboss.messaging.util.UUIDGenerator;
 import org.jboss.messaging.util.VersionLoader;
 
@@ -39,8 +43,11 @@
  * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
  * @author <a href="mailto:ataylor at redhat.com">Andy Taylor</a>
  * @version <tt>$Revision: 3602 $</tt>
+ * 
+ * Note! There should never be more than one clientsessionfactory with the same connection params
+ * Otherwise failover won't work properly since channel ids won't match on live and backup
  */
-public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal
+public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, FailureListener
 {
    // Constants
    // ------------------------------------------------------------------------------------
@@ -51,6 +58,8 @@
 
    public static final long DEFAULT_PING_PERIOD = 5000;
 
+   public static final int DEFAULT_PING_POOL_SIZE = 5;
+
    public static final int DEFAULT_CONSUMER_WINDOW_SIZE = 1024 * 1024;
 
    public static final int DEFAULT_CONSUMER_MAX_RATE = -1;
@@ -67,26 +76,34 @@
 
    public static final boolean DEFAULT_AUTO_GROUP_ID = false;
 
+   public static final int DEFAULT_MAX_CONNECTIONS = 8;
+
    // Attributes
    // -----------------------------------------------------------------------------------
 
-   private ConnectionRegistry connectionRegistry;
-
    // These attributes are mutable and can be updated by different threads so
    // must be volatile
 
-   private volatile ConnectorFactory connectorFactory;
+   private final ConnectorFactory connectorFactory;
 
-   private volatile Map<String, Object> transportParams;
+   private final Map<String, Object> transportParams;
 
-   private volatile ConnectorFactory backupConnectorFactory;
+   private final ConnectorFactory backupConnectorFactory;
 
-   private volatile Map<String, Object> backupTransportParams;
+   private final Map<String, Object> backupTransportParams;
 
-   private volatile long pingPeriod;
+   private final long pingPeriod;
 
-   private volatile long callTimeout;
+   private final int pingPoolSize;
 
+   private final long callTimeout;
+
+   private final int maxConnections;
+
+   private volatile ConnectionManager connectionManager;
+
+   private volatile ConnectionManager backupConnectionManager;
+
    private volatile int consumerWindowSize;
 
    private volatile int consumerMaxRate;
@@ -101,12 +118,19 @@
 
    private volatile boolean blockOnNonPersistentSend;
 
-   private volatile boolean failedOver;
+   private volatile boolean autoGroupId;
 
-   private final Set<ClientSessionInternal> sessions = new ConcurrentHashSet<ClientSessionInternal>();
+   private final Set<ClientSessionInternal> sessions = new HashSet<ClientSessionInternal>();
+   
+   private final Object exitLock = new Object();
+   
+   private final Object createSessionLock = new Object();
+   
+   private boolean inCreateSession;
+   
+   private final Object failoverLock = new Object();
+   
 
-   private volatile boolean autoGroupId;
-
    // Static
    // ---------------------------------------------------------------------------------------
 
@@ -119,6 +143,7 @@
    public ClientSessionFactoryImpl(final TransportConfiguration connectorConfig,
                                    final TransportConfiguration backupConfig,
                                    final long pingPeriod,
+                                   final int pingPoolSize,
                                    final long callTimeout,
                                    final int consumerWindowSize,
                                    final int consumerMaxRate,
@@ -127,16 +152,42 @@
                                    final boolean blockOnAcknowledge,
                                    final boolean blockOnNonPersistentSend,
                                    final boolean blockOnPersistentSend,
-                                   final boolean autoGroupId)
+                                   final boolean autoGroupId,
+                                   final int maxConnections)
    {
       connectorFactory = instantiateConnectorFactory(connectorConfig.getFactoryClassName());
+
       transportParams = connectorConfig.getParams();
+
+      connectionManager = new ConnectionManagerImpl(connectorFactory,
+                                                    transportParams,
+                                                    pingPeriod,
+                                                    callTimeout,
+                                                    maxConnections,
+                                                    pingPoolSize);
       if (backupConfig != null)
       {
          backupConnectorFactory = instantiateConnectorFactory(backupConfig.getFactoryClassName());
+
          backupTransportParams = backupConfig.getParams();
+
+         backupConnectionManager = new ConnectionManagerImpl(backupConnectorFactory,
+                                                             backupTransportParams,
+                                                             pingPeriod,
+                                                             callTimeout,
+                                                             maxConnections,
+                                                             pingPoolSize);
       }
+      else
+      {
+         backupConnectorFactory = null;
+
+         backupTransportParams = null;
+
+         backupConnectionManager = null;
+      }
       this.pingPeriod = pingPeriod;
+      this.pingPoolSize = pingPoolSize;
       this.callTimeout = callTimeout;
       this.consumerWindowSize = consumerWindowSize;
       this.consumerMaxRate = consumerMaxRate;
@@ -146,30 +197,27 @@
       this.blockOnNonPersistentSend = blockOnNonPersistentSend;
       this.blockOnPersistentSend = blockOnPersistentSend;
       this.autoGroupId = autoGroupId;
-      connectionRegistry = ConnectionRegistryImpl.instance;
+      this.maxConnections = maxConnections;
    }
 
    public ClientSessionFactoryImpl(final TransportConfiguration connectorConfig,
                                    final TransportConfiguration backupConfig)
    {
-      connectorFactory = instantiateConnectorFactory(connectorConfig.getFactoryClassName());
-      transportParams = connectorConfig.getParams();
-      if (backupConfig != null)
-      {
-         backupConnectorFactory = instantiateConnectorFactory(backupConfig.getFactoryClassName());
-         backupTransportParams = backupConfig.getParams();
-      }
-      pingPeriod = DEFAULT_PING_PERIOD;
-      callTimeout = ConfigurationImpl.DEFAULT_CALL_TIMEOUT;
-      consumerWindowSize = DEFAULT_CONSUMER_WINDOW_SIZE;
-      consumerMaxRate = DEFAULT_CONSUMER_MAX_RATE;
-      producerWindowSize = DEFAULT_PRODUCER_WINDOW_SIZE;
-      producerMaxRate = DEFAULT_PRODUCER_MAX_RATE;
-      blockOnAcknowledge = DEFAULT_BLOCK_ON_ACKNOWLEDGE;
-      blockOnPersistentSend = DEFAULT_BLOCK_ON_PERSISTENT_SEND;
-      blockOnNonPersistentSend = DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND;
-      autoGroupId = DEFAULT_AUTO_GROUP_ID;
-      connectionRegistry = ConnectionRegistryImpl.instance;
+      this(connectorConfig,
+           backupConfig,
+           DEFAULT_PING_PERIOD,
+           DEFAULT_PING_POOL_SIZE,
+           DEFAULT_CALL_TIMEOUT,
+           DEFAULT_CONSUMER_WINDOW_SIZE,
+           DEFAULT_CONSUMER_MAX_RATE,
+           DEFAULT_PRODUCER_WINDOW_SIZE,
+           DEFAULT_PRODUCER_MAX_RATE,
+           DEFAULT_BLOCK_ON_ACKNOWLEDGE,
+           DEFAULT_BLOCK_ON_PERSISTENT_SEND,
+           DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
+           DEFAULT_AUTO_GROUP_ID,
+           DEFAULT_MAX_CONNECTIONS);
+
    }
 
    /**
@@ -177,19 +225,7 @@
     */
    public ClientSessionFactoryImpl(final TransportConfiguration connectorConfig)
    {
-      connectorFactory = instantiateConnectorFactory(connectorConfig.getFactoryClassName());
-      transportParams = connectorConfig.getParams();
-      pingPeriod = DEFAULT_PING_PERIOD;
-      callTimeout = ConfigurationImpl.DEFAULT_CALL_TIMEOUT;
-      consumerWindowSize = DEFAULT_CONSUMER_WINDOW_SIZE;
-      consumerMaxRate = DEFAULT_CONSUMER_MAX_RATE;
-      producerWindowSize = DEFAULT_PRODUCER_WINDOW_SIZE;
-      producerMaxRate = DEFAULT_PRODUCER_MAX_RATE;
-      blockOnAcknowledge = DEFAULT_BLOCK_ON_ACKNOWLEDGE;
-      blockOnPersistentSend = DEFAULT_BLOCK_ON_PERSISTENT_SEND;
-      blockOnNonPersistentSend = DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND;
-      autoGroupId = DEFAULT_AUTO_GROUP_ID;
-      connectionRegistry = ConnectionRegistryImpl.instance;
+      this(connectorConfig, null);
    }
 
    // ClientSessionFactory implementation
@@ -199,20 +235,15 @@
                                       final String password,
                                       final boolean xa,
                                       final boolean autoCommitSends,
-                                      final boolean autoCommitAcks,                             
+                                      final boolean autoCommitAcks,
                                       final boolean cacheProducers) throws MessagingException
    {
-      return createSessionInternal(username,
-                                   password,
-                                   xa,
-                                   autoCommitSends,
-                                   autoCommitAcks,                                   
-                                   cacheProducers);
+      return createSessionInternal(username, password, xa, autoCommitSends, autoCommitAcks, cacheProducers);
    }
 
    public ClientSession createSession(final boolean xa,
                                       final boolean autoCommitSends,
-                                      final boolean autoCommitAcks,                                   
+                                      final boolean autoCommitAcks,
                                       final boolean cacheProducers) throws MessagingException
    {
       return createSessionInternal(null, null, xa, autoCommitSends, autoCommitAcks, cacheProducers);
@@ -288,7 +319,7 @@
       blockOnAcknowledge = blocking;
    }
 
-   public boolean isAutoGroupId()
+   public boolean isAutoGroupID()
    {
       return autoGroupId;
    }
@@ -303,69 +334,29 @@
       return connectorFactory;
    }
 
-   public void setConnectorFactory(final ConnectorFactory connectorFactory)
-   {
-      if (!sessions.isEmpty())
-      {
-         throw new IllegalStateException("Cannot set connector factory after connections have been created");
-      }
-
-      this.connectorFactory = connectorFactory;
-   }
-
    public Map<String, Object> getTransportParams()
    {
       return transportParams;
    }
 
-   public void setTransportParams(final Map<String, Object> transportParams)
-   {
-      if (!sessions.isEmpty())
-      {
-         throw new IllegalStateException("Cannot set transport params after connections have been created");
-      }
-
-      this.transportParams = transportParams;
-   }
-
    public ConnectorFactory getBackupConnectorFactory()
    {
       return backupConnectorFactory;
    }
 
-   public void setBackupConnectorFactory(final ConnectorFactory connectorFactory)
-   {
-      if (!sessions.isEmpty())
-      {
-         throw new IllegalStateException("Cannot set backup connector factory after connections have been created");
-      }
-
-      backupConnectorFactory = connectorFactory;
-   }
-
    public Map<String, Object> getBackupTransportParams()
    {
       return backupTransportParams;
    }
 
-   public void setBackupTransportParams(final Map<String, Object> transportParams)
-   {
-      if (!sessions.isEmpty())
-      {
-         throw new IllegalStateException("Cannot set backup transport params after connections have been created");
-      }
-
-      backupTransportParams = transportParams;
-   }
-
    public long getPingPeriod()
    {
       return pingPeriod;
    }
 
-   public void setPingPeriod(final long pingPeriod)
+   public int getPingPoolSize()
    {
-      this.pingPeriod = pingPeriod;
+      return pingPoolSize;
    }
 
    public long getCallTimeout()
@@ -373,210 +364,311 @@
       return callTimeout;
    }
 
-   public void setCallTimeout(final long callTimeout)
+   public int getMaxConnections()
    {
-      this.callTimeout = callTimeout;
+      return maxConnections;
    }
 
-   public boolean isFailedOver()
-   {
-      return failedOver;
-   }
-   
-   public int getSessionCount()
-   {
-      return sessions.size();
-   }
-
    // ClientSessionFactoryInternal implementation
    // ------------------------------------------
 
    // Must be synchronized to prevent it happening concurrently with failover which can lead to
    // inconsistencies
-   public synchronized void removeSession(final ClientSessionInternal session)
+   public void removeSession(final ClientSessionInternal session)
    {
-      sessions.remove(session);
-   }
-   
-   public boolean checkFailover(final MessagingException me)
-   {
-      if (backupConnectorFactory != null)
+      //TODO - can we simplify this locking?
+      synchronized (createSessionLock)
       {
-         handleFailover(me);
-         
-         return true;
+         synchronized (failoverLock)
+         {
+            if (!sessions.remove(session))
+            {
+               throw new IllegalStateException("Cannot find session to remove " + session);
+            }
+      
+            connectionManager.returnConnection(session.getConnection().getID());
+      
+            if (backupConnectionManager != null)
+            {
+               backupConnectionManager.returnConnection(session.getBackupConnection().getID());
+            }
+         }
       }
-      else
-      {
-         return false;
-      }
    }
 
-   // Public
-   // ---------------------------------------------------------------------------------------
-
-   public void setConnectionRegistry(final ConnectionRegistry registry)
+   public int numConnections()
    {
-      connectionRegistry = registry;
+      return connectionManager.numConnections();
    }
 
-   // Protected
-   // ------------------------------------------------------------------------------------
-
-   // Package Private
-   // ------------------------------------------------------------------------------
-
-   // Private
-   // --------------------------------------------------------------------------------------
-
-   private synchronized void handleFailover(final MessagingException me)
+   public int numBackupConnections()
    {
-      log.info("Connection failure has been detected, initiating failover");
-
-      if (backupConnectorFactory == null)
-      {
-         throw new IllegalStateException("Cannot fail-over if backup connector factory is null");
-      }
-
-      for (ClientSessionInternal session : sessions)
-      {
-         // Need to get it once for each session to ensure ref count in
-         // holder is incremented properly
-         RemotingConnection backupConnection = connectionRegistry.getConnection(backupConnectorFactory,
-                                                                                backupTransportParams,
-                                                                                pingPeriod,
-                                                                                callTimeout);         
-
-         boolean ok = session.handleFailover(backupConnection);
-         
-         if (!ok)
-         {
-            //Already closed - so return it
-            connectionRegistry.returnConnection(backupConnection.getID());
-         }
-      }
-
-      connectorFactory = backupConnectorFactory;
-      transportParams = backupTransportParams;
-
-      backupConnectorFactory = null;
-      backupTransportParams = null;
-
-      failedOver = true;
-
-      log.info("Failover complete");
+      return backupConnectionManager != null ? backupConnectionManager.numConnections() : 0;
    }
 
-   private synchronized ClientSession createSessionInternal(final String username,
-                                                            final String password,
-                                                            final boolean xa,
-                                                            final boolean autoCommitSends,
-                                                            final boolean autoCommitAcks,                                                            
-                                                            final boolean cacheProducers) throws MessagingException
+   public int numSessions()
    {
-      Version clientVersion = VersionLoader.getVersion();
+      return sessions.size();
+   }
 
-      RemotingConnection connection = null;
-      try
-      {
-         connection = connectionRegistry.getConnection(connectorFactory, transportParams, pingPeriod, callTimeout);
+   // FailureListener implementation --------------------------------------------------------
 
-         String name = UUIDGenerator.getInstance().generateSimpleStringUUID().toString();
-
-         long sessionChannelID = connection.generateChannelID();
-
-         boolean hasBackup = backupConnectorFactory != null;
-
-         Packet pResponse = null;
-
-         Packet request = new CreateSessionMessage(name,
-                                                   sessionChannelID,
-                                                   clientVersion.getIncrementingVersion(),
-                                                   username,
-                                                   password,
-                                                   xa,
-                                                   autoCommitSends,
-                                                   autoCommitAcks);
-
-         Channel channel1 = connection.getChannel(1, -1, true);
-
-         try
+   public void connectionFailed(final MessagingException me)
+   {      
+      synchronized (failoverLock)
+      {         
+         //Now get locks on all channel 1s, whilst holding the failoverLock - this makes sure
+         //There are either no threads executing in createSession, or one is blocking on a createSession
+         //result.
+         
+         //Then interrupt the channel 1 that is blocking (could just interrupt them all)
+         
+         //Then release all channel 1 locks - this allows the createSession to exit the monitor
+         
+         //Then get all channel 1 locks again - this ensures the any createSession thread has executed the section and
+         //returned all its connections to the connection manager (the code to return connections to connection manager
+         //must be inside the lock
+         
+         //Then perform failover
+         
+         //Then release failoverLock
+         
+         //The other side of the bargain - during createSession:
+         //The calling thread must get the failoverLock and get its' connections when this is locked.
+         //While this is still locked it must then get the channel1 lock
+         //It can then release the failoverLock
+         //It should catch MessagingException.INTERRUPTED in the call to channel.sendBlocking
+         //It should then return its connections, with channel 1 lock still held
+         //It can then release the channel 1 lock, and retry (which will cause locking on failoverLock
+         //until failover is complete
+         
+         if (backupConnectionManager != null)
          {
-            pResponse = channel1.sendBlocking(request);
-         }
-         catch (MessagingException me)
-         {
-            if (hasBackup && me.getCode() == MessagingException.NOT_CONNECTED)
+            log.info("Commencing automatic failover");
+            lockAllChannel1s();
+            
+            final boolean needToInterrupt;
+            
+            synchronized (exitLock)
             {
-               // Failure occurred after create session was sent but before response came back
-               // in this case the blocking thread will be interrupted and throw this exception
-               log.warn("Failed to create session, will retry");
-
-               // We should be able to try again immediately - since failover will have occurred
-               pResponse = channel1.sendBlocking(request);
+               needToInterrupt = inCreateSession;
             }
-            else
+            
+            unlockAllChannel1s();
+                 
+            if (needToInterrupt)
+            {           
+               //Forcing return all channels won't guarantee that any blocked thread will return immediately
+               //So we need to wait for it
+               forceReturnAllChannel1s();
+               
+               //Now we need to make sure that the thread has actually exited and returned it's connections
+               //before failover occurs
+               
+               synchronized (exitLock)
+               {
+                  while (inCreateSession)
+                  {
+                     try
+                     {
+                        exitLock.wait(5000);
+                     }
+                     catch (InterruptedException e)
+                     {                        
+                     }
+                  }
+               }
+            }
+            
+            //Now we absolutely know that no threads are executing in or blocked in createSession, and no
+            //more will execute it until failover is complete
+            
+            //So.. do failover
+            
+            connectionManager = backupConnectionManager;
+   
+            backupConnectionManager = null;
+            
+            for (ClientSessionInternal session : sessions)
             {
-               throw me;
+               session.handleFailover();
             }
-         }
+            
+            log.info("Failover complete");
+         }                    
+      }      
+   }
+   
+   // Public
+   // ---------------------------------------------------------------------------------------
 
-         CreateSessionResponseMessage response = (CreateSessionResponseMessage)pResponse;
+   // Protected
+   // ------------------------------------------------------------------------------------
 
-         int packetConfirmationBatchSize = response.getPacketConfirmationBatchSize();
-         
-         Channel sessionChannel = connection.getChannel(sessionChannelID,                                               
-                                                        packetConfirmationBatchSize,                                               
-                                                        !hasBackup);
+   // Package Private
+   // ------------------------------------------------------------------------------
 
-         ClientSessionInternal session = new ClientSessionImpl(this,
-                                                               name,
-                                                               xa,                                                              
-                                                               cacheProducers,
-                                                               autoCommitSends,
-                                                               autoCommitAcks,
-                                                               blockOnAcknowledge,
-                                                               autoGroupId,
-                                                               connection,
-                                                               this,
-                                                               response.getServerVersion(),
-                                                               sessionChannel);
+   // Private
+   // --------------------------------------------------------------------------------------
 
-         sessions.add(session);
-
-         ChannelHandler handler = new ClientSessionPacketHandler(session);
-
-         sessionChannel.setHandler(handler);
-
-         return session;
-      }
-      catch (Throwable t)
+   
+   //The whole method must be synchonrized to prevent more than one thread executing concurrently
+   private ClientSession createSessionInternal(final String username,
+                                               final String password,
+                                               final boolean xa,
+                                               final boolean autoCommitSends,
+                                               final boolean autoCommitAcks,
+                                               final boolean cacheProducers) throws MessagingException
+   {
+      synchronized (createSessionLock)
       {
-         if (connection != null)
-         {
+         String name = UUIDGenerator.getInstance().generateSimpleStringUUID().toString();
+         boolean retry = false;
+         do
+         {         
+            Version clientVersion = VersionLoader.getVersion();
+      
+            RemotingConnection connection = null;
+      
+            RemotingConnection backupConnection = null;
+            
+            Lock lock = null;
+      
             try
-            {
-               connectionRegistry.returnConnection(connection.getID());
+            {    
+               Channel channel1;
+               
+               synchronized (failoverLock)
+               {               
+                  connection = connectionManager.getConnection();
+      
+                  if (backupConnectionManager != null)
+                  {
+                     backupConnection = backupConnectionManager.getConnection();
+                  }
+                  
+                  channel1 = connection.getChannel(1, -1);
+                  
+                  //Lock it - this must be done while the failoverLock is held
+                  channel1.getLock().lock();
+                  
+                  lock = channel1.getLock();
+               } //We can now release the failoverLock
+               
+               //We now set a flag saying createSession is executing
+               synchronized (exitLock)
+               {
+                  inCreateSession = true;
+               }
+                                    
+               long sessionChannelID = connection.generateChannelID();
+      
+               Packet request = new CreateSessionMessage(name,
+                                                         sessionChannelID,
+                                                         clientVersion.getIncrementingVersion(),
+                                                         username,
+                                                         password,
+                                                         xa,
+                                                         autoCommitSends,
+                                                         autoCommitAcks);
+      
+               Packet pResponse = channel1.sendBlocking(request);
+               
+               if (pResponse.getType() == EARLY_RESPONSE)
+               {
+                  //This means the thread was blocked on create session and failover unblocked it
+                  //so failover could occur
+                  
+                  //So we just need to return our connections and flag for retry
+                  
+                  connectionManager.returnConnection(connection.getID());               
+         
+                  backupConnectionManager.returnConnection(backupConnection.getID());
+                  
+                  retry = true;                             
+               }
+               else
+               {
+         
+                  CreateSessionResponseMessage response = (CreateSessionResponseMessage)pResponse;
+         
+                  int packetConfirmationBatchSize = response.getPacketConfirmationBatchSize();
+         
+                  Channel sessionChannel = connection.getChannel(sessionChannelID,
+                                                                 packetConfirmationBatchSize);
+         
+                  ClientSessionInternal session = new ClientSessionImpl(this,
+                                                                        name,
+                                                                        xa,
+                                                                        cacheProducers,
+                                                                        autoCommitSends,
+                                                                        autoCommitAcks,
+                                                                        blockOnAcknowledge,
+                                                                        autoGroupId,
+                                                                        connection,
+                                                                        backupConnection,
+                                                                        this,
+                                                                        response.getServerVersion(),
+                                                                        sessionChannel);
+                           
+                  sessions.add(session);
+
+                  ChannelHandler handler = new ClientSessionPacketHandler(session);
+         
+                  sessionChannel.setHandler(handler);
+         
+                  connection.addFailureListener(this);
+         
+                  return session;
+               }
             }
-            catch (Throwable ignore)
+            catch (Throwable t)
             {
+               if (connection != null)
+               {
+                  connectionManager.returnConnection(connection.getID());
+               }
+      
+               if (backupConnection != null)
+               {
+                  backupConnectionManager.returnConnection(backupConnection.getID());
+               }
+      
+               if (t instanceof MessagingException)
+               {
+                  throw (MessagingException)t;
+               }
+               else
+               {
+                  MessagingException me = new MessagingException(MessagingException.INTERNAL_ERROR,
+                                                                 "Failed to create session");
+      
+                  me.initCause(t);
+      
+                  throw me;
+               }
+            } 
+            finally
+            {
+               if (lock != null)
+               {
+                  lock.unlock();
+               }
+               
+               //Execution has finished so notify any failover thread that may be waiting for us to be done
+               synchronized (exitLock)
+               {
+                  inCreateSession = false;
+                  
+                  exitLock.notify();
+               }                     
             }
          }
-
-         if (t instanceof MessagingException)
-         {
-            throw (MessagingException)t;
-         }
-         else
-         {
-            MessagingException me = new MessagingException(MessagingException.INTERNAL_ERROR,
-                                                           "Failed to start connection");
-
-            me.initCause(t);
-
-            throw me;
-         }
+         while (retry);
       }
+      
+      //Should never get here
+      throw new IllegalStateException("How did you get here??");
    }
 
    private ConnectorFactory instantiateConnectorFactory(final String connectorFactoryClassName)
@@ -593,5 +685,42 @@
                                             "\"", e);
       }
    }
+   
+   private void lockAllChannel1s()
+   {
+      Set<RemotingConnection> conns = connectionManager.getConnections();
+      
+      for (RemotingConnection conn: conns)
+      {
+         Channel channel1 = conn.getChannel(1, -1);
+         
+         channel1.getLock().lock();
+      }
+   }
+   
+   private void unlockAllChannel1s()
+   {
+      Set<RemotingConnection> conns = connectionManager.getConnections();
+      
+      for (RemotingConnection conn: conns)
+      {
+         Channel channel1 = conn.getChannel(1, -1);
+         
+         channel1.getLock().unlock();
+      }
+   }
+   
+   private void forceReturnAllChannel1s()
+   {
+      Set<RemotingConnection> conns = connectionManager.getConnections();
+      
+      for (RemotingConnection conn: conns)
+      {
+         Channel channel1 = conn.getChannel(1, -1);
+         
+         channel1.returnBlocking();
+      }
+   }
+   
 
 }

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryInternal.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryInternal.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryInternal.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,7 +22,6 @@
 package org.jboss.messaging.core.client.impl;
 
 import org.jboss.messaging.core.client.ClientSessionFactory;
-import org.jboss.messaging.core.exception.MessagingException;
 
 /**
  * A ClientSessionFactoryInternal
@@ -34,5 +33,11 @@
 {
    void removeSession(ClientSessionInternal session);
    
-   boolean checkFailover(MessagingException me);
+   //for testing
+   
+   int numConnections();
+   
+   int numBackupConnections();
+   
+   int numSessions();
 }

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -41,11 +41,9 @@
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.Channel;
-import org.jboss.messaging.core.remoting.ConnectionRegistry;
 import org.jboss.messaging.core.remoting.FailureListener;
 import org.jboss.messaging.core.remoting.Packet;
 import org.jboss.messaging.core.remoting.RemotingConnection;
-import org.jboss.messaging.core.remoting.impl.ConnectionRegistryImpl;
 import org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl;
 import org.jboss.messaging.core.remoting.impl.wireformat.ReattachSessionMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.ReattachSessionResponseMessage;
@@ -128,6 +126,8 @@
    private final Executor executor;
 
    private volatile RemotingConnection remotingConnection;
+   
+   private volatile RemotingConnection backupConnection;
 
    private final Map<Long, ClientProducerInternal> producers = new ConcurrentHashMap<Long, ClientProducerInternal>();
 
@@ -151,17 +151,13 @@
 
    private final int version;
 
-   private ConnectionRegistry connectionRegistry;
-
    // For testing only
    private boolean forceNotSameRM;
 
    private final IDGenerator idGenerator = new SimpleIDGenerator(0);
 
-   private volatile boolean failedOver;
-
    private volatile boolean started;
-
+   
    // Constructors ----------------------------------------------------------------------------
 
    public ClientSessionImpl(final ClientSessionFactoryInternal sessionFactory,
@@ -173,6 +169,7 @@
                             final boolean blockOnAcknowledge,
                             final boolean autoGroupId,
                             final RemotingConnection remotingConnection,
+                            final RemotingConnection backupConnection,
                             final ClientSessionFactory connectionFactory,
                             final int version,
                             final Channel channel) throws MessagingException
@@ -182,6 +179,8 @@
       this.name = name;
 
       this.remotingConnection = remotingConnection;
+      
+      this.backupConnection = backupConnection;
 
       this.connectionFactory = connectionFactory;
 
@@ -210,11 +209,7 @@
 
       this.channel = channel;
 
-      this.version = version;
-
-      connectionRegistry = ConnectionRegistryImpl.instance;
-
-      remotingConnection.addFailureListener(this);
+      this.version = version;      
    }
 
    // ClientSession implementation
@@ -225,7 +220,7 @@
                            final SimpleString filterString,
                            final boolean durable,
                            final boolean temp) throws MessagingException
-   {
+   {   
       checkClosed();
 
       SessionCreateQueueMessage request = new SessionCreateQueueMessage(address, queueName, filterString, durable, temp);
@@ -234,14 +229,14 @@
    }
 
    public void deleteQueue(final SimpleString queueName) throws MessagingException
-   {
+   {    
       checkClosed();
 
       channel.sendBlocking(new SessionDeleteQueueMessage(queueName));
    }
 
    public SessionQueueQueryResponseMessage queueQuery(final SimpleString queueName) throws MessagingException
-   {
+   {    
       checkClosed();
 
       SessionQueueQueryMessage request = new SessionQueueQueryMessage(queueName);
@@ -252,7 +247,7 @@
    }
 
    public SessionBindingQueryResponseMessage bindingQuery(final SimpleString address) throws MessagingException
-   {
+   {    
       checkClosed();
 
       SessionBindingQueryMessage request = new SessionBindingQueryMessage(address);
@@ -263,7 +258,7 @@
    }
 
    public void addDestination(final SimpleString address, final boolean durable, final boolean temp) throws MessagingException
-   {
+   {     
       checkClosed();
 
       SessionAddDestinationMessage request = new SessionAddDestinationMessage(address, durable, temp);
@@ -272,7 +267,7 @@
    }
 
    public void removeDestination(final SimpleString address, final boolean durable) throws MessagingException
-   {
+   {     
       checkClosed();
 
       SessionRemoveDestinationMessage request = new SessionRemoveDestinationMessage(address, durable);
@@ -281,7 +276,7 @@
    }
 
    public ClientConsumer createConsumer(final SimpleString queueName) throws MessagingException
-   {
+   {      
       checkClosed();
 
       return createConsumer(queueName, null, false);
@@ -290,7 +285,7 @@
    public ClientConsumer createConsumer(final SimpleString queueName,
                                         final SimpleString filterString,
                                         final boolean direct) throws MessagingException
-   {
+   {     
       checkClosed();
 
       return createConsumer(queueName,
@@ -318,7 +313,7 @@
                                         final int windowSize,
                                         final int maxRate,
                                         final boolean browseOnly) throws MessagingException
-   {
+   {     
       checkClosed();
 
       SessionCreateConsumerMessage request = new SessionCreateConsumerMessage(queueName,
@@ -378,7 +373,7 @@
 
 
    public ClientProducer createProducer(final SimpleString address) throws MessagingException
-   {
+   {      
       checkClosed();
 
       return createProducer(address, connectionFactory.getProducerWindowSize(), connectionFactory.getProducerMaxRate());
@@ -412,7 +407,7 @@
                                         final int maxRate,
                                         final boolean blockOnNonPersistentSend,
                                         final boolean blockOnPersistentSend) throws MessagingException
-   {
+   {    
       checkClosed();
 
       ClientProducerInternal producer = null;
@@ -553,7 +548,7 @@
    }
 
    public void start() throws MessagingException
-   {
+   {    
       checkClosed();
 
       if (!started)
@@ -565,7 +560,7 @@
    }
 
    public void stop() throws MessagingException
-   {
+   {   
       checkClosed();
 
       if (started)
@@ -601,7 +596,7 @@
 
    // This acknowledges all messages received by the consumer so far
    public void acknowledge(final long consumerID, final long messageID) throws MessagingException
-   {
+   {     
       checkClosed();
 
       SessionAcknowledgeMessage message = new SessionAcknowledgeMessage(consumerID, messageID, blockOnAcknowledge);
@@ -677,7 +672,7 @@
    }
 
    public void close() throws MessagingException
-   {
+   {     
       if (closed)
       {
          return;
@@ -710,13 +705,13 @@
    }
 
    //Needs to be synchronized to prevent issues with occurring concurrently with close()
-   public synchronized boolean handleFailover(final RemotingConnection backupConnection)
+   public synchronized void handleFailover()
    {
       if (closed)
       {
-         return false;
+         return ;
       }
-
+      
       // We lock the channel to prevent any packets to be added to the resend
       // cache during the failover process
       channel.lock();
@@ -731,26 +726,26 @@
 
          Packet request = new ReattachSessionMessage(name, channel.getLastReceivedCommandID());
 
-         Channel channel1 = backupConnection.getChannel(1, -1, true);
+         Channel channel1 = backupConnection.getChannel(1, -1);
+        
+         ReattachSessionResponseMessage response = (ReattachSessionResponseMessage)channel1.sendBlocking(request);         
 
-         ReattachSessionResponseMessage response = (ReattachSessionResponseMessage)channel1.sendBlocking(request);
-
          if (!response.isRemoved())
          {
             channel.replayCommands(response.getLastReceivedCommandID());
          }
          else
          {
-            // There may be a create session call blocking - the response will never come because the session has been
+            // There may be a close session call blocking - the response will never come because the session has been
             // closed on the server so we need to interrupt it
-            channel.interruptBlocking();
+            channel.returnBlocking();
          }
+         
+         backupConnection = null;
       }
       catch (Throwable t)
       {
          log.error("Failed to handle failover", t);
-
-         return false;
       }
       finally
       {
@@ -758,10 +753,9 @@
       }
 
       channel.send(new SessionFailoverCompleteMessage(name));
-
-      failedOver = true;
-
-      return true;
+      
+      //Now we can add a failure listener since if a further failure occurs we cleanup since no backup any more
+      remotingConnection.addFailureListener(this);
    }
 
    // XAResource implementation
@@ -1023,7 +1017,6 @@
       }
       catch (MessagingException e)
       {
-         log.error("Caught jmsexecptione ", e);
          // This should never occur
          throw new XAException(XAException.XAER_RMERR);
       }
@@ -1032,21 +1025,15 @@
    // FailureListener implementation --------------------------------------------
 
    public void connectionFailed(final MessagingException me)
-   {
-      if (!sessionFactory.checkFailover(me))
+   { 
+      try
       {
-         if (!failedOver)
-         {
-            try
-            {
-               cleanUp();
-            }
-            catch (Exception e)
-            {
-               log.error("Failed to cleanup session");
-            }
-         }
+         cleanUp();
       }
+      catch (Exception e)
+      {
+         log.error("Failed to cleanup session");
+      }         
    }
 
    // Public
@@ -1057,15 +1044,15 @@
       forceNotSameRM = force;
    }
 
-   public void setConnectionRegistry(final ConnectionRegistry registry)
-   {
-      connectionRegistry = registry;
-   }
-
    public RemotingConnection getConnection()
    {
       return remotingConnection;
    }
+   
+   public RemotingConnection getBackupConnection()
+   {
+      return backupConnection;
+   }
 
    // Protected
    // ----------------------------------------------------------------------------
@@ -1106,11 +1093,9 @@
       {
          closed = true;
          
-         channel.close();
-
-         connectionRegistry.returnConnection(remotingConnection.getID());
-      }
-
+         channel.close();                                  
+      }  
+      
       sessionFactory.removeSession(this);
    }
 
@@ -1147,5 +1132,4 @@
          producer.close();
       }
    }
-
 }

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionInternal.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionInternal.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionInternal.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -12,15 +12,15 @@
 
 package org.jboss.messaging.core.client.impl;
 
+import java.util.Map;
+import java.util.Set;
+
 import org.jboss.messaging.core.client.ClientMessage;
 import org.jboss.messaging.core.client.ClientSession;
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.remoting.RemotingConnection;
 import org.jboss.messaging.util.SimpleString;
 
-import java.util.Map;
-import java.util.Set;
-
 /**
  * A ClientSessionInternal
  * 
@@ -50,5 +50,9 @@
 
    void handleReceiveMessage(long consumerID, ClientMessage message) throws Exception;
 
-   boolean handleFailover(final RemotingConnection backupConnection);
+   void handleFailover();
+   
+   RemotingConnection getConnection();
+   
+   RemotingConnection getBackupConnection();
 }

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionPacketHandler.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionPacketHandler.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionPacketHandler.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -30,7 +30,6 @@
 import org.jboss.messaging.core.remoting.ChannelHandler;
 import org.jboss.messaging.core.remoting.Packet;
 import org.jboss.messaging.core.remoting.impl.wireformat.MessagingExceptionMessage;
-import org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionProducerFlowCreditMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionReceiveMessage;
 

Modified: trunk/src/main/org/jboss/messaging/core/config/Configuration.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/config/Configuration.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/config/Configuration.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,12 +22,12 @@
 
 package org.jboss.messaging.core.config;
 
-import org.jboss.messaging.core.server.JournalType;
-
 import java.io.Serializable;
 import java.util.List;
 import java.util.Set;
 
+import org.jboss.messaging.core.server.JournalType;
+
 /**
  * 
  * A Configuration

Modified: trunk/src/main/org/jboss/messaging/core/config/impl/FileConfiguration.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/config/impl/FileConfiguration.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/config/impl/FileConfiguration.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,6 +22,13 @@
 
 package org.jboss.messaging.core.config.impl;
 
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Map;
+
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.server.JournalType;
@@ -31,13 +38,6 @@
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-
 /**
  * ConfigurationImpl
  * This class allows the Configuration class to be configured via a config file.

Modified: trunk/src/main/org/jboss/messaging/core/exception/MessagingException.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/exception/MessagingException.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/exception/MessagingException.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -42,6 +42,8 @@
    public static final int NOT_CONNECTED = 002;
    
    public static final int CONNECTION_TIMEDOUT = 003;
+   
+   public static final int INTERRUPTED = 004;
 
    
    public static final int QUEUE_DOES_NOT_EXIST = 100;

Modified: trunk/src/main/org/jboss/messaging/core/filter/impl/FilterImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/filter/impl/FilterImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/filter/impl/FilterImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,15 +22,15 @@
 
 package org.jboss.messaging.core.filter.impl;
 
+import java.util.HashMap;
+import java.util.Map;
+
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.filter.Filter;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.util.SimpleString;
 
-import java.util.HashMap;
-import java.util.Map;
-
 /**
 * This class implements a JBoss Messaging filter
 * 

Modified: trunk/src/main/org/jboss/messaging/core/message/Message.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/message/Message.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/message/Message.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -24,7 +24,6 @@
 
 import java.util.Set;
 
-import org.jboss.messaging.core.journal.EncodingSupport;
 import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
 import org.jboss.messaging.util.SimpleString;
 

Modified: trunk/src/main/org/jboss/messaging/core/message/impl/MessageImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/message/impl/MessageImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/message/impl/MessageImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,15 +22,19 @@
 
 package org.jboss.messaging.core.message.impl;
 
+import static org.jboss.messaging.util.DataConstants.SIZE_BOOLEAN;
+import static org.jboss.messaging.util.DataConstants.SIZE_BYTE;
+import static org.jboss.messaging.util.DataConstants.SIZE_INT;
+import static org.jboss.messaging.util.DataConstants.SIZE_LONG;
+
+import java.util.Set;
+
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.message.Message;
 import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
-import static org.jboss.messaging.util.DataConstants.*;
 import org.jboss.messaging.util.SimpleString;
 import org.jboss.messaging.util.TypedProperties;
 
-import java.util.Set;
-
 /**
  * A concrete implementation of a message
  *

Modified: trunk/src/main/org/jboss/messaging/core/paging/PagingManager.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/paging/PagingManager.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/paging/PagingManager.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,14 +22,14 @@
 
 package org.jboss.messaging.core.paging;
 
+import java.util.Collection;
+
 import org.jboss.messaging.core.journal.SequentialFile;
 import org.jboss.messaging.core.postoffice.PostOffice;
 import org.jboss.messaging.core.server.MessagingComponent;
 import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.util.SimpleString;
 
-import java.util.Collection;
-
 /**
  * 
  * <p>Look at the <a href="http://wiki.jboss.org/wiki/JBossMessaging2Paging">WIKI</a> for more information.</p>

Modified: trunk/src/main/org/jboss/messaging/core/paging/impl/PagingManagerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/paging/impl/PagingManagerImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/paging/impl/PagingManagerImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,6 +22,15 @@
 
 package org.jboss.messaging.core.paging.impl;
 
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.paging.LastPageRecord;
 import org.jboss.messaging.core.paging.PageMessage;
@@ -38,15 +47,6 @@
 import org.jboss.messaging.util.SimpleString;
 import org.jboss.messaging.util.TypedProperties;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicLong;
-
 /**
  *  <p>Look at the <a href="http://wiki.jboss.org/wiki/JBossMessaging2Paging">WIKI</a> for more information.</p>
  * 

Modified: trunk/src/main/org/jboss/messaging/core/persistence/StorageManager.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/persistence/StorageManager.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/persistence/StorageManager.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,6 +22,11 @@
 
 package org.jboss.messaging.core.persistence;
 
+import java.util.List;
+import java.util.Map;
+
+import javax.transaction.xa.Xid;
+
 import org.jboss.messaging.core.paging.LastPageRecord;
 import org.jboss.messaging.core.paging.PageTransactionInfo;
 import org.jboss.messaging.core.postoffice.Binding;
@@ -34,10 +39,6 @@
 import org.jboss.messaging.core.transaction.ResourceManager;
 import org.jboss.messaging.util.SimpleString;
 
-import javax.transaction.xa.Xid;
-import java.util.List;
-import java.util.Map;
-
 /**
  * 
  * A StorageManager

Modified: trunk/src/main/org/jboss/messaging/core/persistence/impl/journal/JournalStorageManager.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/persistence/impl/journal/JournalStorageManager.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/persistence/impl/journal/JournalStorageManager.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,6 +22,17 @@
 
 package org.jboss.messaging.core.persistence.impl.journal;
 
+import java.io.File;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.atomic.AtomicLong;
+
+import javax.transaction.xa.Xid;
+
 import org.jboss.messaging.core.config.Configuration;
 import org.jboss.messaging.core.filter.Filter;
 import org.jboss.messaging.core.filter.impl.FilterImpl;
@@ -59,16 +70,6 @@
 import org.jboss.messaging.util.SimpleString;
 import org.jboss.messaging.util.TimeAndCounterIDGenerator;
 
-import javax.transaction.xa.Xid;
-import java.io.File;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.atomic.AtomicLong;
-
 /**
  * 
  * A JournalStorageManager

Modified: trunk/src/main/org/jboss/messaging/core/persistence/impl/nullpm/NullStorageManager.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/persistence/impl/nullpm/NullStorageManager.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/persistence/impl/nullpm/NullStorageManager.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,6 +22,11 @@
 
 package org.jboss.messaging.core.persistence.impl.nullpm;
 
+import java.util.List;
+import java.util.Map;
+
+import javax.transaction.xa.Xid;
+
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.paging.LastPageRecord;
 import org.jboss.messaging.core.paging.PageTransactionInfo;
@@ -37,10 +42,6 @@
 import org.jboss.messaging.util.SimpleString;
 import org.jboss.messaging.util.TimeAndCounterIDGenerator;
 
-import javax.transaction.xa.Xid;
-import java.util.List;
-import java.util.Map;
-
 /**
  * 
  * A NullStorageManager

Modified: trunk/src/main/org/jboss/messaging/core/postoffice/Address.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/postoffice/Address.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/postoffice/Address.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,10 +21,10 @@
  */
 package org.jboss.messaging.core.postoffice;
 
+import java.util.List;
+
 import org.jboss.messaging.util.SimpleString;
 
-import java.util.List;
-
 /**
  * USed to hold a hierarchichal style address, delimited by a '.'.
  *

Modified: trunk/src/main/org/jboss/messaging/core/postoffice/AddressManager.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/postoffice/AddressManager.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/postoffice/AddressManager.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,12 +21,12 @@
  */
 package org.jboss.messaging.core.postoffice;
 
-import org.jboss.messaging.util.SimpleString;
-
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
+import org.jboss.messaging.util.SimpleString;
+
 /**
  * Used to maintain addresses and Bindings.
  * 

Modified: trunk/src/main/org/jboss/messaging/core/postoffice/PostOffice.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/postoffice/PostOffice.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/postoffice/PostOffice.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -30,6 +30,7 @@
 import org.jboss.messaging.core.paging.PagingManager;
 import org.jboss.messaging.core.server.MessageReference;
 import org.jboss.messaging.core.server.MessagingComponent;
+import org.jboss.messaging.core.server.SendLock;
 import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.util.SimpleString;
 
@@ -85,4 +86,6 @@
    void activate();
    
    PagingManager getPagingManager();
+   
+   SendLock getAddressLock(SimpleString address);
 }

Modified: trunk/src/main/org/jboss/messaging/core/postoffice/impl/AddressImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/postoffice/impl/AddressImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/postoffice/impl/AddressImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,14 +21,15 @@
  */
 package org.jboss.messaging.core.postoffice.impl;
 
-import org.jboss.messaging.core.postoffice.Address;
 import static org.jboss.messaging.core.postoffice.impl.WildcardAddressManager.DELIM;
 import static org.jboss.messaging.core.postoffice.impl.WildcardAddressManager.SINGLE_WORD;
-import org.jboss.messaging.util.SimpleString;
 
 import java.util.ArrayList;
 import java.util.List;
 
+import org.jboss.messaging.core.postoffice.Address;
+import org.jboss.messaging.util.SimpleString;
+
 /**splits an address string into its hierarchical parts split by '.'
  * @author <a href="mailto:andy.taylor at jboss.org">Andy Taylor</a>
  */

Modified: trunk/src/main/org/jboss/messaging/core/postoffice/impl/FlowControllerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/postoffice/impl/FlowControllerImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/postoffice/impl/FlowControllerImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,14 +22,14 @@
 
 package org.jboss.messaging.core.postoffice.impl;
 
+import java.util.concurrent.ConcurrentLinkedQueue;
+
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.postoffice.FlowController;
 import org.jboss.messaging.core.postoffice.PostOffice;
 import org.jboss.messaging.core.server.ServerProducer;
 import org.jboss.messaging.util.SimpleString;
 
-import java.util.concurrent.ConcurrentLinkedQueue;
-
 /**
  * 
  * A FlowControllerImpl

Modified: trunk/src/main/org/jboss/messaging/core/postoffice/impl/PostOfficeImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/postoffice/impl/PostOfficeImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/postoffice/impl/PostOfficeImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -45,7 +45,9 @@
 import org.jboss.messaging.core.server.MessageReference;
 import org.jboss.messaging.core.server.Queue;
 import org.jboss.messaging.core.server.QueueFactory;
+import org.jboss.messaging.core.server.SendLock;
 import org.jboss.messaging.core.server.ServerMessage;
+import org.jboss.messaging.core.server.impl.SendLockImpl;
 import org.jboss.messaging.core.transaction.ResourceManager;
 import org.jboss.messaging.util.SimpleString;
 
@@ -80,7 +82,9 @@
    private final ManagementService managementService;
 
    private final ResourceManager resourceManager;
-
+   
+   private Map<SimpleString, SendLock> addressLocks = new HashMap<SimpleString, SendLock>();
+   
    public PostOfficeImpl(final StorageManager storageManager,
                          final PagingManager pagingManager,
                          final QueueFactory queueFactory,
@@ -110,7 +114,7 @@
       {
          addressManager = new SimpleAddressManager();
       }
-      
+
       this.backup = backup;
    }
 
@@ -149,7 +153,7 @@
 
    // PostOffice implementation -----------------------------------------------
 
-   public boolean addDestination(final SimpleString address, final boolean durable) throws Exception
+   public synchronized boolean addDestination(final SimpleString address, final boolean durable) throws Exception
    {
       boolean added = addressManager.addDestination(address);
 
@@ -167,7 +171,7 @@
       return added;
    }
 
-   public boolean removeDestination(final SimpleString address, final boolean durable) throws Exception
+   public synchronized boolean removeDestination(final SimpleString address, final boolean durable) throws Exception
    {
       boolean removed = addressManager.removeDestination(address);
 
@@ -181,11 +185,13 @@
          }
          managementService.unregisterAddress(address);
       }
+            
+      addressLocks.remove(address);
 
       return removed;
    }
 
-   public boolean containsDestination(final SimpleString address)
+   public synchronized boolean containsDestination(final SimpleString address)
    {
       return addressManager.containsDestination(address);
    }
@@ -195,11 +201,17 @@
       return addressManager.getDestinations();
    }
 
-   public Binding addBinding(final SimpleString address,
-                             final SimpleString queueName,
-                             final Filter filter,
-                             final boolean durable,
-                             boolean temporary) throws Exception
+   //TODO - needs to be synchronized to prevent happening concurrently with activate().
+   //(and possible removeBinding and other methods)
+   //Otherwise can have situation where createQueue comes in before failover, then failover occurs
+   //and post office is activated but queue remains unactivated after failover so delivery never occurs
+   //even though failover is complete
+   //TODO - more subtle locking could be used -this is a bit heavy handed
+   public synchronized Binding addBinding(final SimpleString address,
+                                          final SimpleString queueName,
+                                          final Filter filter,
+                                          final boolean durable,
+                                          boolean temporary) throws Exception
    {
       Binding binding = createBinding(address, queueName, filter, durable, temporary);
 
@@ -209,11 +221,11 @@
       {
          storageManager.addBinding(binding);
       }
-
+            
       return binding;
    }
 
-   public Binding removeBinding(final SimpleString queueName) throws Exception
+   public synchronized Binding removeBinding(final SimpleString queueName) throws Exception
    {
       Binding binding = removeQueueInMemory(queueName);
 
@@ -268,7 +280,7 @@
          }
 
          List<Binding> bindings = addressManager.getBindings(address);
-         
+
          List<MessageReference> refs = new ArrayList<MessageReference>();
 
          if (bindings != null)
@@ -290,6 +302,7 @@
 
          return refs;
       }
+            
 
    }
 
@@ -307,18 +320,32 @@
    {
       return flowControllers.get(address);
    }
-
-   public void activate()
+   
+   public synchronized void activate()
    {
       this.backup = false;
-      
+
       Map<SimpleString, Binding> nameMap = addressManager.getBindings();
 
       for (Binding binding : nameMap.values())
       {
          binding.getQueue().activate();
-      }            
+      }
    }
+   
+   public synchronized SendLock getAddressLock(final SimpleString address)
+   {
+      SendLock lock = addressLocks.get(address);
+                  
+      if (lock == null)
+      {
+         lock = new SendLockImpl();
+         
+         addressLocks.put(address, lock);
+      }
+      
+      return lock;
+   }
 
    // Private -----------------------------------------------------------------
 

Modified: trunk/src/main/org/jboss/messaging/core/postoffice/impl/SimpleAddressManager.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/postoffice/impl/SimpleAddressManager.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/postoffice/impl/SimpleAddressManager.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,12 +21,6 @@
  */
 package org.jboss.messaging.core.postoffice.impl;
 
-import org.jboss.messaging.core.postoffice.AddressManager;
-import org.jboss.messaging.core.postoffice.Binding;
-import org.jboss.messaging.util.ConcurrentHashSet;
-import org.jboss.messaging.util.ConcurrentSet;
-import org.jboss.messaging.util.SimpleString;
-
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
@@ -35,6 +29,12 @@
 import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.CopyOnWriteArrayList;
 
+import org.jboss.messaging.core.postoffice.AddressManager;
+import org.jboss.messaging.core.postoffice.Binding;
+import org.jboss.messaging.util.ConcurrentHashSet;
+import org.jboss.messaging.util.ConcurrentSet;
+import org.jboss.messaging.util.SimpleString;
+
 /**
  * A simple address manager that maintains the addresses and bindings.
  *

Modified: trunk/src/main/org/jboss/messaging/core/postoffice/impl/WildcardAddressManager.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/postoffice/impl/WildcardAddressManager.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/postoffice/impl/WildcardAddressManager.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,16 +21,16 @@
  */
 package org.jboss.messaging.core.postoffice.impl;
 
-import org.jboss.messaging.core.postoffice.Address;
-import org.jboss.messaging.core.postoffice.Binding;
-import org.jboss.messaging.util.SimpleString;
-
 import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.CopyOnWriteArrayList;
 
+import org.jboss.messaging.core.postoffice.Address;
+import org.jboss.messaging.core.postoffice.Binding;
+import org.jboss.messaging.util.SimpleString;
+
 /**
  * extends the simple manager to allow wilcard addresses to be used.
  *

Modified: trunk/src/main/org/jboss/messaging/core/remoting/Channel.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/Channel.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/remoting/Channel.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -11,7 +11,7 @@
  */
 package org.jboss.messaging.core.remoting;
 
-import java.util.Queue;
+import java.util.concurrent.locks.Lock;
 
 import org.jboss.messaging.core.exception.MessagingException;
 
@@ -50,25 +50,29 @@
 
    void unlock();
 
-   void interruptBlocking();
+   void returnBlocking();
    
-   //debug only
-   Queue<Command> getSentCommands();
+   Lock getLock();
    
-   Queue<Command> getReceivedCommands();
+   RemotingConnection getConnection();
    
-   // For debug only
-   static class Command
-   {
-      public final int commandID;
-
-      public final Packet packet;
-
-      public Command(final int commandID, final Packet packet)
-      {
-         this.commandID = commandID;
-
-         this.packet = packet;
-      }
-   }
+//   //debug only
+//   Queue<Command> getSentCommands();
+//   
+//   Queue<Command> getReceivedCommands();
+//   
+//   // For debug only
+//   static class Command
+//   {
+//      public final int commandID;
+//
+//      public final Packet packet;
+//
+//      public Command(final int commandID, final Packet packet)
+//      {
+//         this.commandID = commandID;
+//
+//         this.packet = packet;
+//      }
+//   }
 }

Added: trunk/src/main/org/jboss/messaging/core/remoting/ConnectionManager.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/ConnectionManager.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/remoting/ConnectionManager.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -0,0 +1,48 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+
+package org.jboss.messaging.core.remoting;
+
+import java.util.Set;
+
+/**
+ * A ConnectionManager
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * 
+ * Created 24 Oct 2008 09:07:05
+ *
+ *
+ */
+public interface ConnectionManager
+{
+   RemotingConnection getConnection();
+   
+   RemotingConnection createConnection();
+   
+   void returnConnection(Object connectionID);
+   
+   int numConnections();
+   
+   Set<RemotingConnection> getConnections();
+}

Deleted: trunk/src/main/org/jboss/messaging/core/remoting/ConnectionRegistry.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/ConnectionRegistry.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/remoting/ConnectionRegistry.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -1,51 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */ 
-
-package org.jboss.messaging.core.remoting;
-
-import java.util.Map;
-
-import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
-
-/**
- * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- * @version <tt>$Revision$</tt>
- */
-public interface ConnectionRegistry
-{
-   RemotingConnection getConnection(ConnectorFactory connectorFactory, Map<String, Object> params,
-                                    long pingInterval, long callTimeout);
-   
-   RemotingConnection getConnectionNoCache(ConnectorFactory connectorFactory, Map<String, Object> params,
-                                           long pingInterval, long callTimeout);
-   
-   void returnConnection(Object connectionID);
-   
-   int size();
-   
-   int getCount(ConnectorFactory connectorFactory, Map<String, Object> params);
-   
-   void clear();
-   
-   void dump();
-}
\ No newline at end of file

Modified: trunk/src/main/org/jboss/messaging/core/remoting/Packet.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/Packet.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/remoting/Packet.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -47,7 +47,5 @@
    
    boolean isRequiresConfirmations();
    
-   boolean isWriteAlways();
-   
-   boolean isRequiresGlobalOrdering();      
+   boolean isWriteAlways();     
 }

Modified: trunk/src/main/org/jboss/messaging/core/remoting/RemotingConnection.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/RemotingConnection.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/remoting/RemotingConnection.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -26,7 +26,7 @@
 {
    Object getID();
 
-   Channel getChannel(long channelID, int packetConfirmationBatchSize, boolean interruptBlockOnFailure);
+   Channel getChannel(long channelID, int packetConfirmationBatchSize);
 
    long generateChannelID();
 
@@ -49,4 +49,6 @@
    long getIDGeneratorSequence();
    
    void activate();
+   
+   void freeze();
 }

Added: trunk/src/main/org/jboss/messaging/core/remoting/impl/ConnectionManagerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/ConnectionManagerImpl.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/ConnectionManagerImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -0,0 +1,331 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.jboss.messaging.core.remoting.impl;
+
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+
+import org.jboss.messaging.core.exception.MessagingException;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.remoting.ConnectionManager;
+import org.jboss.messaging.core.remoting.RemotingConnection;
+import org.jboss.messaging.core.remoting.spi.Connection;
+import org.jboss.messaging.core.remoting.spi.ConnectionLifeCycleListener;
+import org.jboss.messaging.core.remoting.spi.Connector;
+import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
+import org.jboss.messaging.util.JBMThreadFactory;
+
+/**
+ * A ConnectionManagerImpl
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * 
+ * Created 24 Oct 2008 09:08:12
+ *
+ *
+ */
+public class ConnectionManagerImpl implements ConnectionManager, ConnectionLifeCycleListener
+{
+   private static final Logger log = Logger.getLogger(ConnectionManagerImpl.class);
+   
+   private final ConnectorFactory connectorFactory;
+   
+   private final Map<String, Object> params;
+   
+   private final long pingInterval;
+   
+   private final long callTimeout;
+   
+   private final int maxConnections;
+       
+   //TODO - allow this to be configurable
+   private static final ScheduledThreadPoolExecutor pingExecutor = new ScheduledThreadPoolExecutor(5,
+                                                                             new JBMThreadFactory("jbm-pinger-threads"));
+   
+   private final Map<Object, ConnectionEntry> connections = new LinkedHashMap<Object, ConnectionEntry>();
+      
+   private int refCount;
+   
+   private Iterator<ConnectionEntry> mapIterator;
+   
+   private Object failConnectionLock = new Object();
+      
+   public ConnectionManagerImpl(final ConnectorFactory connectorFactory,
+                                final Map<String, Object> params,
+                                final long pingInterval,
+                                final long callTimeout,
+                                final int maxConnections,
+                                final int pingPoolSize)  // FIXME - pingPoolSize is not used
+   {
+      this.connectorFactory = connectorFactory;
+      
+      this.params = params;
+      
+      this.pingInterval = pingInterval;
+      
+      this.callTimeout = callTimeout;
+      
+      this.maxConnections = maxConnections; 
+   }
+    
+   public RemotingConnection createConnection()
+   {
+      DelegatingBufferHandler handler = new DelegatingBufferHandler();
+
+      NoCacheConnectionLifeCycleListener listener = new NoCacheConnectionLifeCycleListener();
+
+      Connector connector = connectorFactory.createConnector(params, handler, listener);
+
+      connector.start();
+
+      Connection tc = connector.createConnection();
+
+      if (tc == null)
+      {
+         throw new IllegalStateException("Failed to connect");
+      }
+
+      RemotingConnection connection = new RemotingConnectionImpl(tc, callTimeout, pingInterval, pingExecutor, null);
+
+      handler.conn = connection;
+
+      listener.conn = connection;
+
+      connection.startPinger();
+
+      return connection;
+   }
+   
+   public synchronized RemotingConnection getConnection()
+   {
+      RemotingConnection conn;
+
+      if (connections.size() < maxConnections)
+      {
+         // Create a new one
+
+         DelegatingBufferHandler handler = new DelegatingBufferHandler();
+
+         Connector connector = connectorFactory.createConnector(params, handler, this);
+
+         connector.start();
+
+         Connection tc = connector.createConnection();
+
+         if (tc == null)
+         {
+            throw new IllegalStateException("Failed to connect");
+         }
+
+         conn = new RemotingConnectionImpl(tc, callTimeout, pingInterval, pingExecutor, null);
+
+         handler.conn = conn;
+
+         conn.startPinger();
+
+         connections.put(conn.getID(), new ConnectionEntry(conn, connector));
+      }
+      else
+      {
+         // Return one round-robin from the list
+         
+         if (mapIterator == null || !mapIterator.hasNext())
+         {
+            mapIterator = connections.values().iterator();
+         }
+
+         ConnectionEntry entry = mapIterator.next();
+         
+         conn = entry.connection;            
+      }
+      
+      refCount++;
+      
+      return conn;
+   }
+   
+   public synchronized void returnConnection(final Object connectionID)
+   {              
+      ConnectionEntry entry = connections.get(connectionID);
+      
+      if (refCount != 0)
+      {
+         refCount--;
+      }
+      
+      if (entry != null)
+      {                  
+         checkCloseConnections();
+      }
+      else
+      {
+         //Can be legitimately null if session was closed before then went to remove session from csf
+         //and locked since failover had started then after failover removes it but it's already been failed
+      }
+   }
+    
+   public void failConnection(final MessagingException me)
+   {      
+      synchronized (failConnectionLock)
+      {
+         //When a single connection fails, we fail *all* the connections
+         
+         Set<ConnectionEntry> copy = new HashSet<ConnectionEntry>(connections.values());         
+         
+         for (ConnectionEntry entry: copy)
+         {
+            entry.connection.fail(me);      
+         }
+         
+         refCount = 0;
+      }
+   }
+   
+   public synchronized int getRefCount()
+   {
+      return refCount;
+   }
+   
+   public synchronized int numConnections()
+   {    
+      return connections.size();
+   }
+   
+   public synchronized Set<RemotingConnection> getConnections()
+   {
+      Set<RemotingConnection> conns = new HashSet<RemotingConnection>();
+      
+      for (ConnectionEntry entry: connections.values())
+      {
+         conns.add(entry.connection);
+      }
+      
+      return conns;
+   }
+   
+   // Private -------------------------------------------------------
+   
+   private void checkCloseConnections()
+   {
+      if (refCount == 0)
+      {
+         //Close connections
+            
+         Set<ConnectionEntry> copy = new HashSet<ConnectionEntry>(connections.values());
+         
+         connections.clear();    
+         
+         for (ConnectionEntry entry: copy)
+         {
+            try
+            {
+               entry.connection.destroy();
+            
+               entry.connector.close();
+            }
+            catch (Throwable ignore)
+            {                  
+            }                                    
+         }                                    
+      }
+   }
+   
+   // ConnectionLifeCycleListener implementation --------------------
+
+   public void connectionCreated(final Connection connection)
+   {
+   }
+
+   public void connectionDestroyed(final Object connectionID)
+   {      
+      // If conn still exists here this means that the underlying transport
+      // conn has been closed from the server side without
+      // being returned from the client side so we need to fail the conn and
+      // call it's listeners
+      MessagingException me = new MessagingException(MessagingException.OBJECT_CLOSED,
+                                                     "The conn has been closed.");
+      failConnection(me);              
+   }
+
+   public void connectionException(final Object connectionID, final MessagingException me)
+   {
+      failConnection(me);      
+   }
+   
+   // Inner classes ----------------------------------------------------------------
+   
+   private class ConnectionEntry
+   {
+      ConnectionEntry(final RemotingConnection connection, final Connector connector)
+      {
+         this.connection = connection;
+         
+         this.connector = connector;
+      }
+      
+      final RemotingConnection connection;
+      
+      final Connector connector;
+   }
+   
+   private class DelegatingBufferHandler extends AbstractBufferHandler
+   {
+      RemotingConnection conn;
+
+      public void bufferReceived(final Object connectionID, final MessagingBuffer buffer)
+      {
+         conn.bufferReceived(connectionID, buffer);
+      }
+   }
+   
+   private static class NoCacheConnectionLifeCycleListener implements ConnectionLifeCycleListener
+   {
+      private RemotingConnection conn;
+
+      public void connectionCreated(final Connection connection)
+      {
+      }
+
+      public void connectionDestroyed(final Object connectionID)
+      {
+         if (conn != null)
+         {
+            conn.destroy();
+         }
+      }
+
+      public void connectionException(final Object connectionID, final MessagingException me)
+      {
+         if (conn != null)
+         {
+            conn.fail(me);
+         }
+      }
+   }
+
+}

Deleted: trunk/src/main/org/jboss/messaging/core/remoting/impl/ConnectionRegistryImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/ConnectionRegistryImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/ConnectionRegistryImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -1,429 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-
-package org.jboss.messaging.core.remoting.impl;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-
-import org.jboss.messaging.core.exception.MessagingException;
-import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.remoting.ConnectionRegistry;
-import org.jboss.messaging.core.remoting.RemotingConnection;
-import org.jboss.messaging.core.remoting.spi.Connection;
-import org.jboss.messaging.core.remoting.spi.ConnectionLifeCycleListener;
-import org.jboss.messaging.core.remoting.spi.Connector;
-import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
-import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
-import org.jboss.messaging.util.JBMThreadFactory;
-
-/**
- * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- * @version <tt>$Revision$</tt>
- */
-public class ConnectionRegistryImpl implements ConnectionRegistry, ConnectionLifeCycleListener
-{
-   // Constants -----------------------------------------------------
-
-   public static final Logger log = Logger.getLogger(ConnectionRegistryImpl.class);
-
-   // Attributes ----------------------------------------------------
-
-   private final Map<RegistryKey, ConnectionHolder> connections = new ConcurrentHashMap<RegistryKey, ConnectionHolder>();
-
-   private final Map<Object, RegistryKey> reverseMap = new ConcurrentHashMap<Object, RegistryKey>();
-
-   // TODO - core pool size should be configurable
-   private final ScheduledThreadPoolExecutor pingExecutor = new ScheduledThreadPoolExecutor(10,
-                                                                                            new JBMThreadFactory("jbm-pinger-threads"));
-
-   // Static --------------------------------------------------------
-
-   public static ConnectionRegistry instance = new ConnectionRegistryImpl();
-
-   // ConnectionRegistry implementation -----------------------------
-
-   public synchronized RemotingConnection getConnection(final ConnectorFactory connectorFactory,
-                                                        final Map<String, Object> params,
-                                                        final long pingInterval,
-                                                        final long callTimeout)
-   {
-      RegistryKey key = new RegistryKey(connectorFactory, params);
-
-      ConnectionHolder holder = connections.get(key);
-
-      if (holder != null)
-      {
-         holder.increment();
-         
-         RemotingConnection connection = holder.getConnection();
-
-         return connection;
-      }
-      else
-      {
-         DelegatingBufferHandler handler = new DelegatingBufferHandler();
-
-         Connector connector = connectorFactory.createConnector(params, handler, this);
-
-         connector.start();
-
-         Connection tc = connector.createConnection();
-
-         if (tc == null)
-         {
-            throw new IllegalStateException("Failed to connect");
-         }
-
-         RemotingConnection connection = new RemotingConnectionImpl(tc,
-                                                                    callTimeout,
-                                                                    pingInterval,                                                             
-                                                                    pingExecutor,
-                                                                    null);        
-
-         handler.conn = connection;
-
-         connection.startPinger();
-
-         holder = new ConnectionHolder(connection, connector);
-
-         connections.put(key, holder);
-
-         reverseMap.put(tc.getID(), key);
-
-         return connection;
-      }
-   }
-
-   public RemotingConnection getConnectionNoCache(final ConnectorFactory connectorFactory,
-                                                  final Map<String, Object> params,
-                                                  final long pingInterval,
-                                                  final long callTimeout)
-   {
-      DelegatingBufferHandler handler = new DelegatingBufferHandler();
-
-      NoCacheConnectionLifeCycleListener listener = new NoCacheConnectionLifeCycleListener();
-
-      Connector connector = connectorFactory.createConnector(params, handler, listener);
-
-      connector.start();
-
-      Connection tc = connector.createConnection();
-
-      if (tc == null)
-      {
-         throw new IllegalStateException("Failed to connect");
-      }
-
-      RemotingConnection connection = new RemotingConnectionImpl(tc,
-                                                                 callTimeout,
-                                                                 pingInterval,                                                            
-                                                                 pingExecutor,
-                                                                 null);        
-
-      handler.conn = connection;
-
-      listener.conn = connection;
-
-      connection.startPinger();
-
-      return connection;
-   }
-
-   public synchronized void returnConnection(final Object connectionID)
-   {
-      
-      RegistryKey key = reverseMap.get(connectionID);
-
-      if (key == null)
-      {
-         // This is ok and might happen if conn is returned after an error
-         // occurred on it in which
-         // case it will have already automatically been closed and removed
-         log.warn("Connection not found when returning - probably conn has failed and been automatically removed");
-         return;
-      }
-
-      ConnectionHolder holder = connections.get(key);
-      
-      if (holder.getCount() == 1)
-      {
-         RemotingConnection conn = holder.getConnection();
-
-         reverseMap.remove(connectionID);
-
-         connections.remove(key);
-
-         conn.destroy();
-
-         holder.getConnector().close();
-      }
-      else
-      {
-         holder.decrement();
-      }
-   }
-
-   public synchronized int size()
-   {  
-      return connections.size();
-   }
-
-   public synchronized int getCount(final ConnectorFactory connectorFactory, final Map<String, Object> params)
-   {
-      RegistryKey key = new RegistryKey(connectorFactory, params);
-
-      ConnectionHolder holder = connections.get(key);
-
-      if (holder != null)
-      {
-         return holder.getCount();
-      }
-      else
-      {
-         return 0;
-      }
-   }
-
-   public synchronized void clear()
-   {
-      connections.clear();
-      
-      reverseMap.clear();
-   }
-
-   public void dump()
-   {
-      for (ConnectionHolder holder : connections.values())
-      {
-         log.info("=============================");
-         log.info("connection " + System.identityHashCode(holder.connection) + " count " + holder.count);
-         for (StackTraceElement elem: holder.trace)
-         {
-            log.info(elem.toString());
-         }
-      }
-   }
-
-   // Constructors --------------------------------------------------
-
-   // Public --------------------------------------------------------
-
-   // ConnectionLifeCycleListener implementation --------------------
-
-   public void connectionCreated(final Connection connection)
-   {
-   }
-
-   public void connectionDestroyed(final Object connectionID)
-   {
-      RegistryKey key = reverseMap.remove(connectionID);
-
-      if (key != null)
-      {
-         ConnectionHolder holder = connections.remove(key);
-         
-         if (holder != null)
-         {
-            // If conn still exists here this means that the underlying transport
-            // conn has been closed from the server side without
-            // being returned from the client side so we need to fail the conn and
-            // call it's listeners
-            MessagingException me = new MessagingException(MessagingException.OBJECT_CLOSED, "The conn has been closed.");
-            holder.getConnection().fail(me);
-         }
-      }
-   }
-
-   public void connectionException(final Object connectionID, final MessagingException me)
-   {
-      RegistryKey key = reverseMap.remove(connectionID);
-
-      if (key == null)
-      {
-         throw new IllegalStateException("Cannot find conn with id " + connectionID);
-      }
-
-      ConnectionHolder holder = connections.remove(key);
-      
-      if (holder != null)
-      {
-         holder.getConnection().fail(me);
-      }
-   }
-
-   // Package protected ---------------------------------------------
-
-   // Protected -----------------------------------------------------
-
-   // Private -------------------------------------------------------
-
-   // Inner classes -------------------------------------------------
-
-   private static class NoCacheConnectionLifeCycleListener implements ConnectionLifeCycleListener
-   {
-      private RemotingConnection conn;
-
-      public void connectionCreated(final Connection connection)
-      {
-      }
-
-      public void connectionDestroyed(final Object connectionID)
-      {
-         if (conn != null)
-         {
-            conn.destroy();
-         }
-      }
-
-      public void connectionException(final Object connectionID, final MessagingException me)
-      {
-         if (conn != null)
-         {
-            conn.fail(me);
-         }
-      }
-   }
-
-   private static class ConnectionHolder
-   {
-      private final RemotingConnection connection;
-
-      private final Connector connector;
-
-      private int count;
-      
-      private StackTraceElement[] trace;
-
-      public ConnectionHolder(final RemotingConnection connection, final Connector connector)
-      {
-         assert connector != null;
-
-         this.connection = connection;
-         this.connector = connector;
-         count = 1;
-         
-         trace = Thread.currentThread().getStackTrace();
-      }
-
-      public void increment()
-      {
-         count++;
-      }
-
-      public void decrement()
-      {
-         count--;
-      }
-
-      public int getCount()
-      {
-         return count;
-      }
-
-      public RemotingConnection getConnection()
-      {
-         return connection;
-      }
-
-      public Connector getConnector()
-      {
-         return connector;
-      }
-   }
-
-   private class RegistryKey
-   {
-      private final String connectorFactoryClassName;
-
-      private final Map<String, Object> params;
-
-      RegistryKey(final ConnectorFactory connectorFactory, final Map<String, Object> params)
-      {
-         connectorFactoryClassName = connectorFactory.getClass().getName();
-
-         this.params = params;
-      }
-
-      @Override
-      public boolean equals(final Object other)
-      {
-         RegistryKey kother = (RegistryKey)other;
-
-         if (connectorFactoryClassName.equals(kother.connectorFactoryClassName))
-         {
-            if (params == null)
-            {
-               return kother.params == null;
-            }
-            else
-            {
-               if (kother.params == null)
-               {
-                  return false;
-               }
-               else if (params.size() == kother.params.size())
-               {
-                  for (Map.Entry<String, Object> entry : params.entrySet())
-                  {
-                     Object thisVal = entry.getValue();
-
-                     Object otherVal = kother.params.get(entry.getKey());
-
-                     if (otherVal == null || !otherVal.equals(thisVal))
-                     {
-                        return false;
-                     }
-                  }
-                  return true;
-               }
-               else
-               {
-                  return false;
-               }
-            }
-         }
-         else
-         {
-            return false;
-         }
-      }
-
-      @Override
-      public int hashCode()
-      {
-         return connectorFactoryClassName.hashCode();
-      }
-   }
-
-   private class DelegatingBufferHandler extends AbstractBufferHandler
-   {
-      RemotingConnection conn;
-
-      public void bufferReceived(final Object connectionID, final MessagingBuffer buffer)
-      {
-         conn.bufferReceived(connectionID, buffer);
-      }
-   }
-}

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingConnectionImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingConnectionImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingConnectionImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -14,6 +14,7 @@
 
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.CREATESESSION;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.CREATESESSION_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.EARLY_RESPONSE;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.EXCEPTION;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.NULL_RESPONSE;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.PACKETS_CONFIRMED;
@@ -21,6 +22,7 @@
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.PONG;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.REATTACH_SESSION;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.REATTACH_SESSION_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.REPLICATE_CREATESESSION;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.REPLICATION_RESPONSE;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_ACKNOWLEDGE;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_ADD_DESTINATION;
@@ -68,9 +70,6 @@
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_XA_SUSPEND;
 
 import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Queue;
@@ -83,7 +82,6 @@
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.locks.Condition;
 import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReadWriteLock;
 import java.util.concurrent.locks.ReentrantLock;
 
 import org.jboss.messaging.core.exception.MessagingException;
@@ -105,6 +103,7 @@
 import org.jboss.messaging.core.remoting.impl.wireformat.Pong;
 import org.jboss.messaging.core.remoting.impl.wireformat.ReattachSessionMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.ReattachSessionResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.ReplicateCreateSessionMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionAcknowledgeMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionAddDestinationMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionBindingQueryMessage;
@@ -211,157 +210,18 @@
 
    private boolean idGeneratorSynced = false;
 
-   private final ReadWriteLock readWriteLock;
-
    private final Object transferLock = new Object();
-
+   
+   private final ChannelHandler ppHandler = new PingPongHandler();
+   
+   private boolean frozen;
+   
+   private final Object failLock = new Object();
+      
    // debug only stuff
 
    private boolean createdActive;
-
-   public static volatile boolean debug = false;
-
-   private static final int MAX_DEBUG_CACHE_SIZE = 1000;
-
-   private static final Map<Long, Channel> serverLiveChannels = new LinkedHashMap<Long, Channel>();
-
-   private static final Map<Long, Channel> serverBackupChannels = new LinkedHashMap<Long, Channel>();
-
-   private static final Map<Long, Channel> clientChannels = new LinkedHashMap<Long, Channel>();
-
-   private static void report()
-   {
-      log.info("=================================================================");
-      log.info("Report on channel history");
-      log.info("-------------------------");
-      log.info(" ");
-      log.info("Server--->Client traffic");
-      log.info("------------------------");
-      for (Channel serverBackupChannel : serverBackupChannels.values())
-      {
-         Channel serverLiveChannel = serverLiveChannels.get(serverBackupChannel.getID());
-
-         Channel clientChannel = clientChannels.get(serverBackupChannel.getID());
-
-         log.info("Channel id: " + serverBackupChannel.getID());
-         log.info("Backup     Live     Client");
-         Iterator<Channel.Command> backup = serverBackupChannel.getSentCommands().iterator();
-         Iterator<Channel.Command> live = serverLiveChannel == null ? null : serverLiveChannel.getSentCommands()
-                                                                                              .iterator();
-         Iterator<Channel.Command> client = clientChannel == null ? null : clientChannel.getReceivedCommands()
-                                                                                        .iterator();
-
-         while (backup.hasNext() || (live != null && live.hasNext()) || (client != null && client.hasNext()))
-         {
-            String line = "";
-            byte bkpPacketType = -1;
-            byte livePacketType = -1;
-            byte clientPacketType = -1;
-            if (backup.hasNext())
-            {
-               Channel.Command backupCommand = backup.next();
-               line += "id:" + backupCommand.commandID + " type:" + backupCommand.packet.getType() + ", ";
-               bkpPacketType = backupCommand.packet.getType();
-            }
-            else
-            {
-               line += "--------------";
-            }
-            if (live != null && live.hasNext())
-            {
-               Channel.Command liveCommand = live.next();
-               line += "id:" + liveCommand.commandID + " type:" + liveCommand.packet.getType() + ", ";
-               livePacketType = liveCommand.packet.getType();
-            }
-            else
-            {
-               line += "--------------";
-            }
-            if (client != null && client.hasNext())
-            {
-               Channel.Command clientCommand = client.next();
-               line += "id:" + clientCommand.commandID + " type:" + clientCommand.packet.getType() + ", ";
-               clientPacketType = clientCommand.packet.getType();
-            }
-            else
-            {
-               line += "--------------";
-            }
-            log.info(line);
-            if (bkpPacketType != -1 && livePacketType != -1 && clientPacketType != -1 &&
-                     (bkpPacketType != livePacketType || livePacketType != clientPacketType))
-            {
-               log.info("*** ERROR Packets in wrong sequence ***");
-            }
-         }
-      }
-      
-      log.info("Client--->Server traffic");
-      log.info("------------------------");
-      for (Channel serverBackupChannel : serverBackupChannels.values())
-      {
-         Channel serverLiveChannel = serverLiveChannels.get(serverBackupChannel.getID());
-
-         Channel clientChannel = clientChannels.get(serverBackupChannel.getID());
-
-         log.info("Channel id: " + serverBackupChannel.getID());
-         log.info("Backup     Live     Client");
-         Iterator<Channel.Command> backup = serverBackupChannel.getReceivedCommands().iterator();
-         Iterator<Channel.Command> live = serverLiveChannel == null ? null : serverLiveChannel.getReceivedCommands()
-                                                                                              .iterator();
-         Iterator<Channel.Command> client = clientChannel == null ? null : clientChannel.getSentCommands()
-                                                                                        .iterator();
-
-         while (backup.hasNext() || (live != null && live.hasNext()) || (client != null && client.hasNext()))
-         {
-            String line = "";
-            byte bkpPacketType = -1;
-            byte livePacketType = -1;
-            byte clientPacketType = -1;
-            if (backup.hasNext())
-            {
-               Channel.Command backupCommand = backup.next();
-               line += "id:" + backupCommand.commandID + " type:" + backupCommand.packet.getType() + ", ";
-               bkpPacketType = backupCommand.packet.getType();
-            }
-            else
-            {
-               line += "--------------";
-            }
-            if (live != null && live.hasNext())
-            {
-               Channel.Command liveCommand = live.next();
-               line += "id:" + liveCommand.commandID + " type:" + liveCommand.packet.getType() + ", ";
-               livePacketType = liveCommand.packet.getType();
-            }
-            else
-            {
-               line += "--------------";
-            }
-            if (client != null && client.hasNext())
-            {
-               Channel.Command clientCommand = client.next();
-               line += "id:" + clientCommand.commandID + " type:" + clientCommand.packet.getType() + ", ";
-               clientPacketType = clientCommand.packet.getType();
-            }
-            else
-            {
-               line += "--------------";
-            }
-            log.info(line);
-            if (bkpPacketType != -1 && livePacketType != -1 && clientPacketType != -1 &&
-                     (bkpPacketType != livePacketType || livePacketType != clientPacketType))
-            {
-               log.info("*** ERROR Packets in wrong sequence ***");
-            }
-         }
-      }
-      
-      log.info("End of report====================================================");
-   }
-
-   // end debug only stuff
-
+  
    // Constructors
    // ---------------------------------------------------------------------------------
 
@@ -374,33 +234,29 @@
                                  final ScheduledExecutorService pingExecutor,
                                  final List<Interceptor> interceptors)
    {
-      this(transportConnection, blockingCallTimeout, pingPeriod, pingExecutor, interceptors, null, true, null, true);
+      this(transportConnection, blockingCallTimeout, pingPeriod, pingExecutor, interceptors, null, true, true);
    }
 
    /*
     * Create a server side connection
     */
    public RemotingConnectionImpl(final Connection transportConnection,
-                                 final long blockingCallTimeout,
-                                 final long pingPeriod,
-                                 final ScheduledExecutorService pingExecutor,
+                                 final long blockingCallTimeout,                                
                                  final List<Interceptor> interceptors,
                                  final RemotingConnection replicatingConnection,
-                                 final boolean active,
-                                 final ReadWriteLock readWriteLock)
+                                 final boolean active)
 
    {
       this(transportConnection,
            blockingCallTimeout,
-           pingPeriod,
-           pingExecutor,
+           -1,
+           null,
            interceptors,
            replicatingConnection,
            active,
-           readWriteLock,
            false);
    }
-
+   
    private RemotingConnectionImpl(final Connection transportConnection,
                                   final long blockingCallTimeout,
                                   final long pingPeriod,
@@ -408,7 +264,6 @@
                                   final List<Interceptor> interceptors,
                                   final RemotingConnection replicatingConnection,
                                   final boolean active,
-                                  final ReadWriteLock readWriteLock,
                                   final boolean client)
 
    {
@@ -426,13 +281,9 @@
 
       this.pingExecutor = pingExecutor;
 
-      this.readWriteLock = readWriteLock;
-
       // Channel zero is reserved for pinging
-      pingChannel = getChannel(0, -1, false);
+      pingChannel = getChannel(0, -1);
 
-      final ChannelHandler ppHandler = new PingPongHandler();
-
       pingChannel.setHandler(ppHandler);
 
       this.client = client;
@@ -465,35 +316,15 @@
    }
 
    public synchronized Channel getChannel(final long channelID,
-                                          final int packetConfirmationBatchSize,
-                                          final boolean interruptBlockOnFailure)
+                                          final int packetConfirmationBatchSize)
    {
       ChannelImpl channel = channels.get(channelID);
 
       if (channel == null)
       {
-         channel = new ChannelImpl(this, channelID, packetConfirmationBatchSize, interruptBlockOnFailure);
+         channel = new ChannelImpl(this, channelID, packetConfirmationBatchSize);
 
          channels.put(channelID, channel);
-
-         if (debug)
-         {
-            if (client)
-            {
-               clientChannels.put(channelID, channel);
-            }
-            else
-            {
-               if (createdActive)
-               {
-                  serverLiveChannels.put(channelID, channel);
-               }
-               else
-               {
-                  serverBackupChannels.put(channelID, channel);
-               }
-            }
-         }
       }
 
       return channel;
@@ -524,8 +355,6 @@
       return transportConnection.createBuffer(size);
    }
 
-   private final Object failLock = new Object();
-
    /*
     * This can be called concurrently by more than one thread so needs to be locked
     */
@@ -540,16 +369,16 @@
          }
 
          log.warn(me.getMessage());
-
+         
          // Then call the listeners
          callListeners(me);
-
+        
          internalClose();
 
          for (Channel channel : channels.values())
          {
             channel.fail();
-         }
+         }                  
       }
    }
 
@@ -609,59 +438,35 @@
    {
       final Packet packet = decode(buffer);
 
-      final long channelID = packet.getChannelID();
-
-      // FIXME - need to redo global ordering since this won't work with multiple connections
-      // Instead use lastSeq technique
-
-      final boolean useLock = readWriteLock != null;
-
-      if (useLock)
+      synchronized (transferLock)
       {
-         if (packet.isRequiresGlobalOrdering() || packet.getType() == REPLICATION_RESPONSE)
+         if (!frozen)
          {
-            readWriteLock.writeLock().lock();
-         }
-         else
-         {
-            readWriteLock.readLock().lock();
-         }
-      }
-
-      try
-      {
-         // This needs to be synchronized so plays nice with transfer connection
-         synchronized (transferLock)
-         {
-            final ChannelImpl channel = channels.get(channelID);
-
+            final ChannelImpl channel = channels.get(packet.getChannelID());
+   
             if (channel != null)
             {
                channel.handlePacket(packet);
             }
          }
       }
-      finally
-      {
-         if (useLock)
-         {
-            if (packet.isRequiresGlobalOrdering() || packet.getType() == REPLICATION_RESPONSE)
-            {
-               readWriteLock.writeLock().unlock();
-            }
-            else
-            {
-               readWriteLock.readLock().unlock();
-            }
-         }
-      }
    }
 
    public void activate()
    {
       active = true;
    }
-
+   
+   public void freeze()
+   {
+      //Prevent any more packets being handled on this connection
+      
+      synchronized (transferLock)
+      {
+         frozen = true;
+      }
+   }
+   
    // Package protected
    // ----------------------------------------------------------------------------
 
@@ -719,7 +524,7 @@
    // private static AtomicInteger specialSeq = new AtomicInteger(0);
 
    private void doWrite(final Packet packet)
-   {
+   {      
       final MessagingBuffer buffer = transportConnection.createBuffer(PacketImpl.INITIAL_BUFFER_SIZE);
 
       packet.encode(buffer);
@@ -765,6 +570,11 @@
             packet = new CreateSessionMessage();
             break;
          }
+         case REPLICATE_CREATESESSION:
+         {
+            packet = new ReplicateCreateSessionMessage();
+            break;
+         }
          case CREATESESSION_RESP:
          {
             packet = new CreateSessionResponseMessage();
@@ -1044,10 +854,6 @@
 
       private volatile boolean closed;
 
-      private final boolean interruptBlockOnFailure;
-
-      private Thread blockThread;
-
       private final Lock lock = new ReentrantLock();
 
       private final Condition sendCondition = lock.newCondition();
@@ -1060,18 +866,9 @@
 
       private final Queue<DelayedResult> responseActions = new ConcurrentLinkedQueue<DelayedResult>();
 
-      // debug stuff
-
-      private final Queue<Command> receivedCommandsCache;
-
-      private final Queue<Command> sentCommandsCache;
-
-      // end debug stuff
-
       private ChannelImpl(final RemotingConnectionImpl connection,
                           final long id,
-                          final int packetConfirmationBatchSize,
-                          final boolean interruptBlockOnFailure)
+                          final int packetConfirmationBatchSize)
       {
          this.connection = connection;
 
@@ -1081,10 +878,15 @@
          {
             // Don't want to send confirmations if replicating to backup
             this.packetConfirmationBatchSize = -1;
-
-            replicatingChannel = connection.replicatingConnection.getChannel(id, -1, interruptBlockOnFailure);
-
-            replicatingChannel.setHandler(new ReplicatedPacketsConfirmedChannelHandler());
+            
+            //We don't redirect the ping channel
+            
+            if (id != 0)
+            {
+               replicatingChannel = connection.replicatingConnection.getChannel(id, -1);
+   
+               replicatingChannel.setHandler(new ReplicatedPacketsConfirmedChannelHandler());
+            }
          }
          else
          {
@@ -1103,21 +905,6 @@
          {
             resendCache = null;
          }
-
-         this.interruptBlockOnFailure = interruptBlockOnFailure;
-
-         if (debug)
-         {
-            this.sentCommandsCache = new LinkedList<Command>();
-
-            this.receivedCommandsCache = new LinkedList<Command>();
-         }
-         else
-         {
-            this.sentCommandsCache = null;
-
-            this.receivedCommandsCache = null;
-         }
       }
 
       public long getID()
@@ -1129,15 +916,19 @@
       {
          return lastReceivedCommandID;
       }
+      
+      public Lock getLock()
+      {
+         return lock;
+      }
 
-      // Interrupt a blocking close session
-      public void interruptBlocking()
+      public void returnBlocking()
       {
          lock.lock();
 
          try
          {
-            response = new NullResponseMessage();
+            response = new PacketImpl(EARLY_RESPONSE);
 
             sendCondition.signal();
          }
@@ -1212,8 +1003,6 @@
 
             addToCache(packet);
 
-            blockThread = Thread.currentThread();
-
             response = null;
 
             connection.doWrite(packet);
@@ -1228,15 +1017,8 @@
                {
                   sendCondition.await(toWait, TimeUnit.MILLISECONDS);
                }
-               catch (final InterruptedException e)
-               {
-                  if (interruptBlockOnFailure)
-                  {
-                     if (connection.destroyed)
-                     {
-                        throw new MessagingException(MessagingException.NOT_CONNECTED, "Connection failed");
-                     }
-                  }
+               catch (InterruptedException e)
+               {                  
                }
 
                final long now = System.currentTimeMillis();
@@ -1265,21 +1047,10 @@
          }
          finally
          {
-            blockThread = null;
-
             lock.unlock();
          }
       }
 
-      /*
-       * With replication we must satisfy two rules:
-       * 1) A command must replicated and processed on the backup and liive before the result on the live is returned
-       * 2) A command must be processed on the live before the next command is processed on the live
-       * We replicate as follows:
-       * As a command arrives on the live, we replicate to the backup where it will get processed, we then immediately process
-       * it on the live, but we stop short of sending the result back from the live until the result of completion has
-       * arrived back from the backup. This is what the DelayedResult is used for.
-       */
       public DelayedResult replicatePacket(final Packet packet)
       {
          if (replicatingChannel != null)
@@ -1355,41 +1126,31 @@
       }
 
       public void fail()
-      {
-         if (interruptBlockOnFailure)
-         {
-            lock.lock();
-            try
-            {
-               if (blockThread != null)
-               {
-                  blockThread.interrupt();
-               }
-            }
-            finally
-            {
-               lock.unlock();
-            }
-         }
+      {         
       }
 
       public Channel getReplicatingChannel()
       {
          return replicatingChannel;
       }
-
+            
       public void transferConnection(final RemotingConnection newConnection)
       {
          // Needs to synchronize on the connection to make sure no packets from
          // the old connection get processed after transfer has occurred
          synchronized (connection.transferLock)
-         {
+         {          
             connection.channels.remove(id);
 
             // And switch it
 
             final RemotingConnectionImpl rnewConnection = (RemotingConnectionImpl)newConnection;
 
+            if (rnewConnection.channels.containsKey(id))
+            {
+               throw new IllegalStateException("Backup connection already has channel with id " + id);
+            }
+
             rnewConnection.channels.put(id, this);
 
             connection = rnewConnection;
@@ -1425,36 +1186,14 @@
 
          lock.unlock();
       }
-
-      public Queue<Command> getSentCommands()
+      
+      public RemotingConnection getConnection()
       {
-         return this.sentCommandsCache;
+         return connection;
       }
 
-      public Queue<Command> getReceivedCommands()
-      {
-         return this.receivedCommandsCache;
-      }
-
-      // we need to do a thorough investigation of how packets confirmed get
-      //
-      // a) replicated from client through live to backup without dealing with on live
-      // b) got redirected back to client from server
-
       private void handlePacket(final Packet packet)
       {
-         if (debug)
-         {
-            int commandID = packet.isRequiresConfirmations() ? lastReceivedCommandID + 1 : -1;
-
-            receivedCommandsCache.add(new Command(commandID, packet));
-
-            if (receivedCommandsCache.size() == MAX_DEBUG_CACHE_SIZE)
-            {
-               receivedCommandsCache.poll();
-            }
-         }
-
          if (packet.getType() == PACKETS_CONFIRMED)
          {
             if (resendCache != null)
@@ -1541,35 +1280,18 @@
                nextConfirmation += packetConfirmationBatchSize;
 
                confirmed.setChannelID(id);
-               
-               if (debug)
-               {
-                  this.sentCommandsCache.add(new Command(-1, confirmed));
-               }
 
                connection.doWrite(confirmed);
             }
          }
       }
 
-      private volatile int lastSentID;
-
       private void addToCache(final Packet packet)
       {
          if (resendCache != null)
          {
             resendCache.add(packet);
          }
-
-         if (debug && packet.getType() != PacketImpl.SESS_REPLICATE_DELIVERY)
-         {
-            sentCommandsCache.add(new Command(lastSentID++, packet));
-
-            if (sentCommandsCache.size() == MAX_DEBUG_CACHE_SIZE)
-            {
-               sentCommandsCache.poll();
-            }
-         }
       }
 
       private void clearUpTo(final int lastReceivedCommandID)
@@ -1587,7 +1309,7 @@
 
             if (packet == null)
             {
-               report();
+               // report();
                throw new IllegalStateException(System.identityHashCode(this) + " Can't find packet to clear: " +
                                                " last received command id " +
                                                lastReceivedCommandID +
@@ -1608,25 +1330,28 @@
       }
 
       private class ReplicatedPacketsConfirmedChannelHandler implements ChannelHandler
-      {
+      {  
          public void handlePacket(final Packet packet)
          {
-            if (packet.getType() == PACKETS_CONFIRMED)
-            {
-               if (debug)
+            switch (packet.getType())
+            {                          
+               case PACKETS_CONFIRMED:
                {
-                  sentCommandsCache.add(new Command(-1, packet));
+                  connection.doWrite(packet);
+                  
+                  break;
                }
-               connection.doWrite(packet);
+               case REPLICATION_RESPONSE:
+               {
+                  replicateResponseReceived();
+                  
+                  break;
+               }
+               default:
+               {
+                  throw new IllegalArgumentException("Invalid packet " + packet);
+               }
             }
-            else if (packet.getType() == REPLICATION_RESPONSE)
-            {
-               replicateResponseReceived();
-            }
-            else
-            {
-               throw new IllegalArgumentException("Invalid packet " + packet);
-            }
          }
       }
    }
@@ -1639,7 +1364,8 @@
          {
             // Error - didn't get pong back
             final MessagingException me = new MessagingException(MessagingException.NOT_CONNECTED,
-                                                                 "Did not receive pong from server");
+                                                                 "Did not receive pong from server, active " + 
+                                                                 createdActive + " client " + client);
 
             fail(me);
          }
@@ -1664,7 +1390,7 @@
          if (type == PONG)
          {
             gotPong = true;
-
+            
             if (stopPinging)
             {
                future.cancel(true);
@@ -1676,7 +1402,7 @@
 
             // Parameter is placeholder for future
             final Packet pong = new Pong(-1);
-
+ 
             pingChannel.send(pong);
          }
          else
@@ -1685,5 +1411,4 @@
          }
       }
    }
-
 }

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingServiceImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingServiceImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingServiceImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -20,8 +20,6 @@
 import java.util.Timer;
 import java.util.TimerTask;
 import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
 
 import org.jboss.messaging.core.config.Configuration;
 import org.jboss.messaging.core.config.TransportConfiguration;
@@ -67,7 +65,7 @@
 
    private final Map<Object, RemotingConnection> connections = new ConcurrentHashMap<Object, RemotingConnection>();
 
-   private final Timer failedConnectionTimer = new Timer(true);
+   private Timer failedConnectionTimer;
 
    private TimerTask failedConnectionsTask;
 
@@ -79,8 +77,6 @@
 
    private volatile MessagingServer server;
    
-   private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);
-
    // Static --------------------------------------------------------
 
    // Constructors --------------------------------------------------
@@ -143,6 +139,8 @@
       {
          a.start();
       }
+      
+      failedConnectionTimer = new Timer(true);
 
       failedConnectionsTask = new FailedConnectionsTask();
 
@@ -158,11 +156,15 @@
          return;
       }
 
-      if (failedConnectionsTask != null)
+      if (failedConnectionTimer != null)
       {
          failedConnectionsTask.cancel();
 
          failedConnectionsTask = null;
+         
+         failedConnectionTimer.cancel();
+         
+         failedConnectionTimer = null;
       }
 
       for (Acceptor acceptor : acceptors)
@@ -172,7 +174,7 @@
 
       started = false;
    }
-
+   
    public boolean isStarted()
    {
       return started;
@@ -215,15 +217,12 @@
       RemotingConnection replicatingConnection = server.getReplicatingConnection();
 
       RemotingConnection rc = new RemotingConnectionImpl(connection,
-                                                         callTimeout,
-                                                         -1,                            
-                                                         null,
+                                                         callTimeout,                                           
                                                          interceptors,
                                                          replicatingConnection,
-                                                         !backup,
-                                                         readWriteLock);
+                                                         !backup);
 
-      Channel channel1 = rc.getChannel(1,  -1, false);
+      Channel channel1 = rc.getChannel(1,  -1);
 
       ChannelHandler handler = new MessagingServerPacketHandler(server, channel1, rc);
 

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/invm/InVMConnection.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/invm/InVMConnection.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/invm/InVMConnection.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -32,7 +32,6 @@
 import org.jboss.messaging.core.remoting.spi.ConnectionLifeCycleListener;
 import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
 import org.jboss.messaging.util.ExecutorFactory;
-import org.jboss.messaging.util.Future;
 import org.jboss.messaging.util.JBMThreadFactory;
 import org.jboss.messaging.util.OrderedExecutorFactory;
 import org.jboss.messaging.util.UUIDGenerator;

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/netty/ChannelBufferWrapper.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/netty/ChannelBufferWrapper.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/netty/ChannelBufferWrapper.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,8 +22,12 @@
 
 package org.jboss.messaging.core.remoting.impl.netty;
 
-import static org.jboss.messaging.util.DataConstants.*;
-import static org.jboss.netty.buffer.ChannelBuffers.*;
+import static org.jboss.messaging.util.DataConstants.FALSE;
+import static org.jboss.messaging.util.DataConstants.NOT_NULL;
+import static org.jboss.messaging.util.DataConstants.NULL;
+import static org.jboss.messaging.util.DataConstants.TRUE;
+import static org.jboss.netty.buffer.ChannelBuffers.copiedBuffer;
+import static org.jboss.netty.buffer.ChannelBuffers.dynamicBuffer;
 
 import java.nio.BufferUnderflowException;
 

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/PacketImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/PacketImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/PacketImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -50,6 +50,7 @@
 
    public static final byte REPLICATION_RESPONSE = 23;
 
+   public static final byte EARLY_RESPONSE = 24;
 
    // Server
    public static final byte CREATESESSION = 30;
@@ -60,6 +61,8 @@
 
    public static final byte REATTACH_SESSION_RESP = 33;
 
+   public static final byte REPLICATE_CREATESESSION = 34;
+
    // Session
    public static final byte SESS_CREATECONSUMER = 40;
 
@@ -69,88 +72,86 @@
 
    public static final byte SESS_CREATEPRODUCER_RESP = 43;
 
-   public static final byte SESS_CREATEQUEUECOPY = 44;
+   public static final byte SESS_ACKNOWLEDGE = 44;
 
-   public static final byte SESS_ACKNOWLEDGE = 46;
+   public static final byte SESS_COMMIT = 45;
 
-   public static final byte SESS_COMMIT = 47;
+   public static final byte SESS_ROLLBACK = 46;
 
-   public static final byte SESS_ROLLBACK = 48;
+   public static final byte SESS_QUEUEQUERY = 47;
 
-   public static final byte SESS_QUEUEQUERY = 49;
+   public static final byte SESS_QUEUEQUERY_RESP = 48;
 
-   public static final byte SESS_QUEUEQUERY_RESP = 50;
+   public static final byte SESS_CREATEQUEUE = 49;
 
-   public static final byte SESS_CREATEQUEUE = 51;
+   public static final byte SESS_DELETE_QUEUE = 50;
 
-   public static final byte SESS_DELETE_QUEUE = 52;
+   public static final byte SESS_ADD_DESTINATION = 51;
 
-   public static final byte SESS_ADD_DESTINATION = 53;
+   public static final byte SESS_REMOVE_DESTINATION = 52;
 
-   public static final byte SESS_REMOVE_DESTINATION = 54;
+   public static final byte SESS_BINDINGQUERY = 53;
 
-   public static final byte SESS_BINDINGQUERY = 55;
+   public static final byte SESS_BINDINGQUERY_RESP = 54;
 
-   public static final byte SESS_BINDINGQUERY_RESP = 56;
+   public static final byte SESS_XA_START = 55;
 
-   public static final byte SESS_XA_START = 62;
+   public static final byte SESS_XA_END = 56;
 
-   public static final byte SESS_XA_END = 63;
+   public static final byte SESS_XA_COMMIT = 57;
 
-   public static final byte SESS_XA_COMMIT = 64;
+   public static final byte SESS_XA_PREPARE = 58;
 
-   public static final byte SESS_XA_PREPARE = 65;
+   public static final byte SESS_XA_RESP = 59;
 
-   public static final byte SESS_XA_RESP = 66;
+   public static final byte SESS_XA_ROLLBACK = 60;
 
-   public static final byte SESS_XA_ROLLBACK = 67;
+   public static final byte SESS_XA_JOIN = 61;
 
-   public static final byte SESS_XA_JOIN = 68;
+   public static final byte SESS_XA_SUSPEND = 62;
 
-   public static final byte SESS_XA_SUSPEND = 69;
+   public static final byte SESS_XA_RESUME = 63;
 
-   public static final byte SESS_XA_RESUME = 70;
+   public static final byte SESS_XA_FORGET = 64;
 
-   public static final byte SESS_XA_FORGET = 71;
+   public static final byte SESS_XA_INDOUBT_XIDS = 65;
 
-   public static final byte SESS_XA_INDOUBT_XIDS = 72;
+   public static final byte SESS_XA_INDOUBT_XIDS_RESP = 66;
 
-   public static final byte SESS_XA_INDOUBT_XIDS_RESP = 73;
+   public static final byte SESS_XA_SET_TIMEOUT = 67;
 
-   public static final byte SESS_XA_SET_TIMEOUT = 74;
+   public static final byte SESS_XA_SET_TIMEOUT_RESP = 68;
 
-   public static final byte SESS_XA_SET_TIMEOUT_RESP = 75;
+   public static final byte SESS_XA_GET_TIMEOUT = 69;
 
-   public static final byte SESS_XA_GET_TIMEOUT = 76;
+   public static final byte SESS_XA_GET_TIMEOUT_RESP = 70;
 
-   public static final byte SESS_XA_GET_TIMEOUT_RESP = 77;
+   public static final byte SESS_START = 71;
 
-   public static final byte SESS_START = 78;
+   public static final byte SESS_STOP = 72;
 
-   public static final byte SESS_STOP = 79;
+   public static final byte SESS_CLOSE = 73;
 
-   public static final byte SESS_CLOSE = 80;
+   public static final byte SESS_FLOWTOKEN = 74;
 
-   public static final byte SESS_FLOWTOKEN = 81;
+   public static final byte SESS_SEND = 75;
 
-   public static final byte SESS_SEND = 82;
+   public static final byte SESS_RECEIVETOKENS = 76;
 
-   public static final byte SESS_RECEIVETOKENS = 83;
+   public static final byte SESS_CONSUMER_CLOSE = 77;
 
-   public static final byte SESS_CONSUMER_CLOSE = 84;
+   public static final byte SESS_PRODUCER_CLOSE = 78;
 
-   public static final byte SESS_PRODUCER_CLOSE = 85;
+   public static final byte SESS_RECEIVE_MSG = 79;
 
-   public static final byte SESS_RECEIVE_MSG = 87;
+   public static final byte SESS_MANAGEMENT_SEND = 80;
 
-   public static final byte SESS_MANAGEMENT_SEND = 88;
+   public static final byte SESS_SCHEDULED_SEND = 81;
 
-   public static final byte SESS_SCHEDULED_SEND = 89;
+   public static final byte SESS_FAILOVER_COMPLETE = 82;
 
-   public static final byte SESS_FAILOVER_COMPLETE = 90;
+   public static final byte SESS_REPLICATE_DELIVERY = 83;
 
-   public static final byte SESS_REPLICATE_DELIVERY = 91;
-
    // Static --------------------------------------------------------
 
    public PacketImpl(final byte type)
@@ -195,7 +196,7 @@
    public void decode(final MessagingBuffer buffer)
    {
       channelID = buffer.getLong();
-      
+
       decodeBody(buffer);
    }
 
@@ -222,11 +223,6 @@
       return false;
    }
 
-   public boolean isRequiresGlobalOrdering()
-   {
-      return false;
-   }
-
    @Override
    public String toString()
    {
@@ -258,5 +254,4 @@
    // Private -------------------------------------------------------
 
    // Inner classes -------------------------------------------------
-
 }

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionCreateQueueMessage.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionCreateQueueMessage.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionCreateQueueMessage.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -103,11 +103,6 @@
       return temporary;
    }
    
-   public boolean isRequiresGlobalOrdering()
-   {
-      return true;
-   }
-   
    public void encodeBody(final MessagingBuffer buffer)
    {
       buffer.putSimpleString(address);

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionDeleteQueueMessage.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionDeleteQueueMessage.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionDeleteQueueMessage.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -70,11 +70,6 @@
       return queueName;
    }
       
-   public boolean isRequiresGlobalOrdering()
-   {
-      return true;
-   }
-   
    public void encodeBody(final MessagingBuffer buffer)
    {
       buffer.putSimpleString(queueName);

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/XidCodecSupport.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/XidCodecSupport.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/XidCodecSupport.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,12 +22,12 @@
 
 package org.jboss.messaging.core.remoting.impl.wireformat;
 
+import javax.transaction.xa.Xid;
+
 import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
 import org.jboss.messaging.core.transaction.impl.XidImpl;
 import org.jboss.messaging.util.DataConstants;
 
-import javax.transaction.xa.Xid;
-
 /**
  * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
  *

Modified: trunk/src/main/org/jboss/messaging/core/server/MessagingServer.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/MessagingServer.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/server/MessagingServer.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -73,6 +73,16 @@
                                               boolean autoCommitAcks,
                                               boolean xa) throws Exception;
 
+   CreateSessionResponseMessage replicateCreateSession(String name,
+                                                       long channelID,
+                                                       String username,
+                                                       String password,
+                                                       int incrementingVersion,
+                                                       RemotingConnection remotingConnection,
+                                                       boolean autoCommitSends,
+                                                       boolean autoCommitAcks,
+                                                       boolean xa) throws Exception;
+
    void removeSession(String name) throws Exception;
 
    boolean isStarted();

Modified: trunk/src/main/org/jboss/messaging/core/server/Queue.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/Queue.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/server/Queue.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -145,4 +145,6 @@
    
    //Only used in testing
    void deliverNow();
+   
+  // void dumpRefs();
 }

Modified: trunk/src/main/org/jboss/messaging/core/server/ServerConsumer.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/ServerConsumer.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/server/ServerConsumer.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,7 +22,6 @@
 
 package org.jboss.messaging.core.server;
 
-
 import java.util.List;
 
 import org.jboss.messaging.core.remoting.Packet;

Modified: trunk/src/main/org/jboss/messaging/core/server/ServerSession.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/ServerSession.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/server/ServerSession.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,6 +22,7 @@
 
 package org.jboss.messaging.core.server;
 
+import org.jboss.messaging.core.remoting.Channel;
 import org.jboss.messaging.core.remoting.DelayedResult;
 import org.jboss.messaging.core.remoting.Packet;
 import org.jboss.messaging.core.remoting.RemotingConnection;
@@ -148,7 +149,9 @@
    void handleReplicatedDelivery(SessionReplicateDeliveryMessage packet);
    
    int transferConnection(RemotingConnection newConnection, int lastReceivedCommandID);
-
+   
+   Channel getChannel();
+   
    //Should this really be here??
    void sendResponse(final DelayedResult result, final Packet response);
 

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/GroupingRoundRobinDistributionPolicy.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/GroupingRoundRobinDistributionPolicy.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/GroupingRoundRobinDistributionPolicy.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,18 +21,14 @@
  */
 package org.jboss.messaging.core.server.impl;
 
+import java.util.concurrent.ConcurrentHashMap;
+
 import org.jboss.messaging.core.message.impl.MessageImpl;
 import org.jboss.messaging.core.server.Consumer;
-import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.core.server.HandleStatus;
 import org.jboss.messaging.core.server.MessageReference;
 import org.jboss.messaging.util.SimpleString;
 
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
 /**
  * Distributes message based on the message property 'JMSXGroupID'. Once a message has been successfully delivered to a
  * consumer that consumer is then bound to that group. Any message that has the same group id set will always be

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServerImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServerImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -16,7 +16,6 @@
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
@@ -38,9 +37,10 @@
 import org.jboss.messaging.core.postoffice.impl.PostOfficeImpl;
 import org.jboss.messaging.core.remoting.Channel;
 import org.jboss.messaging.core.remoting.ChannelHandler;
+import org.jboss.messaging.core.remoting.ConnectionManager;
 import org.jboss.messaging.core.remoting.RemotingConnection;
 import org.jboss.messaging.core.remoting.RemotingService;
-import org.jboss.messaging.core.remoting.impl.ConnectionRegistryImpl;
+import org.jboss.messaging.core.remoting.impl.ConnectionManagerImpl;
 import org.jboss.messaging.core.remoting.impl.wireformat.CreateSessionResponseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.ReattachSessionResponseMessage;
 import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
@@ -113,12 +113,8 @@
 
    private MessagingServerControlMBean serverManagement;
 
-   private final ConcurrentMap<String, ServerSession> sessions = new ConcurrentHashMap<String, ServerSession>();
+   private final Map<String, ServerSession> sessions = new ConcurrentHashMap<String, ServerSession>();
 
-   private ConnectorFactory backupConnectorFactory;
-
-   private Map<String, Object> backupConnectorParams;
-   
    // plugins
 
    private StorageManager storageManager;
@@ -133,6 +129,8 @@
 
    private final SimpleStringIdGenerator simpleStringIdGenerator = new GroupIdGenerator(new SimpleString("AutoGroupId-"));
 
+   private ConnectionManager replicatingConnectionManager;
+
    // Constructors
    // ---------------------------------------------------------------------------------
 
@@ -242,6 +240,7 @@
 
       if (backupConnector != null)
       {
+         ConnectorFactory backupConnectorFactory;
          ClassLoader loader = Thread.currentThread().getContextClassLoader();
          try
          {
@@ -254,7 +253,15 @@
                                                         "\"",
                                                e);
          }
-         backupConnectorParams = backupConnector.getParams();
+         Map<String, Object> backupConnectorParams = backupConnector.getParams();
+
+         // TODO don't hardcode ping interval and code timeout
+         replicatingConnectionManager = new ConnectionManagerImpl(backupConnectorFactory,
+                                                                  backupConnectorParams,
+                                                                  5000,
+                                                                  30000,
+                                                                  1,
+                                                                  5);
       }
       remotingService.setMessagingServer(this);
 
@@ -395,23 +402,57 @@
       return started;
    }
 
+   private synchronized void checkActivate(final RemotingConnection connection)
+   {
+      if (configuration.isBackup())
+      {
+         freezeAllBackupConnections();
+         
+         postOffice.activate();
+
+         configuration.setBackup(false);
+
+         remotingService.setBackup(false);                  
+      }
+
+      connection.activate();
+   }
+   
+   //We need to prevent any more packets being handled on any connections (from live) as soon as first live connection
+   //is created or re-attaches, to prevent a situation like the following:
+   //connection 1 create queue A
+   //connection 2 fails over
+   //A gets activated since no consumers
+   //connection 1 create consumer on A
+   //connection 1 delivery
+   //connection 1 delivery gets replicated
+   //can't find message in queue since active was delivered immediately   
+   private void freezeAllBackupConnections()
+   {
+      Set<RemotingConnection> connections = new HashSet<RemotingConnection>();
+      
+      for (ServerSession session: sessions.values())
+      {
+         connections.add(session.getChannel().getConnection());
+      }
+      
+      for (RemotingConnection connection: connections)
+      {
+         connection.freeze();
+      }
+   }
+   
    public ReattachSessionResponseMessage reattachSession(final RemotingConnection connection,
-                                                         final String name,
-                                                         final int lastReceivedCommandID) throws Exception
+                                                                      final String name,
+                                                                      final int lastReceivedCommandID) throws Exception
    {
       ServerSession session = sessions.get(name);
 
       // Need to activate the connection even if session can't be found - since otherwise response
       // will never get back
 
-      connection.activate();
+      checkActivate(connection);
 
-      postOffice.activate();
-
-      configuration.setBackup(false);
-
-      remotingService.setBackup(false);
-
       if (session == null)
       {
          return new ReattachSessionResponseMessage(-1, true);
@@ -420,78 +461,58 @@
       {
          // Reconnect the channel to the new connection
          int serverLastReceivedCommandID = session.transferConnection(connection, lastReceivedCommandID);
-                         
+
          return new ReattachSessionResponseMessage(serverLastReceivedCommandID, false);
       }
    }
-   
+
+   public CreateSessionResponseMessage replicateCreateSession(final String name,
+                                                                           final long channelID,
+                                                                           final String username,
+                                                                           final String password,
+                                                                           final int incrementingVersion,
+                                                                           final RemotingConnection connection,
+                                                                           final boolean autoCommitSends,
+                                                                           final boolean autoCommitAcks,
+                                                                           final boolean xa) throws Exception
+   {
+      return doCreateSession(name,
+                             channelID,
+                             username,
+                             password,
+                             incrementingVersion,
+                             connection,
+                             autoCommitSends,
+                             autoCommitAcks,
+                             xa);
+   }
+
    public CreateSessionResponseMessage createSession(final String name,
-                                                     final long channelID,
-                                                     final String username,
-                                                     final String password,
-                                                     final int incrementingVersion,
-                                                     final RemotingConnection connection,
-                                                     final boolean autoCommitSends,
-                                                     final boolean autoCommitAcks,
-                                                     final boolean xa) throws Exception
+                                                                  final long channelID,
+                                                                  final String username,
+                                                                  final String password,
+                                                                  final int incrementingVersion,
+                                                                  final RemotingConnection connection,
+                                                                  final boolean autoCommitSends,
+                                                                  final boolean autoCommitAcks,
+                                                                  final boolean xa) throws Exception
    {
-      if (version.getIncrementingVersion() < incrementingVersion)
-      {
-         throw new MessagingException(MessagingException.INCOMPATIBLE_CLIENT_SERVER_VERSIONS,
-                                      "client not compatible with version: " + version.getFullVersion());
-      }
+//      if (configuration.isBackup())
+//      {
+//         throw new IllegalStateException("Cannot create a session on a backup server");
+//      }
 
-      // Is this comment relevant any more ?
+      checkActivate(connection);
 
-      // Authenticate. Successful autentication will place a new SubjectContext
-      // on thread local,
-      // which will be used in the authorization process. However, we need to
-      // make sure we clean
-      // up thread local immediately after we used the information, otherwise
-      // some other people
-      // security my be screwed up, on account of thread local security stack
-      // being corrupted.
-
-      securityStore.authenticate(username, password);
- 
-      Channel channel = connection.getChannel(channelID,                                             
-                                              configuration.getPacketConfirmationBatchSize(),                                             
-                                              false);
-
-      final ServerSessionImpl session = new ServerSessionImpl(name,
-                                                              channelID,
-                                                              username,
-                                                              password,
-                                                              autoCommitSends,
-                                                              autoCommitAcks,
-                                                              xa,
-                                                              connection,
-                                                              storageManager,
-                                                              postOffice,
-                                                              queueSettingsRepository,
-                                                              resourceManager,
-                                                              securityStore,
-                                                              executorFactory.getExecutor(),
-                                                              channel,
-                                                              managementService,
-                                                              this,
-                                                              simpleStringIdGenerator);
-
-      // If the session already exists that's fine - create session must be idempotent
-      // This is because if server failures occurring during a create session call we need to
-      // retry it on the backup, but the create session might have and might not have been replicated
-      // to the backup, so we need to work in both cases
-      if (sessions.putIfAbsent(name, session) == null)
-      {
-         ChannelHandler handler = new ServerSessionPacketHandler(session, channel);
-
-         channel.setHandler(handler);
-
-         connection.addFailureListener(session);
-      }
-
-      return new CreateSessionResponseMessage(version.getIncrementingVersion(),
-                                              configuration.getPacketConfirmationBatchSize());
+      return doCreateSession(name,
+                             channelID,
+                             username,
+                             password,
+                             incrementingVersion,
+                             connection,
+                             autoCommitSends,
+                             autoCommitAcks,
+                             xa);
    }
 
    public void removeSession(final String name) throws Exception
@@ -507,13 +528,10 @@
       // need to preserve channel ids
       // before and after failover
 
-      if (backupConnectorFactory != null)
+      if (this.replicatingConnectionManager != null)
       {
-         // TODO don't hardcode ping interval and code timeout
-         RemotingConnection replicatingConnection = ConnectionRegistryImpl.instance.getConnectionNoCache(backupConnectorFactory,
-                                                                                                         backupConnectorParams,
-                                                                                                         -1,
-                                                                                                         2000);
+         RemotingConnection replicatingConnection = replicatingConnectionManager.createConnection();
+
          return replicatingConnection;
       }
       else
@@ -521,7 +539,7 @@
          return null;
       }
    }
-   
+
    public MessagingServerControlMBean getServerManagement()
    {
       return serverManagement;
@@ -549,6 +567,79 @@
    // Private
    // --------------------------------------------------------------------------------------
 
+   private final Object createSessionLock = new Object();
+   
+   private CreateSessionResponseMessage doCreateSession(final String name,
+                                                        final long channelID,
+                                                        final String username,
+                                                        final String password,
+                                                        final int incrementingVersion,
+                                                        final RemotingConnection connection,
+                                                        final boolean autoCommitSends,
+                                                        final boolean autoCommitAcks,
+                                                        final boolean xa) throws Exception
+   {
+      if (version.getIncrementingVersion() < incrementingVersion)
+      {
+         throw new MessagingException(MessagingException.INCOMPATIBLE_CLIENT_SERVER_VERSIONS,
+                                      "client not compatible with version: " + version.getFullVersion());
+      }
+
+      // Is this comment relevant any more ?
+
+      // Authenticate. Successful autentication will place a new SubjectContext
+      // on thread local,
+      // which will be used in the authorization process. However, we need to
+      // make sure we clean
+      // up thread local immediately after we used the information, otherwise
+      // some other people
+      // security my be screwed up, on account of thread local security stack
+      // being corrupted.
+
+      securityStore.authenticate(username, password);
+
+      ServerSession currentSession = sessions.remove(name);
+
+      if (currentSession != null)
+      {
+         // This session may well be on a different connection and different channel id, so we must get rid
+         // of it and create another
+         currentSession.getChannel().close();
+      }
+
+      Channel channel = connection.getChannel(channelID, configuration.getPacketConfirmationBatchSize());
+
+      final ServerSessionImpl session = new ServerSessionImpl(name,
+                                                              channelID,
+                                                              username,
+                                                              password,
+                                                              autoCommitSends,
+                                                              autoCommitAcks,
+                                                              xa,
+                                                              connection,
+                                                              storageManager,
+                                                              postOffice,
+                                                              queueSettingsRepository,
+                                                              resourceManager,
+                                                              securityStore,
+                                                              executorFactory.getExecutor(),
+                                                              channel,
+                                                              managementService,
+                                                              this,
+                                                              simpleStringIdGenerator);
+
+      sessions.put(name, session);
+
+      ChannelHandler handler = new ServerSessionPacketHandler(session, channel);
+
+      channel.setHandler(handler);
+
+      connection.addFailureListener(session);
+
+      return new CreateSessionResponseMessage(version.getIncrementingVersion(),
+                                              configuration.getPacketConfirmationBatchSize());
+   }
+
    // Inner classes
    // --------------------------------------------------------------------------------
 }

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServerPacketHandler.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServerPacketHandler.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServerPacketHandler.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -14,6 +14,7 @@
 
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.CREATESESSION;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.REATTACH_SESSION;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.REPLICATE_CREATESESSION;
 
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
@@ -24,7 +25,9 @@
 import org.jboss.messaging.core.remoting.RemotingConnection;
 import org.jboss.messaging.core.remoting.impl.wireformat.CreateSessionMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.MessagingExceptionMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl;
 import org.jboss.messaging.core.remoting.impl.wireformat.ReattachSessionMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.ReplicateCreateSessionMessage;
 import org.jboss.messaging.core.server.MessagingServer;
 
 /**
@@ -56,23 +59,36 @@
    }
 
    public void handlePacket(final Packet packet)
-   {  
-      DelayedResult result = channel1.replicatePacket(packet);
+   {
+      DelayedResult result = null;
       
+      if (packet.getType() == PacketImpl.CREATESESSION && channel1.getReplicatingChannel() != null)
+      {
+         CreateSessionMessage msg = (CreateSessionMessage)packet;
+
+         Packet replPacket = new ReplicateCreateSessionMessage(msg.getName(), msg.getSessionChannelID(),
+                                                               msg.getVersion(), msg.getUsername(),
+                                                               msg.getPassword(), msg.isXA(),
+                                                               msg.isAutoCommitSends(),
+                                                               msg.isAutoCommitAcks());
+         
+         result = channel1.replicatePacket(replPacket);
+      }
+            
       Packet response = null;
-      
+
       byte type = packet.getType();
 
       // All these operations need to be idempotent since they are outside of the session
       // reliability replay functionality
       try
-      {                
+      {
          switch (type)
          {
             case CREATESESSION:
             {
                CreateSessionMessage request = (CreateSessionMessage)packet;
-   
+
                response = server.createSession(request.getName(),
                                                request.getSessionChannelID(),
                                                request.getUsername(),
@@ -84,12 +100,27 @@
                                                request.isXA());
                break;
             }
+            case REPLICATE_CREATESESSION:
+            {
+               ReplicateCreateSessionMessage request = (ReplicateCreateSessionMessage)packet;
+
+               response = server.replicateCreateSession(request.getName(),
+                                                        request.getSessionChannelID(),
+                                                        request.getUsername(),
+                                                        request.getPassword(),
+                                                        request.getVersion(),
+                                                        connection,
+                                                        request.isAutoCommitSends(),
+                                                        request.isAutoCommitAcks(),
+                                                        request.isXA());
+               break;
+            }
             case REATTACH_SESSION:
             {
                ReattachSessionMessage request = (ReattachSessionMessage)packet;
-   
+
                response = server.reattachSession(connection, request.getName(), request.getLastReceivedCommandID());
-               
+
                break;
             }
             default:
@@ -116,7 +147,7 @@
 
          response = new MessagingExceptionMessage(me);
       }
-      
+
       if (response != null)
       {
          if (result == null)
@@ -126,7 +157,7 @@
          else
          {
             final Packet theResponse = response;
-            
+
             result.setResultRunner(new Runnable()
             {
                public void run()
@@ -136,7 +167,7 @@
             });
          }
       }
-      
+
       channel1.replicateComplete();
    }
 }
\ No newline at end of file

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServiceImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServiceImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServiceImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,6 +21,8 @@
   */
 package org.jboss.messaging.core.server.impl;
 
+import java.lang.management.ManagementFactory;
+
 import org.jboss.messaging.core.config.Configuration;
 import org.jboss.messaging.core.config.impl.ConfigurationImpl;
 import org.jboss.messaging.core.journal.Journal;
@@ -38,8 +40,6 @@
 import org.jboss.messaging.core.server.MessagingServer;
 import org.jboss.messaging.core.server.MessagingService;
 
-import java.lang.management.ManagementFactory;
-
 /**
  * 
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -35,8 +35,8 @@
 import org.jboss.messaging.core.server.HandleStatus;
 import org.jboss.messaging.core.server.MessageReference;
 import org.jboss.messaging.core.server.Queue;
-import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.core.server.ScheduledDeliveryHandler;
+import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.core.settings.HierarchicalRepository;
 import org.jboss.messaging.core.settings.impl.QueueSettings;
 import org.jboss.messaging.core.transaction.Transaction;
@@ -151,7 +151,7 @@
    }
 
    public HandleStatus addLast(final MessageReference ref)
-   {
+   {      
       HandleStatus status = add(ref, false);
 
       return status;
@@ -196,7 +196,6 @@
    {
       deliver();
    }
-
    
    public void addConsumer(final Consumer consumer)
    {
@@ -211,7 +210,7 @@
       {
          promptDelivery = false;
       }
-
+      
       return removed;
    }
 
@@ -298,7 +297,7 @@
    }
 
    public synchronized int getMessageCount()
-   {
+   {    
       return messageReferences.size() + getScheduledCount() + getDeliveringCount();
    }
 
@@ -322,11 +321,6 @@
       deliveringCount.decrementAndGet();
 
       sizeBytes.addAndGet(-ref.getMessage().getEncodeSize());
-
-      // if (flowController != null)
-      // {
-      // flowController.messageAcknowledged();
-      // }
    }
 
    public void referenceCancelled()
@@ -510,7 +504,7 @@
    }
 
    public synchronized void setBackup()
-   {
+   {    
       this.backup = true;
 
       this.direct = false;
@@ -522,9 +516,9 @@
    }
 
    public synchronized void activate()
-   {
+   {      
       consumersToFailover = distributionPolicy.getConsumerCount();
-
+      
       if (consumersToFailover == 0)
       {
          backup = false;
@@ -534,13 +528,13 @@
    public synchronized boolean consumerFailedOver()
    {
       consumersToFailover--;
-
+      
       if (consumersToFailover == 0)
       {
          // All consumers for the queue have failed over, can re-activate it now
 
          backup = false;
-
+         
          scheduledDeliveryHandler.reSchedule();
 
          return true;
@@ -588,7 +582,7 @@
       {
          return;
       }
-
+      
       MessageReference reference;
 
       Iterator<MessageReference> iterator = null;
@@ -750,8 +744,8 @@
          waitingToDeliver.set(false);
 
          synchronized (QueueImpl.this)
-         {
-            deliver();
+         {          
+            deliver();            
          }
       }
    }

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/ScheduledDeliveryHandlerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/ScheduledDeliveryHandlerImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/ScheduledDeliveryHandlerImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,18 +21,18 @@
  */
 package org.jboss.messaging.core.server.impl;
 
+import java.util.ArrayList;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
+
+import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.server.MessageReference;
 import org.jboss.messaging.core.server.ScheduledDeliveryHandler;
-import org.jboss.messaging.core.logging.Logger;
 
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.Set;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.ArrayList;
-
 /**
  * Handles scheduling deliveries to a queue at the correct time.
  * 

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/ServerConsumerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/ServerConsumerImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/ServerConsumerImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -157,108 +157,54 @@
    {
       return id;
    }
-
+   
    public HandleStatus handle(final MessageReference ref) throws Exception
    {
-      if (availableCredits != null && availableCredits.get() <= 0)
+      return doHandle(ref);
+   }
+         
+   public void handleClose(final Packet packet)
+   {
+      //We must stop delivery before replicating the packet, this ensures the close message gets processed
+      //and replicated on the backup in the same order as any delivery that might be occuring gets
+      //processed and replicated on the backup.
+      //Otherwise we could end up with a situation where a close comes in, then a delivery comes in,
+      //then close gets replicated to backup, then delivery gets replicated, but consumer is already
+      //closed!
+      lock.lock();
+      try
       {
-         return HandleStatus.BUSY;
+         setStarted(false);
       }
-
-      final ServerMessage message = ref.getMessage();
-
-      if (message.isExpired())
+      finally
       {
-         // TODO need to replicate expires
-         ref.expire(storageManager, postOffice, queueSettingsRepository);
-
-         return HandleStatus.HANDLED;
+         lock.unlock();
       }
-   
-      lock.lock();
       
-      try
+      DelayedResult result = channel.replicatePacket(packet);
+      
+      if (result != null)
       {
-      
-         // If the consumer is stopped then we don't accept the message, it
-         // should go back into the
-         // queue for delivery later.
-         if (!started)
+         result.setResultRunner(new Runnable()
          {
-            return HandleStatus.BUSY;
-         }
-
-         if (filter != null && !filter.match(message))
-         {
-            return HandleStatus.NO_MATCH;
-         }
-
-         if (availableCredits != null)
-         {
-            availableCredits.addAndGet(-message.getEncodeSize());
-         }
-
-         final SessionReceiveMessage packet = new SessionReceiveMessage(id, message, ref.getDeliveryCount() + 1);
-
-         DelayedResult result = channel.replicatePacket(new SessionReplicateDeliveryMessage(id, message.getMessageID()));
-
-         if (!browseOnly)
-         {
-            deliveringRefs.add(ref);
-         }
-
-         if (result == null)
-         {
-            // Not replicated - just send now
-            channel.send(packet);
-         }
-         else
-         {
-            // Send when replicate delivery response comes back
-            result.setResultRunner(new Runnable()
+            public void run()
             {
-               public void run()
-               {
-                  channel.send(packet);
-               }
-            });
-         }
-
-         return HandleStatus.HANDLED;
+               doHandleClose(packet);
+            }
+         });
       }
-      finally
+      else
       {
-         lock.unlock();
+         doHandleClose(packet);
       }
    }
    
-   public void handleClose(final Packet packet)
+   private void doHandleClose(final Packet packet)
    {
-      DelayedResult result = null;
-
       Packet response = null;
-                  
+      
       try
-      {               
-         lock.lock();
-         try
-         {
-            setStarted(false);
-         }
-         finally
-         {
-            lock.unlock();
-         }
-         
-         //We must stop delivery before replicating the packet, this ensures the close message gets processed
-         //and replicated on the backup in the same order as any delivery that might be occuring gets
-         //processed and replicated on the backup.
-         //Otherwise we could end up with a situation where a close comes in, then a delivery comes in,
-         //then close gets replicated to backup, then delivery gets replicated, but consumer is already
-         //closed!
-         
-         result = channel.replicatePacket(packet);
-         
+      {                                                                   
          doClose();
          
          response = new NullResponseMessage();
@@ -277,7 +223,7 @@
          }
       }
    
-      session.sendResponse(result, response);
+      channel.send(response);
    }
      
    public void close() throws Exception
@@ -292,9 +238,35 @@
          lock.unlock();
       }
 
-      doClose();
+      doClose();     
    }
+   
+   private void doClose() throws Exception
+   {
+      messageQueue.removeConsumer(this);
 
+      session.removeConsumer(this);
+
+      LinkedList<MessageReference> refs = cancelRefs();
+
+      Iterator<MessageReference> iter = refs.iterator();
+
+      while (iter.hasNext())
+      {
+         MessageReference ref = iter.next();
+
+         if (!ref.cancel(storageManager, postOffice, queueSettingsRepository))
+         {
+            iter.remove();
+         }
+      }
+
+      if (!refs.isEmpty())
+      {
+         messageQueue.addListFirst(refs);
+      }
+   }
+
    public LinkedList<MessageReference> cancelRefs() throws Exception
    {
       LinkedList<MessageReference> refs = new LinkedList<MessageReference>();
@@ -373,14 +345,17 @@
       // It may not be the first in the queue - since there may be multiple producers
       // sending to the queue
       MessageReference ref = messageQueue.removeReferenceWithID(messageID);
-      
+
       if (ref == null)
       {
-         log.error("Queue has size " + messageQueue.getMessageCount());
          throw new IllegalStateException("Cannot find ref when replicating delivery " + messageID);
       }
                   
-      HandleStatus handled = this.handle(ref);
+      //We call doHandle rather than handle, since we don't want to check available credits
+      //This is because delivery and receive credits can be processed in different order on live
+      //and backup, and otherwise we could have a situation where the delivery is replicated
+      //but the credits haven't arrived yet, so the delivery gets rejected on backup
+      HandleStatus handled = doHandle(ref);
 
       if (handled != HandleStatus.HANDLED)
       {
@@ -415,36 +390,84 @@
    // Private
    // --------------------------------------------------------------------------------------
 
-   private void doClose() throws Exception
+   private void promptDelivery()
    {
-      messageQueue.removeConsumer(this);
+      session.promptDelivery(messageQueue);
+   }
+   
+   private HandleStatus doHandle(final MessageReference ref) throws Exception
+   {
+      if (availableCredits != null && availableCredits.get() <= 0)
+      {
+         return HandleStatus.BUSY;
+      }
 
-      session.removeConsumer(this);
+      final ServerMessage message = ref.getMessage();
 
-      LinkedList<MessageReference> refs = cancelRefs();
+      if (message.isExpired())
+      {
+         // TODO need to replicate expires
+         ref.expire(storageManager, postOffice, queueSettingsRepository);
 
-      Iterator<MessageReference> iter = refs.iterator();
+         return HandleStatus.HANDLED;
+      }
+   
+      lock.lock();
+      
+      try
+      {      
+         // If the consumer is stopped then we don't accept the message, it
+         // should go back into the
+         // queue for delivery later.
+         if (!started)
+         {
+            return HandleStatus.BUSY;
+         }
 
-      while (iter.hasNext())
-      {
-         MessageReference ref = iter.next();
+         if (filter != null && !filter.match(message))
+         {
+            return HandleStatus.NO_MATCH;
+         }
 
-         if (!ref.cancel(storageManager, postOffice, queueSettingsRepository))
+         if (availableCredits != null)
          {
-            iter.remove();
+            availableCredits.addAndGet(-message.getEncodeSize());
          }
+
+         final SessionReceiveMessage packet = new SessionReceiveMessage(id, message, ref.getDeliveryCount() + 1);
+
+         DelayedResult result =
+            channel.replicatePacket(new SessionReplicateDeliveryMessage(id, message.getMessageID()));
+
+         if (!browseOnly)
+         {
+            deliveringRefs.add(ref);
+         }
+
+         if (result == null)
+         {
+            // Not replicated - just send now
+            channel.send(packet);
+         }
+         else
+         {
+            // Send when replicate delivery response comes back
+            result.setResultRunner(new Runnable()
+            {
+               public void run()
+               {
+                  channel.send(packet);
+               }
+            });
+         }
+
+         return HandleStatus.HANDLED;
       }
-
-      if (!refs.isEmpty())
+      finally
       {
-         messageQueue.addListFirst(refs);
+         lock.unlock();
       }
    }
-   
-   private void promptDelivery()
-   {
-      session.promptDelivery(messageQueue);
-   }
 
    // Inner classes
    // ------------------------------------------------------------------------

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/ServerProducerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/ServerProducerImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/ServerProducerImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -27,8 +27,6 @@
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.postoffice.FlowController;
 import org.jboss.messaging.core.remoting.Channel;
-import org.jboss.messaging.core.remoting.Packet;
-import org.jboss.messaging.core.remoting.impl.wireformat.SessionProducerFlowCreditMessage;
 import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.core.server.ServerProducer;
 import org.jboss.messaging.core.server.ServerSession;

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -86,6 +86,7 @@
 import org.jboss.messaging.core.server.MessageReference;
 import org.jboss.messaging.core.server.MessagingServer;
 import org.jboss.messaging.core.server.Queue;
+import org.jboss.messaging.core.server.SendLock;
 import org.jboss.messaging.core.server.ServerConsumer;
 import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.core.server.ServerProducer;
@@ -305,7 +306,7 @@
          if (!pager.page(msg))
          {
             List<MessageReference> refs = postOffice.route(msg);
-
+            
             if (msg.getDurableRefCount() != 0)
             {
                storageManager.storeMessage(msg);
@@ -356,8 +357,8 @@
          tx.addScheduledMessage(msg, scheduledDeliveryTime);
       }
    }
-
-   public void handleCreateConsumer(final SessionCreateConsumerMessage packet)
+   
+   public void doHandleCreateConsumer(final SessionCreateConsumerMessage packet)
    {
       SimpleString queueName = packet.getQueueName();
 
@@ -369,8 +370,6 @@
 
       boolean browseOnly = packet.isBrowseOnly();
 
-      DelayedResult result = channel.replicatePacket(packet);
-
       Packet response = null;
 
       try
@@ -456,23 +455,42 @@
          }
       }
 
-      sendResponse(result, response);
+      channel.send(response);
    }
 
-   public void handleCreateQueue(final SessionCreateQueueMessage packet)
+   public void handleCreateConsumer(final SessionCreateConsumerMessage packet)
    {
+      DelayedResult result = channel.replicatePacket(packet);
+      
+      if (result == null)
+      {
+         doHandleCreateConsumer(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleCreateConsumer(packet);
+            }
+         });
+      }
+   }
+
+   public void doHandleCreateQueue(final SessionCreateQueueMessage packet)
+   {
       SimpleString address = packet.getAddress();
 
       SimpleString queueName = packet.getQueueName();
-
+      
       SimpleString filterString = packet.getFilterString();
 
       boolean temporary = packet.isTemporary();
 
       boolean durable = packet.isDurable();
 
-      DelayedResult result = channel.replicatePacket(packet);
-
       Packet response = null;
 
       try
@@ -540,16 +558,87 @@
             response = new MessagingExceptionMessage(new MessagingException(MessagingException.INTERNAL_ERROR));
          }
       }
+      
+      channel.send(response);
+   }
+      
 
-      sendResponse(result, response);
+   public void handleCreateQueue(final SessionCreateQueueMessage packet)
+   {
+      final SendLock lock;
+      if (channel.getReplicatingChannel() != null)
+      {
+         lock = postOffice.getAddressLock(packet.getAddress());
+         
+         lock.lock();
+      }
+      else
+      {
+         lock = null;
+      }
+      
+      DelayedResult result = channel.replicatePacket(packet);
+                 
+      if (result == null)
+      {
+         doHandleCreateQueue(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleCreateQueue(packet);        
+               
+               lock.unlock();               
+            }
+         });
+      }
    }
-
+   
    public void handleDeleteQueue(final SessionDeleteQueueMessage packet)
    {
+      final SendLock lock;
+      if (channel.getReplicatingChannel() != null)
+      {
+         Binding binding = postOffice.getBinding(packet.getQueueName());
+         lock = postOffice.getAddressLock(binding.getAddress());
+         
+         lock.lock();
+      }
+      else
+      {
+         lock = null;
+      }
+      
+      DelayedResult result = channel.replicatePacket(packet);
+            
+      
+      if (result == null)
+      {
+         doHandleDeleteQueue(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleDeleteQueue(packet);     
+               
+               lock.unlock();
+            }
+         });
+      }   
+   }
+   
+   public void doHandleDeleteQueue(final SessionDeleteQueueMessage packet)
+   {
       SimpleString queueName = packet.getQueueName();
 
-      DelayedResult result = channel.replicatePacket(packet);
-
       Packet response = null;
 
       try
@@ -588,16 +677,35 @@
             response = new MessagingExceptionMessage(new MessagingException(MessagingException.INTERNAL_ERROR));
          }
       }
-
-      sendResponse(result, response);
+      
+      channel.send(response);
    }
-
+      
    public void handleExecuteQueueQuery(final SessionQueueQueryMessage packet)
    {
+      DelayedResult result = channel.replicatePacket(packet);
+      
+      if (result == null)
+      {
+         doHandleExecuteQueueQuery(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleExecuteQueueQuery(packet);
+            }
+         });
+      }   
+   }
+
+   public void doHandleExecuteQueueQuery(final SessionQueueQueryMessage packet)
+   {
       SimpleString queueName = packet.getQueueName();
 
-      DelayedResult result = channel.replicatePacket(packet);
-
       Packet response = null;
 
       try
@@ -642,15 +750,34 @@
          }
       }
 
-      sendResponse(result, response);
+      channel.send(response);
    }
-
+   
    public void handleExecuteBindingQuery(final SessionBindingQueryMessage packet)
    {
+      DelayedResult result = channel.replicatePacket(packet);
+      
+      if (result == null)
+      {
+         doHandleExecuteBindingQuery(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleExecuteBindingQuery(packet);
+            }
+         });
+      } 
+   }
+
+   public void doHandleExecuteBindingQuery(final SessionBindingQueryMessage packet)
+   {
       SimpleString address = packet.getAddress();
 
-      DelayedResult result = channel.replicatePacket(packet);
-
       Packet response = null;
 
       try
@@ -689,8 +816,8 @@
             response = new MessagingExceptionMessage(new MessagingException(MessagingException.INTERNAL_ERROR));
          }
       }
-
-      sendResponse(result, response);
+      
+      channel.send(response);
    }
 
    /**
@@ -703,6 +830,27 @@
     */
    public void handleCreateProducer(final SessionCreateProducerMessage packet)
    {
+      DelayedResult result = channel.replicatePacket(packet);
+      
+      if (result == null)
+      {
+         doHandleCreateProducer(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleCreateProducer(packet);
+            }
+         });
+      }
+   }
+   
+   public void doHandleCreateProducer(final SessionCreateProducerMessage packet)
+   {
       SimpleString address = packet.getAddress();
 
       int maxRate = packet.getMaxRate();
@@ -711,8 +859,6 @@
 
       boolean autoGroupID = packet.isAutoGroupId();
 
-      DelayedResult result = channel.replicatePacket(packet);
-
       Packet response = null;
 
       try
@@ -770,13 +916,32 @@
          }
       }
 
-      sendResponse(result, response);
+      channel.send(response);
    }
 
    public void handleAcknowledge(final SessionAcknowledgeMessage packet)
    {
       DelayedResult result = channel.replicatePacket(packet);
-
+      
+      if (result == null)
+      {
+         doHandleAcknowledge(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleAcknowledge(packet);
+            }
+         });
+      }
+   }
+   
+   public void doHandleAcknowledge(final SessionAcknowledgeMessage packet)
+   {
       Packet response = null;
 
       try
@@ -822,13 +987,35 @@
          }
       }
 
-      sendResponse(result, response);
+      if (response != null)
+      {
+         channel.send(response);
+      }
    }
-
+   
    public void handleCommit(final Packet packet)
    {
       DelayedResult result = channel.replicatePacket(packet);
+      
+      if (result == null)
+      {
+         doHandleCommit(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleCommit(packet);
+            }
+         });
+      }
+   }
 
+   public void doHandleCommit(final Packet packet)
+   {
       Packet response = null;
 
       try
@@ -855,13 +1042,32 @@
          tx = new TransactionImpl(storageManager, postOffice);
       }
 
-      sendResponse(result, response);
+      channel.send(response);
    }
-
+   
    public void handleRollback(final Packet packet)
-   {
+   {      
       DelayedResult result = channel.replicatePacket(packet);
+      
+      if (result == null)
+      {
+         doHandleRollback(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleRollback(packet);
+            }
+         });
+      }
+   }
 
+   public void doHandleRollback(final Packet packet)
+   {   
       Packet response = null;
 
       try
@@ -884,13 +1090,32 @@
          }
       }
 
-      sendResponse(result, response);
+      channel.send(response);
    }
 
    public void handleXACommit(final SessionXACommitMessage packet)
    {
       DelayedResult result = channel.replicatePacket(packet);
-
+      
+      if (result == null)
+      {
+         doHandleXACommit(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleXACommit(packet);
+            }
+         });
+      }
+   }
+   
+   public void doHandleXACommit(final SessionXACommitMessage packet)
+   {
       Packet response = null;
 
       Xid xid = packet.getXid();
@@ -947,13 +1172,32 @@
          }
       }
 
-      sendResponse(result, response);
+      channel.send(response);
    }
-
+   
    public void handleXAEnd(final SessionXAEndMessage packet)
    {
       DelayedResult result = channel.replicatePacket(packet);
-
+      
+      if (result == null)
+      {
+         doHandleXAEnd(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleXAEnd(packet);
+            }
+         });
+      }
+   }
+   
+   public void doHandleXAEnd(final SessionXAEndMessage packet)
+   {
       Packet response = null;
 
       Xid xid = packet.getXid();
@@ -1021,25 +1265,63 @@
          }
       }
 
-      sendResponse(result, response);
+      channel.send(response);
    }
-
+   
    public void handleXAForget(final SessionXAForgetMessage packet)
    {
       DelayedResult result = channel.replicatePacket(packet);
+      
+      if (result == null)
+      {
+         doHandleXAForget(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleXAForget(packet);
+            }
+         });
+      }
+   }
 
+   public void doHandleXAForget(final SessionXAForgetMessage packet)
+   {
       // Do nothing since we don't support heuristic commits / rollback from the
       // resource manager
 
       Packet response = new SessionXAResponseMessage(false, XAResource.XA_OK, null);
 
-      sendResponse(result, response);
+      channel.send(response);
    }
 
    public void handleXAJoin(final SessionXAJoinMessage packet)
    {
       DelayedResult result = channel.replicatePacket(packet);
-
+      
+      if (result == null)
+      {
+         doHandleXAJoin(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleXAJoin(packet);
+            }
+         });
+      }
+   }
+   
+   public void doHandleXAJoin(final SessionXAJoinMessage packet)
+   {
       Packet response = null;
 
       Xid xid = packet.getXid();
@@ -1084,13 +1366,32 @@
          }
       }
 
-      sendResponse(result, response);
+      channel.send(response);
    }
 
    public void handleXAResume(final SessionXAResumeMessage packet)
    {
       DelayedResult result = channel.replicatePacket(packet);
-
+      
+      if (result == null)
+      {
+         doHandleXAResume(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleXAResume(packet);
+            }
+         });
+      }
+   }
+   
+   public void doHandleXAResume(final SessionXAResumeMessage packet)
+   {
       Packet response = null;
 
       Xid xid = packet.getXid();
@@ -1146,13 +1447,32 @@
          }
       }
 
-      sendResponse(result, response);
+      channel.send(response);
    }
-
+   
    public void handleXARollback(final SessionXARollbackMessage packet)
    {
       DelayedResult result = channel.replicatePacket(packet);
+      
+      if (result == null)
+      {
+         doHandleXARollback(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleXARollback(packet);
+            }
+         });
+      }
+   }
 
+   public void doHandleXARollback(final SessionXARollbackMessage packet)
+   {
       Packet response = null;
 
       Xid xid = packet.getXid();
@@ -1209,13 +1529,32 @@
          }
       }
 
-      sendResponse(result, response);
+      channel.send(response);
    }
 
    public void handleXAStart(final SessionXAStartMessage packet)
    {
       DelayedResult result = channel.replicatePacket(packet);
-
+      
+      if (result == null)
+      {
+         doHandleXAStart(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleXAStart(packet);
+            }
+         });
+      }
+   }
+   
+   public void doHandleXAStart(final SessionXAStartMessage packet)
+   {
       Packet response = null;
 
       Xid xid = packet.getXid();
@@ -1260,13 +1599,32 @@
          }
       }
 
-      sendResponse(result, response);
+      channel.send(response);
    }
 
    public void handleXASuspend(final Packet packet)
    {
       DelayedResult result = channel.replicatePacket(packet);
-
+      
+      if (result == null)
+      {
+         doHandleXASuspend(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleXASuspend(packet);
+            }
+         });
+      }
+   }
+   
+   public void doHandleXASuspend(final Packet packet)
+   {
       Packet response = null;
 
       try
@@ -1309,13 +1667,32 @@
          }
       }
 
-      sendResponse(result, response);
+      channel.send(response);
    }
 
    public void handleXAPrepare(final SessionXAPrepareMessage packet)
    {
       DelayedResult result = channel.replicatePacket(packet);
-
+      
+      if (result == null)
+      {
+         doHandleXAPrepare(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleXAPrepare(packet);
+            }
+         });
+      }
+   }
+   
+   public void doHandleXAPrepare(final SessionXAPrepareMessage packet)
+   {
       Packet response = null;
 
       Xid xid = packet.getXid();
@@ -1376,40 +1753,116 @@
          }
       }
 
-      sendResponse(result, response);
+      channel.send(response);
    }
 
    public void handleGetInDoubtXids(final Packet packet)
    {
       DelayedResult result = channel.replicatePacket(packet);
-
+      
+      if (result == null)
+      {
+         doHandleGetInDoubtXids(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleGetInDoubtXids(packet);
+            }
+         });
+      }
+   }
+   
+   public void doHandleGetInDoubtXids(final Packet packet)
+   {
       Packet response = new SessionXAGetInDoubtXidsResponseMessage(resourceManager.getPreparedTransactions());
 
-      sendResponse(result, response);
+      channel.send(response);
    }
 
    public void handleGetXATimeout(final Packet packet)
    {
       DelayedResult result = channel.replicatePacket(packet);
-
+      
+      if (result == null)
+      {
+         doHandleGetXATimeout(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleGetXATimeout(packet);
+            }
+         });
+      }
+   }
+   
+   public void doHandleGetXATimeout(final Packet packet)
+   {
       Packet response = new SessionXAGetTimeoutResponseMessage(resourceManager.getTimeoutSeconds());
 
-      sendResponse(result, response);
+      channel.send(response);
    }
 
    public void handleSetXATimeout(final SessionXASetTimeoutMessage packet)
    {
       DelayedResult result = channel.replicatePacket(packet);
-
+      
+      if (result == null)
+      {
+         doHandleSetXATimeout(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleSetXATimeout(packet);
+            }
+         });
+      }
+   }
+   
+   public void doHandleSetXATimeout(final SessionXASetTimeoutMessage packet)
+   {
       Packet response = new SessionXASetTimeoutResponseMessage(resourceManager.setTimeoutSeconds(packet.getTimeoutSeconds()));
 
-      sendResponse(result, response);
+      channel.send(response);
    }
-
+   
    public void handleAddDestination(final SessionAddDestinationMessage packet)
    {
       DelayedResult result = channel.replicatePacket(packet);
+      
+      if (result == null)
+      {
+         doHandleAddDestination(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleAddDestination(packet);
+            }
+         });
+      }
+   }
 
+   public void doHandleAddDestination(final SessionAddDestinationMessage packet)
+   {
       Packet response = null;
 
       final SimpleString address = packet.getAddress();
@@ -1467,13 +1920,32 @@
          }
       }
 
-      sendResponse(result, response);
+      channel.send(response);
    }
-
+   
    public void handleRemoveDestination(final SessionRemoveDestinationMessage packet)
    {
       DelayedResult result = channel.replicatePacket(packet);
+      
+      if (result == null)
+      {
+         doHandleRemoveDestination(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleRemoveDestination(packet);
+            }
+         });
+      }
+   }
 
+   public void doHandleRemoveDestination(final SessionRemoveDestinationMessage packet)
+   {
       Packet response = null;
 
       final SimpleString address = packet.getAddress();
@@ -1506,7 +1978,7 @@
          }
       }
 
-      sendResponse(result, response);
+      channel.send(response);
    }
 
    private void lockConsumers()
@@ -1543,8 +2015,9 @@
          channel.replicatePacket(packet);
 
          // set started will unlock
-         setStarted(true);
-
+         
+         //note we process start before response is back from the backup
+         setStarted(true);         
       }
       finally
       {
@@ -1555,6 +2028,7 @@
       }
    }
 
+   //TODO try removing the lock consumers and see what happens!!
    public void handleStop(final Packet packet)
    {
       boolean lock = this.channel.getReplicatingChannel() != null;
@@ -1568,6 +2042,8 @@
       {
          DelayedResult result = channel.replicatePacket(packet);
 
+         //note we process stop before response is back from the backup
+         
          setStarted(false);
 
          sendResponse(result, new NullResponseMessage());
@@ -1591,15 +2067,44 @@
          consumer.failedOver();
       }
    }
-
+   
    public void handleClose(final Packet packet)
    {
+      //We need to stop the consumers first before replicating, to ensure no deliveries occur after this,
+      //but we need to process the actual close() when the replication response returns, otherwise things
+      //can happen like acks can come in after close
+      
+      for (ServerConsumer consumer : consumers.values())
+      {
+         consumer.setStarted(false);
+      }
+      
       DelayedResult result = channel.replicatePacket(packet);
+      
+      if (result == null)
+      {
+         doHandleClose(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleClose(packet);
+            }
+         });
+      }
+   }
 
+   public void doHandleClose(final Packet packet)
+   {
       Packet response = null;
 
       try
       {
+         //note we process close before response is back from the backup
          close();
 
          response = new NullResponseMessage();
@@ -1618,7 +2123,7 @@
          }
       }
 
-      sendResponse(result, response, true);
+      channel.send(response);
    }
 
    private void setStarted(final boolean s)
@@ -1632,16 +2137,86 @@
 
       started = s;
    }
-
+   
    public void handleCloseConsumer(final SessionConsumerCloseMessage packet)
    {
-      consumers.get(packet.getConsumerID()).handleClose(packet);
+      //We need to stop the consumer first before replicating, to ensure no deliveries occur after this,
+      //but we need to process the actual close() when the replication response returns, otherwise things
+      //can happen like acks can come in after close
+      
+      ServerConsumer consumer = consumers.get(packet.getConsumerID());    
+      
+      consumer.handleClose(packet);
+      
+//      DelayedResult result = channel.replicatePacket(packet);
+//      
+//      if (result == null)
+//      {
+//         doHandleCloseConsumer(packet);
+//      }
+//      else
+//      {
+//         //Don't process until result has come back from backup
+//         result.setResultRunner(new Runnable()
+//         {
+//            public void run()
+//            {
+//               doHandleCloseConsumer(packet);
+//            }
+//         });
+//      }
    }
 
+   public void doHandleCloseConsumer(final SessionConsumerCloseMessage packet)
+   {
+      Packet response = null;
+
+      try
+      {
+         consumers.get(packet.getConsumerID()).close();
+   
+         response = new NullResponseMessage();
+      }
+      catch (Exception e)
+      {
+         log.error("Failed to close", e);
+   
+         if (e instanceof MessagingException)
+         {
+            response = new MessagingExceptionMessage((MessagingException)e);
+         }
+         else
+         {
+            response = new MessagingExceptionMessage(new MessagingException(MessagingException.INTERNAL_ERROR));
+         }
+      }
+   
+      channel.send(response);
+   }
+
    public void handleCloseProducer(final SessionProducerCloseMessage packet)
    {
       DelayedResult result = channel.replicatePacket(packet);
-
+      
+      if (result == null)
+      {
+         doHandleCloseProducer(packet);
+      }
+      else
+      {
+         //Don't process until result has come back from backup
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doHandleCloseProducer(packet);
+            }
+         });
+      }
+   }
+   
+   public void doHandleCloseProducer(final SessionProducerCloseMessage packet)
+   {
       Packet response = null;
 
       try
@@ -1664,7 +2239,7 @@
          }
       }
 
-      sendResponse(result, response);
+      channel.send(response);
    }
 
    public void handleReceiveConsumerCredits(final SessionConsumerFlowCreditMessage packet)
@@ -1673,6 +2248,7 @@
 
       try
       {
+         //Note we don't wait for response before handling this
          consumers.get(packet.getConsumerID()).receiveCredits(packet.getCredits());
       }
       catch (Exception e)
@@ -1682,9 +2258,22 @@
    }
 
    public void handleSendProducerMessage(final SessionSendMessage packet)
-   {
+   {               
       ServerMessage msg = packet.getServerMessage();
-
+      
+      final SendLock lock;
+            
+      if (channel.getReplicatingChannel() != null)
+      {
+         lock = postOffice.getAddressLock(msg.getDestination());
+               
+         lock.beforeSend();
+      }
+      else
+      {
+         lock = null;
+      }
+      
       if (msg.getMessageID() == 0L)
       {
          // must generate message id here, so we know they are in sync on live and backup
@@ -1694,12 +2283,38 @@
       }
 
       DelayedResult result = channel.replicatePacket(packet);
-
+      
+      //With a send we must make sure it is replicated to backup before being processed on live
+      //or can end up with delivery being processed on backup before original send
+      
+      if (result == null)
+      {
+         doSend(packet);                        
+      }
+      else
+      {
+         result.setResultRunner(new Runnable()
+         {
+            public void run()
+            {
+               doSend(packet);
+               
+               lock.afterSend();
+            }
+         });
+      }
+   }
+   
+   private void doSend(final SessionSendMessage packet)
+   {
+      //With a send we must make sure it is replicated to backup before being processed on live
+      //or can end up with delivery being processed on backup before original send
+      
       Packet response = null;
 
       try
       {
-         producers.get(packet.getProducerID()).send(msg);
+         producers.get(packet.getProducerID()).send(packet.getServerMessage());
 
          if (packet.isRequiresResponse())
          {
@@ -1722,8 +2337,11 @@
             }
          }
       }
-
-      sendResponse(result, response);
+      
+      if (response != null)
+      {
+         channel.send(response);
+      }
    }
 
    public void handleSendScheduledProducerMessage(final SessionScheduledSendMessage packet)
@@ -1878,6 +2496,11 @@
 
       return serverLastReceivedCommandID;
    }
+   
+   public Channel getChannel()
+   {
+      return channel;
+   }
 
    // FailureListener implementation
    // --------------------------------------------------------------------

Modified: trunk/src/main/org/jboss/messaging/core/transaction/ResourceManager.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/transaction/ResourceManager.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/transaction/ResourceManager.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,10 +22,11 @@
 
 package org.jboss.messaging.core.transaction;
 
-import javax.transaction.xa.Xid;
 import java.util.List;
 
+import javax.transaction.xa.Xid;
 
+
 /**
  * 
  * A ResourceManager

Modified: trunk/src/main/org/jboss/messaging/core/transaction/Transaction.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/transaction/Transaction.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/transaction/Transaction.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,6 +22,10 @@
 
 package org.jboss.messaging.core.transaction;
 
+import java.util.List;
+
+import javax.transaction.xa.Xid;
+
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.paging.PageTransactionInfo;
 import org.jboss.messaging.core.server.MessageReference;
@@ -29,9 +33,6 @@
 import org.jboss.messaging.core.settings.HierarchicalRepository;
 import org.jboss.messaging.core.settings.impl.QueueSettings;
 
-import javax.transaction.xa.Xid;
-import java.util.List;
-
 /**
  * A JBoss Messaging internal transaction
  *

Modified: trunk/src/main/org/jboss/messaging/core/transaction/impl/ResourceManagerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/transaction/impl/ResourceManagerImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/transaction/impl/ResourceManagerImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,15 +22,16 @@
 
 package org.jboss.messaging.core.transaction.impl;
 
-import org.jboss.messaging.core.transaction.ResourceManager;
-import org.jboss.messaging.core.transaction.Transaction;
-
-import javax.transaction.xa.Xid;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 
+import javax.transaction.xa.Xid;
+
+import org.jboss.messaging.core.transaction.ResourceManager;
+import org.jboss.messaging.core.transaction.Transaction;
+
 /**
  * 
  * A ResourceManagerImpl

Modified: trunk/src/main/org/jboss/messaging/core/transaction/impl/TransactionImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/transaction/impl/TransactionImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/core/transaction/impl/TransactionImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -253,7 +253,12 @@
    }
 
    public void commit() throws Exception
-   {
+   {      
+//      if (inMethod != -1)
+//      {
+//         throw new IllegalStateException("Can't commit, already inmethod " + inMethod);
+//      }
+      inMethod = 2;
       if (state == State.ROLLBACK_ONLY)
       {
          if (messagingException != null)
@@ -320,11 +325,17 @@
 
       clear();
 
-      state = State.COMMITTED;
+      state = State.COMMITTED;   
+      inMethod = -1;
    }
 
    public List<MessageReference> rollback(final HierarchicalRepository<QueueSettings> queueSettingsRepository) throws Exception
    {
+//      if (inMethod != -1)
+//      {
+//         throw new IllegalStateException("Can't rollback, already inmethod " + inMethod);
+//      }
+      inMethod=1;
       if (xid != null)
       {
          if (state != State.PREPARED && state != State.ACTIVE)
@@ -374,6 +385,7 @@
 
       state = State.ROLLEDBACK;
       
+      inMethod = -1;
       return toCancel;
    }
 
@@ -458,8 +470,15 @@
    // Private
    // -------------------------------------------------------------------
 
+   private volatile int inMethod;
+   
    private List<MessageReference> route(final ServerMessage message) throws Exception
    {
+//      if (inMethod != -1)
+//      {
+//         throw new IllegalStateException("Can't route, already inmethod " + inMethod);
+//      }
+      inMethod = 0;
       List<MessageReference> refs = postOffice.route(message);
 
       refsToAdd.addAll(refs);
@@ -470,6 +489,7 @@
 
          containsPersistent = true;
       }
+      inMethod = -1;
       return refs;
    }
 

Modified: trunk/src/main/org/jboss/messaging/jms/client/JBossConnectionFactory.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/client/JBossConnectionFactory.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/jms/client/JBossConnectionFactory.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -12,6 +12,24 @@
 
 package org.jboss.messaging.jms.client;
 
+import java.io.Serializable;
+
+import javax.jms.Connection;
+import javax.jms.ConnectionFactory;
+import javax.jms.JMSException;
+import javax.jms.QueueConnection;
+import javax.jms.QueueConnectionFactory;
+import javax.jms.TopicConnection;
+import javax.jms.TopicConnectionFactory;
+import javax.jms.XAConnection;
+import javax.jms.XAConnectionFactory;
+import javax.jms.XAQueueConnection;
+import javax.jms.XAQueueConnectionFactory;
+import javax.jms.XATopicConnection;
+import javax.jms.XATopicConnectionFactory;
+import javax.naming.NamingException;
+import javax.naming.Reference;
+
 import org.jboss.messaging.core.client.ClientSession;
 import org.jboss.messaging.core.client.ClientSessionFactory;
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
@@ -21,11 +39,6 @@
 import org.jboss.messaging.jms.referenceable.ConnectionFactoryObjectFactory;
 import org.jboss.messaging.jms.referenceable.SerializableObjectRefAddr;
 
-import javax.jms.*;
-import javax.naming.NamingException;
-import javax.naming.Reference;
-import java.io.Serializable;
-
 /**
  * @author <a href="mailto:ovidiu at feodorov.com">Ovidiu Feodorov</a>
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
@@ -58,6 +71,8 @@
    private final int dupsOKBatchSize;
 
    private final long pingPeriod;
+   
+   private final int pingPoolSize;
 
    private final long callTimeout;
 
@@ -76,12 +91,15 @@
    private final boolean blockOnPersistentSend;
 
    private final boolean autoGroupId;
+   
+   private final int maxConnections;
 
    // Constructors ---------------------------------------------------------------------------------
 
    public JBossConnectionFactory(final TransportConfiguration connectorConfig,
                                  final TransportConfiguration backupConnectorConfig,
                                  final long pingPeriod,
+                                 final int pingPoolSize,
                                  final long callTimeout,
                                  final String clientID,
                                  final int dupsOKBatchSize,
@@ -92,13 +110,15 @@
                                  final boolean blockOnAcknowledge,
                                  final boolean blockOnNonPersistentSend,
                                  final boolean blockOnPersistentSend,
-                                 final boolean autoGroupId)
+                                 final boolean autoGroupId,
+                                 final int maxConnections)
    {
       this.connectorConfig = connectorConfig;
       this.backupConnectorConfig = backupConnectorConfig;
       this.clientID = clientID;
       this.dupsOKBatchSize = dupsOKBatchSize;
       this.pingPeriod = pingPeriod;
+      this.pingPoolSize = pingPoolSize;
       this.callTimeout = callTimeout;
       this.consumerMaxRate = consumerMaxRate;
       this.consumerWindowSize = consumerWindowSize;
@@ -108,6 +128,7 @@
       this.blockOnNonPersistentSend = blockOnNonPersistentSend;
       this.blockOnPersistentSend = blockOnPersistentSend;
       this.autoGroupId = autoGroupId;
+      this.maxConnections = maxConnections;
    }
 
    // ConnectionFactory implementation -------------------------------------------------------------
@@ -203,6 +224,11 @@
    {
       return pingPeriod;
    }
+   
+   public int getPingPoolSize()
+   {
+      return pingPoolSize;
+   }
 
    public long getCallTimeout()
    {
@@ -274,6 +300,7 @@
          sessionFactory = new ClientSessionFactoryImpl(connectorConfig,
                                                        backupConnectorConfig,
                                                        pingPeriod,
+                                                       pingPoolSize,
                                                        callTimeout,
                                                        consumerWindowSize,
                                                        consumerMaxRate,
@@ -282,7 +309,8 @@
                                                        blockOnAcknowledge,
                                                        blockOnNonPersistentSend,
                                                        blockOnPersistentSend,
-                                                       autoGroupId);
+                                                       autoGroupId,
+                                                       maxConnections);
 
       }
 

Modified: trunk/src/main/org/jboss/messaging/jms/client/JBossConnectionMetaData.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/client/JBossConnectionMetaData.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/jms/client/JBossConnectionMetaData.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,13 +22,14 @@
 
 package org.jboss.messaging.jms.client;
 
-import org.jboss.messaging.core.version.Version;
+import java.util.Enumeration;
+import java.util.Vector;
 
 import javax.jms.ConnectionMetaData;
 import javax.jms.JMSException;
-import java.util.Enumeration;
-import java.util.Vector;
 
+import org.jboss.messaging.core.version.Version;
+
 /**
  * Connection metadata
  *

Modified: trunk/src/main/org/jboss/messaging/jms/client/JBossMessage.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/client/JBossMessage.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/jms/client/JBossMessage.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -12,6 +12,22 @@
 
 package org.jboss.messaging.jms.client;
 
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.List;
+
+import javax.jms.DeliveryMode;
+import javax.jms.Destination;
+import javax.jms.InvalidDestinationException;
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageFormatException;
+import javax.jms.MessageNotReadableException;
+import javax.jms.MessageNotWriteableException;
+
 import org.jboss.messaging.core.client.ClientMessage;
 import org.jboss.messaging.core.client.ClientSession;
 import org.jboss.messaging.core.client.impl.ClientMessageImpl;
@@ -23,21 +39,6 @@
 import org.jboss.messaging.jms.JBossDestination;
 import org.jboss.messaging.util.SimpleString;
 
-import javax.jms.DeliveryMode;
-import javax.jms.Destination;
-import javax.jms.InvalidDestinationException;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageFormatException;
-import javax.jms.MessageNotReadableException;
-import javax.jms.MessageNotWriteableException;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.List;
-
 /**
  * Implementation of a JMS Message JMS Messages only live on the client side - the server only deals with MessageImpl
  * instances

Modified: trunk/src/main/org/jboss/messaging/jms/client/JBossMessageConsumer.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/client/JBossMessageConsumer.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/jms/client/JBossMessageConsumer.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -29,7 +29,6 @@
 import javax.jms.MessageListener;
 import javax.jms.Queue;
 import javax.jms.QueueReceiver;
-import javax.jms.Session;
 import javax.jms.Topic;
 import javax.jms.TopicSubscriber;
 

Modified: trunk/src/main/org/jboss/messaging/jms/client/JBossMessageProducer.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/client/JBossMessageProducer.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/jms/client/JBossMessageProducer.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,14 +22,7 @@
 
 package org.jboss.messaging.jms.client;
 
-import org.jboss.messaging.core.client.ClientMessage;
-import org.jboss.messaging.core.client.ClientProducer;
-import org.jboss.messaging.core.client.ClientSession;
-import org.jboss.messaging.core.exception.MessagingException;
-import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.jms.JBossDestination;
-import org.jboss.messaging.util.SimpleString;
-import org.jboss.messaging.util.UUIDGenerator;
+import java.util.concurrent.atomic.AtomicLong;
 
 import javax.jms.BytesMessage;
 import javax.jms.DeliveryMode;
@@ -47,8 +40,16 @@
 import javax.jms.TextMessage;
 import javax.jms.Topic;
 import javax.jms.TopicPublisher;
-import java.util.concurrent.atomic.AtomicLong;
 
+import org.jboss.messaging.core.client.ClientMessage;
+import org.jboss.messaging.core.client.ClientProducer;
+import org.jboss.messaging.core.client.ClientSession;
+import org.jboss.messaging.core.exception.MessagingException;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.jms.JBossDestination;
+import org.jboss.messaging.util.SimpleString;
+import org.jboss.messaging.util.UUIDGenerator;
+
 /**
  * @author <a href="mailto:ovidiu at feodorov.com">Ovidiu Feodorov</a>
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>

Modified: trunk/src/main/org/jboss/messaging/jms/client/JBossQueueBrowser.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/client/JBossQueueBrowser.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/jms/client/JBossQueueBrowser.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -24,7 +24,6 @@
 
 import java.util.Enumeration;
 import java.util.NoSuchElementException;
-import java.util.UUID;
 
 import javax.jms.JMSException;
 import javax.jms.Queue;

Modified: trunk/src/main/org/jboss/messaging/jms/client/JBossSession.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/client/JBossSession.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/jms/client/JBossSession.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,19 +22,10 @@
 
 package org.jboss.messaging.jms.client;
 
-import org.jboss.messaging.core.client.ClientConsumer;
-import org.jboss.messaging.core.client.ClientProducer;
-import org.jboss.messaging.core.client.ClientSession;
-import org.jboss.messaging.core.exception.MessagingException;
-import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.remoting.impl.wireformat.SessionBindingQueryResponseMessage;
-import org.jboss.messaging.core.remoting.impl.wireformat.SessionQueueQueryResponseMessage;
-import org.jboss.messaging.jms.JBossDestination;
-import org.jboss.messaging.jms.JBossQueue;
-import org.jboss.messaging.jms.JBossTemporaryQueue;
-import org.jboss.messaging.jms.JBossTemporaryTopic;
-import org.jboss.messaging.jms.JBossTopic;
-import org.jboss.messaging.util.SimpleString;
+import java.io.Serializable;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.UUID;
 
 import javax.jms.BytesMessage;
 import javax.jms.Destination;
@@ -67,11 +58,21 @@
 import javax.jms.XASession;
 import javax.jms.XATopicSession;
 import javax.transaction.xa.XAResource;
-import java.io.Serializable;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.UUID;
 
+import org.jboss.messaging.core.client.ClientConsumer;
+import org.jboss.messaging.core.client.ClientProducer;
+import org.jboss.messaging.core.client.ClientSession;
+import org.jboss.messaging.core.exception.MessagingException;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionBindingQueryResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionQueueQueryResponseMessage;
+import org.jboss.messaging.jms.JBossDestination;
+import org.jboss.messaging.jms.JBossQueue;
+import org.jboss.messaging.jms.JBossTemporaryQueue;
+import org.jboss.messaging.jms.JBossTemporaryTopic;
+import org.jboss.messaging.jms.JBossTopic;
+import org.jboss.messaging.util.SimpleString;
+
 /**
  *
  * Note that we *do not* support JMS ASF (Application Server Facilities) optional

Modified: trunk/src/main/org/jboss/messaging/jms/server/JMSServerManager.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/server/JMSServerManager.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/jms/server/JMSServerManager.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,10 +22,10 @@
 
 package org.jboss.messaging.jms.server;
 
+import java.util.List;
+
 import org.jboss.messaging.core.config.TransportConfiguration;
 
-import java.util.List;
-
 /**
  * The JMS Management interface.
  * 
@@ -82,7 +82,7 @@
     *            if a problem occurred removing the destination
     */
    boolean undeployDestination(String name) throws Exception;
-   
+
    /**
     * destroys a queue and removes it from JNDI
     * 
@@ -105,27 +105,44 @@
     */
    boolean destroyTopic(String name) throws Exception;
 
-   boolean createConnectionFactory(String name, TransportConfiguration connectorConfig,
-            TransportConfiguration backupConnectorConfig,
-            long pingPeriod, long callTimeout, String clientID,
-         int dupsOKBatchSize, int consumerWindowSize, int consumerMaxRate,
-         int producerWindowSize, int producerMaxRate,
-         boolean blockOnAcknowledge,
-         boolean blockOnNonPersistentSend,
-         boolean blockOnPersistentSend, boolean autoGroupId, String jndiBinding)
-         throws Exception;
+   boolean createConnectionFactory(String name,
+                                   TransportConfiguration connectorConfig,
+                                   TransportConfiguration backupConnectorConfig,
+                                   long pingPeriod,
+                                   int pingPoolSize,
+                                   long callTimeout,
+                                   String clientID,
+                                   int dupsOKBatchSize,
+                                   int consumerWindowSize,
+                                   int consumerMaxRate,
+                                   int producerWindowSize,
+                                   int producerMaxRate,
+                                   boolean blockOnAcknowledge,
+                                   boolean blockOnNonPersistentSend,
+                                   boolean blockOnPersistentSend,
+                                   boolean autoGroupId,
+                                   int maxConnections,
+                                   String jndiBinding) throws Exception;
 
+   boolean createConnectionFactory(String name,
+                                   TransportConfiguration connectorConfig,
+                                   TransportConfiguration backupConnectorConfig,
+                                   long pingPeriod,
+                                   int pingPoolSize,
+                                   long callTimeout,
+                                   String clientID,
+                                   int dupsOKBatchSize,
+                                   int consumerWindowSize,
+                                   int consumerMaxRate,
+                                   int producerWindowSize,
+                                   int producerMaxRate,
+                                   boolean blockOnAcknowledge,
+                                   boolean blockOnNonPersistentSend,
+                                   boolean blockOnPersistentSend,
+                                   boolean autoGroupId,
+                                   int maxConnections,
+                                   List<String> jndiBinding) throws Exception;
 
-   boolean createConnectionFactory(String name, TransportConfiguration connectorConfig,
-            TransportConfiguration backupConnectorConfig,
-            long pingPeriod, long callTimeout, String clientID,
-         int dupsOKBatchSize, int consumerWindowSize, int consumerMaxRate,
-         int producerWindowSize, int producerMaxRate,
-         boolean blockOnAcknowledge,
-         boolean blockOnNonPersistentSend,
-         boolean blockOnPersistentSend, boolean autoGroupId,  List<String> jndiBinding)
-         throws Exception;
-
    /**
     * destroys a connection factory.
     * 

Modified: trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerDeployer.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerDeployer.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerDeployer.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -12,6 +12,11 @@
 
 package org.jboss.messaging.jms.server.impl;
 
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.config.impl.ConfigurationImpl;
@@ -23,11 +28,6 @@
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
 /**
  * @author <a href="ataylor at redhat.com">Andy Taylor</a>
  * @author <a href="tim.fox at jboss.com">Tim Fox</a>
@@ -43,6 +43,8 @@
    private static final String CLIENTID_ELEMENT = "client-id";
 
    private static final String PING_PERIOD_ELEMENT = "ping-period";
+   
+   private static final String PING_POOL_SIZE_ELEMENT = "ping-pool-size";
 
    private static final String CALL_TIMEOUT_ELEMENT = "call-timeout";
 
@@ -62,7 +64,9 @@
 
    private static final String SEND_P_MESSAGES_SYNCHRONOUSLY_ELEMENT = "send-p-messages-synchronously";
 
-   private static final String AUTO_GROUP_ID__ELEMENT = "auto-group-id";
+   private static final String AUTO_GROUP_ID_ELEMENT = "auto-group-id";
+   
+   private static final String MAX_CONNECTIONS_ELEMENT = "max-connections";
 
    private static final String CONNECTOR_ELEMENT = "connector";
 
@@ -128,6 +132,7 @@
          NodeList children = node.getChildNodes();
 
          long pingPeriod = ClientSessionFactoryImpl.DEFAULT_PING_PERIOD;
+         int pingPoolSize = ClientSessionFactoryImpl.DEFAULT_PING_POOL_SIZE;
          long callTimeout = ConfigurationImpl.DEFAULT_CALL_TIMEOUT;
          String clientID = null;
          int dupsOKBatchSize = DEFAULT_DUPS_OK_BATCH_SIZE;
@@ -139,6 +144,7 @@
          boolean blockOnNonPersistentSend = ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND;
          boolean blockOnPersistentSend = ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_PERSISTENT_SEND;
          boolean autoGroupId = ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP_ID;
+         int maxConnections = ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS;
          List<String> jndiBindings = new ArrayList<String>();
          String connectorFactoryClassName = null;
          Map<String, Object> params = new HashMap<String, Object>();
@@ -151,6 +157,10 @@
             {
                pingPeriod = Long.parseLong(children.item(j).getTextContent().trim());
             }
+            else if (PING_POOL_SIZE_ELEMENT.equalsIgnoreCase(children.item(j).getNodeName()))
+            {
+               pingPoolSize = Integer.parseInt(children.item(j).getTextContent().trim());
+            }
             else if (CALL_TIMEOUT_ELEMENT.equalsIgnoreCase(children.item(j).getNodeName()))
             {
                callTimeout = Long.parseLong(children.item(j).getTextContent().trim());
@@ -191,10 +201,14 @@
             {
                blockOnPersistentSend = Boolean.parseBoolean(children.item(j).getTextContent().trim());
             }
-            else if(AUTO_GROUP_ID__ELEMENT.equalsIgnoreCase(children.item(j).getNodeName()))
+            else if(AUTO_GROUP_ID_ELEMENT.equalsIgnoreCase(children.item(j).getNodeName()))
             {
                autoGroupId = Boolean.parseBoolean(children.item(j).getTextContent().trim());
             }
+            else if(MAX_CONNECTIONS_ELEMENT.equalsIgnoreCase(children.item(j).getNodeName()))
+            {
+               maxConnections = Integer.parseInt(children.item(j).getTextContent().trim());
+            }
             else if (ENTRY_NODE_NAME.equalsIgnoreCase(children.item(j).getNodeName()))
             {
                String jndiName = children.item(j).getAttributes().getNamedItem("name").getNodeValue();
@@ -388,6 +402,7 @@
                                                   connectorConfig,
                                                   backupConnectorConfig,
                                                   pingPeriod,
+                                                  pingPoolSize,
                                                   callTimeout,
                                                   clientID,
                                                   dupsOKBatchSize,
@@ -399,6 +414,7 @@
                                                   blockOnNonPersistentSend,
                                                   blockOnPersistentSend,
                                                   autoGroupId,
+                                                  maxConnections,
                                                   jndiBindings);
       }
       else if (node.getNodeName().equals(QUEUE_NODE_NAME))

Modified: trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerManagerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerManagerImpl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerManagerImpl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,6 +22,15 @@
 
 package org.jboss.messaging.jms.server.impl;
 
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.management.MessagingServerControlMBean;
@@ -37,14 +46,6 @@
 import org.jboss.messaging.jms.server.management.JMSManagementService;
 import org.jboss.messaging.util.JNDIUtil;
 
-import javax.naming.Context;
-import javax.naming.InitialContext;
-import javax.naming.NamingException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
 /**
  * A Deployer used to create and add to JNDI queues, topics and connection
  * factories. Typically this would only be used in an app server env.
@@ -189,6 +190,7 @@
                                           TransportConfiguration connectorConfig,
                                           TransportConfiguration backupConnectorConfig,
                                           long pingPeriod,
+                                          int pingPoolSize,
                                           long callTimeout,
                                           String clientID,
                                           int dupsOKBatchSize,
@@ -200,6 +202,7 @@
                                           boolean blockOnNonPersistentSend,
                                           boolean blockOnPersistentSend,
                                           boolean autoGroupId,
+                                          int maxConnections,
                                           String jndiBinding) throws Exception
    {
       JBossConnectionFactory cf = connectionFactories.get(name);
@@ -208,6 +211,7 @@
          cf = new JBossConnectionFactory(connectorConfig,
                                          backupConnectorConfig,
                                          pingPeriod,
+                                         pingPoolSize,
                                          callTimeout,
                                          clientID,
                                          dupsOKBatchSize,
@@ -218,7 +222,8 @@
                                          blockOnAcknowledge,
                                          blockOnNonPersistentSend,
                                          blockOnPersistentSend,
-                                         autoGroupId);
+                                         autoGroupId,
+                                         maxConnections);
          connectionFactories.put(name, cf);
       }
       if (!bindToJndi(jndiBinding, cf))
@@ -242,6 +247,7 @@
                                           TransportConfiguration connectorConfig,
                                           TransportConfiguration backupConnectorConfig,
                                           long pingPeriod,
+                                          int pingPoolSize,
                                           long callTimeout,
                                           String clientID,
                                           int dupsOKBatchSize,
@@ -253,6 +259,7 @@
                                           boolean blockOnNonPersistentSend,
                                           boolean blockOnPersistentSend,
                                           boolean autoGroupId,
+                                          int maxConnections,
                                           List<String> jndiBindings) throws Exception
    {
       JBossConnectionFactory cf = connectionFactories.get(name);
@@ -261,6 +268,7 @@
          cf = new JBossConnectionFactory(connectorConfig,
                                          backupConnectorConfig,
                                          pingPeriod,
+                                         pingPoolSize,
                                          callTimeout,
                                          clientID,
                                          dupsOKBatchSize,
@@ -271,7 +279,8 @@
                                          blockOnAcknowledge,
                                          blockOnNonPersistentSend,
                                          blockOnPersistentSend,
-                                         autoGroupId);
+                                         autoGroupId,
+                                         maxConnections);
       }
       for (String jndiBinding : jndiBindings)
       {

Modified: trunk/src/main/org/jboss/messaging/jms/server/management/JMSServerControlMBean.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/server/management/JMSServerControlMBean.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/jms/server/management/JMSServerControlMBean.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,12 +22,12 @@
 
 package org.jboss.messaging.jms.server.management;
 
+import static javax.management.MBeanOperationInfo.ACTION;
+
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.management.Operation;
 import org.jboss.messaging.core.management.Parameter;
 
-import static javax.management.MBeanOperationInfo.ACTION;
-
 /**
  * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
  * 
@@ -45,49 +45,62 @@
    // Operations ----------------------------------------------------
 
    @Operation(desc = "Create a JMS Queue", impact = ACTION)
-   boolean createQueue(
-         @Parameter(name = "name", desc = "Name of the queue to create") String name,
-         @Parameter(name = "jndiBinding", desc = "the name of the binding for JNDI") String jndiBinding)
-         throws Exception;
+   boolean createQueue(@Parameter(name = "name", desc = "Name of the queue to create")
+   String name, @Parameter(name = "jndiBinding", desc = "the name of the binding for JNDI")
+   String jndiBinding) throws Exception;
 
    @Operation(desc = "Destroy a JMS Queue", impact = ACTION)
-   boolean destroyQueue(
-         @Parameter(name = "name", desc = "Name of the queue to destroy") String name)
-         throws Exception;
+   boolean destroyQueue(@Parameter(name = "name", desc = "Name of the queue to destroy")
+   String name) throws Exception;
 
    @Operation(desc = "Create a JMS Topic", impact = ACTION)
-   boolean createTopic(
-         @Parameter(name = "name", desc = "Name of the topic to create") String name,
-         @Parameter(name = "jndiBinding", desc = "the name of the binding for JNDI") String jndiBinding)
-         throws Exception;
+   boolean createTopic(@Parameter(name = "name", desc = "Name of the topic to create")
+   String name, @Parameter(name = "jndiBinding", desc = "the name of the binding for JNDI")
+   String jndiBinding) throws Exception;
 
    @Operation(desc = "Destroy a JMS Topic", impact = ACTION)
-   boolean destroyTopic(
-         @Parameter(name = "name", desc = "Name of the topic to destroy") String name)
-         throws Exception;
+   boolean destroyTopic(@Parameter(name = "name", desc = "Name of the topic to destroy")
+   String name) throws Exception;
 
    @Operation(desc = "Create a JMS ConnectionFactory", impact = ACTION)
-   void createConnectionFactory(
-         @Parameter(name = "name", desc = "Name of the ConnectionFactory to create") String name,
-         @Parameter(name = "transportConfiguration", desc = "The remoting connector configuration") TransportConfiguration connectorConfig,
-         @Parameter(name = "backupTransportConfiguration", desc = "The backup remoting connector configuration") TransportConfiguration backupConnectorConfig,
-         @Parameter(name = "pingPeriod", desc = "The ping period in m") long pingPeriod,
-         @Parameter(name = "callTimeout", desc = "The call timeout in m") long callTimeout,
-         @Parameter(name = "clientID", desc = "ClientID for created connections") String clientID,
-         @Parameter(name = "dupsOKBatchSize", desc = "Size of the batch when using DUPS_OK") int dupsOKBatchSize,
-         @Parameter(name = "consumerWindowSize", desc = "Consumer's window size") int consumerWindowSize,
-         @Parameter(name = "consumerMaxRate", desc = "Consumer's max rate") int consumerMaxRate,
-         @Parameter(name = "producerWindowSize", desc = "Producer's window size") int producerWindowSize,
-         @Parameter(name = "producerMaxRate", desc = "Producer's max rate") int producerMaxRate,
-         @Parameter(name = "blockOnAcknowledge", desc = "Does acknowlegment block?") boolean blockOnAcknowledge,
-         @Parameter(name = "blockOnNonPersistentSend", desc = "Does sending non persistent messages block?") boolean blockOnNonPersistentSend,
-         @Parameter(name = "blockOnPersistentSend", desc = "Does sending persistent messages block") boolean blockOnPersistentSend,
-         @Parameter(name = "autoGroupId", desc = "Any Messages sent via this factories connections will automatically set th eproperty 'JMSXGroupId'") boolean autoGroupId,
-         @Parameter(name = "jndiBinding", desc = "JNDI Binding") String jndiBinding)         
-                  throws Exception;
+   void createConnectionFactory(@Parameter(name = "name", desc = "Name of the ConnectionFactory to create")
+                                String name,
+                                @Parameter(name = "transportConfiguration", desc = "The remoting connector configuration")
+                                TransportConfiguration connectorConfig,
+                                @Parameter(name = "backupTransportConfiguration", desc = "The backup remoting connector configuration")
+                                TransportConfiguration backupConnectorConfig,
+                                @Parameter(name = "pingPeriod", desc = "The ping period in m")
+                                long pingPeriod,
+                                @Parameter(name = "pingPoolSize", desc = "The max size of thread pool used for pinging")
+                                int pingPoolSize,
+                                @Parameter(name = "callTimeout", desc = "The call timeout in m")
+                                long callTimeout,
+                                @Parameter(name = "clientID", desc = "ClientID for created connections")
+                                String clientID,
+                                @Parameter(name = "dupsOKBatchSize", desc = "Size of the batch when using DUPS_OK")
+                                int dupsOKBatchSize,
+                                @Parameter(name = "consumerWindowSize", desc = "Consumer's window size")
+                                int consumerWindowSize,
+                                @Parameter(name = "consumerMaxRate", desc = "Consumer's max rate")
+                                int consumerMaxRate,
+                                @Parameter(name = "producerWindowSize", desc = "Producer's window size")
+                                int producerWindowSize,
+                                @Parameter(name = "producerMaxRate", desc = "Producer's max rate")
+                                int producerMaxRate,
+                                @Parameter(name = "blockOnAcknowledge", desc = "Does acknowlegment block?")
+                                boolean blockOnAcknowledge,
+                                @Parameter(name = "blockOnNonPersistentSend", desc = "Does sending non persistent messages block?")
+                                boolean blockOnNonPersistentSend,
+                                @Parameter(name = "blockOnPersistentSend", desc = "Does sending persistent messages block?")
+                                boolean blockOnPersistentSend,
+                                @Parameter(name = "autoGroupId", desc = "Any Messages sent via this factories connections will automatically set th eproperty 'JMSXGroupId'")
+                                boolean autoGroupId,
+                                @Parameter(name = "maxConnections", desc = "The maximum number of physical connections created per client using this connection factory. Sessions created will be assigned a connection in a round-robin fashion")
+                                int maxConnections,
+                                @Parameter(name = "jndiBinding", desc = "JNDI Binding")
+                                String jndiBinding) throws Exception;
 
    @Operation(desc = "Create a JMS ConnectionFactory", impact = ACTION)
-   void destroyConnectionFactory(
-         @Parameter(name = "name", desc = "Name of the ConnectionFactory to create") String name)
-         throws Exception;
+   void destroyConnectionFactory(@Parameter(name = "name", desc = "Name of the ConnectionFactory to create")
+   String name) throws Exception;
 }

Modified: trunk/src/main/org/jboss/messaging/jms/server/management/impl/JMSServerControl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/server/management/impl/JMSServerControl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/jms/server/management/impl/JMSServerControl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,24 +22,33 @@
 
 package org.jboss.messaging.jms.server.management.impl;
 
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
+
+import javax.management.ListenerNotFoundException;
+import javax.management.MBeanInfo;
+import javax.management.MBeanNotificationInfo;
+import javax.management.NotCompliantMBeanException;
+import javax.management.Notification;
+import javax.management.NotificationBroadcasterSupport;
+import javax.management.NotificationEmitter;
+import javax.management.NotificationFilter;
+import javax.management.NotificationListener;
+import javax.management.StandardMBean;
+
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.management.impl.MBeanInfoHelper;
 import org.jboss.messaging.jms.server.JMSServerManager;
 import org.jboss.messaging.jms.server.management.JMSServerControlMBean;
 
-import javax.management.*;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicLong;
-
 /**
  * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
  * 
  * @version <tt>$Revision$</tt>
  * 
  */
-public class JMSServerControl extends StandardMBean implements
-      JMSServerControlMBean, NotificationEmitter
+public class JMSServerControl extends StandardMBean implements JMSServerControlMBean, NotificationEmitter
 {
 
    // Constants -----------------------------------------------------
@@ -47,15 +56,16 @@
    // Attributes ----------------------------------------------------
 
    private final JMSServerManager server;
+
    private NotificationBroadcasterSupport broadcaster;
+
    private AtomicLong notifSeq = new AtomicLong(0);
 
    // Static --------------------------------------------------------
 
    // Constructors --------------------------------------------------
 
-   public JMSServerControl(final JMSServerManager server)
-         throws NotCompliantMBeanException
+   public JMSServerControl(final JMSServerManager server) throws NotCompliantMBeanException
    {
       super(JMSServerControlMBean.class);
       this.server = server;
@@ -66,32 +76,53 @@
 
    // JMSServerControlMBean implementation --------------------------
 
-   public void createConnectionFactory(String name, TransportConfiguration connectorConfig,
-            TransportConfiguration backupConnectorConfig,
-            long pingPeriod, long callTimeout, String clientID,
-         int dupsOKBatchSize, int consumerWindowSize, int consumerMaxRate,
-         int producerWindowSize, int producerMaxRate,
-         boolean blockOnAcknowledge,
-         boolean blockOnNonPersistentSend,
-         boolean blockOnPersistentSend, boolean autoGroupId, String jndiBinding) throws Exception
+   public void createConnectionFactory(String name,
+                                       TransportConfiguration connectorConfig,
+                                       TransportConfiguration backupConnectorConfig,
+                                       long pingPeriod,
+                                       int pingPoolSize,
+                                       long callTimeout,
+                                       String clientID,
+                                       int dupsOKBatchSize,
+                                       int consumerWindowSize,
+                                       int consumerMaxRate,
+                                       int producerWindowSize,
+                                       int producerMaxRate,
+                                       boolean blockOnAcknowledge,
+                                       boolean blockOnNonPersistentSend,
+                                       boolean blockOnPersistentSend,
+                                       boolean autoGroupId,
+                                       int maxConnections,
+                                       String jndiBinding) throws Exception
    {
       List<String> bindings = new ArrayList<String>();
       bindings.add(jndiBinding);
 
-      boolean created = server.createConnectionFactory(name, connectorConfig,
-               backupConnectorConfig,
-                  pingPeriod, callTimeout, clientID, dupsOKBatchSize, 
-               consumerWindowSize, consumerMaxRate, producerWindowSize, producerMaxRate, 
-               blockOnAcknowledge, blockOnNonPersistentSend, 
-               blockOnPersistentSend, autoGroupId, jndiBinding);
+      boolean created = server.createConnectionFactory(name,
+                                                       connectorConfig,
+                                                       backupConnectorConfig,
+                                                       pingPeriod,
+                                                       pingPoolSize,
+                                                       callTimeout,
+                                                       clientID,
+                                                       dupsOKBatchSize,
+                                                       consumerWindowSize,
+                                                       consumerMaxRate,
+                                                       producerWindowSize,
+                                                       producerMaxRate,
+                                                       blockOnAcknowledge,
+                                                       blockOnNonPersistentSend,
+                                                       blockOnPersistentSend,
+                                                       autoGroupId,
+                                                       maxConnections,
+                                                       jndiBinding);
       if (created)
       {
          sendNotification(NotificationType.CONNECTION_FACTORY_CREATED, name);
       }
    }
 
-   public boolean createQueue(final String name, final String jndiBinding)
-         throws Exception
+   public boolean createQueue(final String name, final String jndiBinding) throws Exception
    {
       boolean created = server.createQueue(name, jndiBinding);
       if (created)
@@ -111,8 +142,7 @@
       return destroyed;
    }
 
-   public boolean createTopic(final String topicName, final String jndiBinding)
-         throws Exception
+   public boolean createTopic(final String topicName, final String jndiBinding) throws Exception
    {
       boolean created = server.createTopic(topicName, jndiBinding);
       if (created)
@@ -154,21 +184,20 @@
    // NotificationEmitter implementation ----------------------------
 
    public void removeNotificationListener(final NotificationListener listener,
-         final NotificationFilter filter, final Object handback)
-         throws ListenerNotFoundException
+                                          final NotificationFilter filter,
+                                          final Object handback) throws ListenerNotFoundException
    {
       broadcaster.removeNotificationListener(listener, filter, handback);
    }
 
-   public void removeNotificationListener(final NotificationListener listener)
-         throws ListenerNotFoundException
+   public void removeNotificationListener(final NotificationListener listener) throws ListenerNotFoundException
    {
       broadcaster.removeNotificationListener(listener);
    }
 
    public void addNotificationListener(final NotificationListener listener,
-         final NotificationFilter filter, final Object handback)
-         throws IllegalArgumentException
+                                       final NotificationFilter filter,
+                                       final Object handback) throws IllegalArgumentException
    {
       broadcaster.addNotificationListener(listener, filter, handback);
    }
@@ -182,7 +211,8 @@
          names[i] = values[i].toString();
       }
       return new MBeanNotificationInfo[] { new MBeanNotificationInfo(names,
-            this.getClass().getName(), "Notifications emitted by a JMS Server") };
+                                                                     this.getClass().getName(),
+                                                                     "Notifications emitted by a JMS Server") };
    }
 
    // StandardMBean overrides
@@ -199,10 +229,12 @@
    public MBeanInfo getMBeanInfo()
    {
       MBeanInfo info = super.getMBeanInfo();
-      return new MBeanInfo(info.getClassName(), info.getDescription(), info
-            .getAttributes(), info.getConstructors(), MBeanInfoHelper
-            .getMBeanOperationsInfo(JMSServerControlMBean.class),
-            getNotificationInfo());
+      return new MBeanInfo(info.getClassName(),
+                           info.getDescription(),
+                           info.getAttributes(),
+                           info.getConstructors(),
+                           MBeanInfoHelper.getMBeanOperationsInfo(JMSServerControlMBean.class),
+                           getNotificationInfo());
    }
 
    // Package protected ---------------------------------------------
@@ -211,11 +243,9 @@
 
    // Private -------------------------------------------------------
 
-   private void sendNotification(final NotificationType type,
-         final String message)
+   private void sendNotification(final NotificationType type, final String message)
    {
-      Notification notif = new Notification(type.toString(), this, notifSeq
-            .incrementAndGet(), message);
+      Notification notif = new Notification(type.toString(), this, notifSeq.incrementAndGet(), message);
       broadcaster.sendNotification(notif);
    }
 
@@ -223,6 +253,11 @@
 
    public static enum NotificationType
    {
-      QUEUE_CREATED, QUEUE_DESTROYED, TOPIC_CREATED, TOPIC_DESTROYED, CONNECTION_FACTORY_CREATED, CONNECTION_FACTORY_DESTROYED;
+      QUEUE_CREATED,
+      QUEUE_DESTROYED,
+      TOPIC_CREATED,
+      TOPIC_DESTROYED,
+      CONNECTION_FACTORY_CREATED,
+      CONNECTION_FACTORY_DESTROYED;
    }
 }

Modified: trunk/src/main/org/jboss/messaging/jms/server/management/impl/TopicControl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/server/management/impl/TopicControl.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/jms/server/management/impl/TopicControl.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -41,7 +41,6 @@
 import org.jboss.messaging.core.server.MessageReference;
 import org.jboss.messaging.core.server.Queue;
 import org.jboss.messaging.core.server.ServerMessage;
-import org.jboss.messaging.core.settings.impl.QueueSettings;
 import org.jboss.messaging.jms.JBossTopic;
 import org.jboss.messaging.jms.server.management.JMSMessageInfo;
 import org.jboss.messaging.jms.server.management.SubscriptionInfo;

Modified: trunk/src/main/org/jboss/messaging/jms/server/recovery/MessagingXAResourceRecovery.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/server/recovery/MessagingXAResourceRecovery.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/jms/server/recovery/MessagingXAResourceRecovery.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -26,10 +26,10 @@
 
 import javax.transaction.xa.XAResource;
 
+import com.arjuna.ats.jta.recovery.XAResourceRecovery;
+
 import org.jboss.messaging.core.logging.Logger;
 
-import com.arjuna.ats.jta.recovery.XAResourceRecovery;
-
 /**
  * 
  * A XAResourceRecovery instance that can be used to recover any JMS provider.

Modified: trunk/src/main/org/jboss/messaging/util/SimpleString.java
===================================================================
--- trunk/src/main/org/jboss/messaging/util/SimpleString.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/src/main/org/jboss/messaging/util/SimpleString.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,14 +22,15 @@
 
 package org.jboss.messaging.util;
 
-import org.jboss.messaging.core.logging.Logger;
 import static org.jboss.messaging.util.DataConstants.SIZE_INT;
 
 import java.io.Serializable;
 import java.util.ArrayList;
 import java.util.List;
 
+import org.jboss.messaging.core.logging.Logger;
 
+
 /**
  * 
  * A SimpleString

Modified: trunk/tests/config/log4j.xml
===================================================================
--- trunk/tests/config/log4j.xml	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/config/log4j.xml	2008-10-30 16:12:28 UTC (rev 5222)
@@ -28,7 +28,7 @@
 
    <!-- A time/date based rolling appender -->
    <appender name="FILE" class="org.jboss.logging.appender.DailyRollingFileAppender">
-      <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/>
+      <!-- <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/> -->
 
       <param name="File" value="${module.output}tests/logs/messaging-tests.log"/>
 

Modified: trunk/tests/jms-tests/src/org/jboss/test/messaging/JBMServerTestCase.java
===================================================================
--- trunk/tests/jms-tests/src/org/jboss/test/messaging/JBMServerTestCase.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/jms-tests/src/org/jboss/test/messaging/JBMServerTestCase.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,6 +21,22 @@
    */
 package org.jboss.test.messaging;
 
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import javax.jms.Queue;
+import javax.jms.Topic;
+import javax.management.ObjectName;
+import javax.naming.InitialContext;
+import javax.sql.DataSource;
+import javax.transaction.TransactionManager;
+
 import org.jboss.messaging.core.security.Role;
 import org.jboss.messaging.core.server.MessagingServer;
 import org.jboss.messaging.jms.JBossQueue;
@@ -33,21 +49,6 @@
 import org.jboss.test.messaging.tools.container.Server;
 import org.jboss.tm.TransactionManagerLocator;
 
-import javax.jms.Queue;
-import javax.jms.Topic;
-import javax.management.ObjectName;
-import javax.naming.InitialContext;
-import javax.sql.DataSource;
-import javax.transaction.TransactionManager;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
 /**
  * @author <a href="mailto:adrian at jboss.org">Adrian Brock</a>
  * @author <a href="mailto:ovidiu at feodorov.com">Ovidiu Feodorov</a>

Modified: trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/BrowserTest.java
===================================================================
--- trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/BrowserTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/BrowserTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,7 +21,7 @@
   */
 package org.jboss.test.messaging.jms;
 
-import org.jboss.messaging.jms.JBossQueue;
+import java.util.Enumeration;
 
 import javax.jms.Connection;
 import javax.jms.InvalidDestinationException;
@@ -31,9 +31,10 @@
 import javax.jms.QueueBrowser;
 import javax.jms.Session;
 import javax.jms.TextMessage;
-import java.util.Enumeration;
 
+import org.jboss.messaging.jms.JBossQueue;
 
+
 /**
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
  * @author <a href="mailto:ovidiu at feodorov.com">Ovidiu Feodorov</a>

Modified: trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/CTSMiscellaneousTest.java
===================================================================
--- trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/CTSMiscellaneousTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/CTSMiscellaneousTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,6 +21,25 @@
  */
 package org.jboss.test.messaging.jms;
 
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.jms.BytesMessage;
+import javax.jms.Connection;
+import javax.jms.DeliveryMode;
+import javax.jms.InvalidSelectorException;
+import javax.jms.Message;
+import javax.jms.MessageConsumer;
+import javax.jms.MessageProducer;
+import javax.jms.QueueConnection;
+import javax.jms.QueueReceiver;
+import javax.jms.QueueSender;
+import javax.jms.QueueSession;
+import javax.jms.Session;
+import javax.jms.TextMessage;
+import javax.jms.TopicConnection;
+import javax.jms.TopicSession;
+
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.jms.client.JBossConnectionFactory;
 import org.jboss.test.messaging.JBMServerTestCase;
@@ -29,10 +48,6 @@
 import org.jboss.test.messaging.jms.message.SimpleJMSTextMessage;
 import org.jboss.test.messaging.tools.container.ServiceAttributeOverrides;
 
-import javax.jms.*;
-import java.util.ArrayList;
-import java.util.List;
-
 /**
  * Safeguards for previously detected TCK failures.
  *
@@ -44,299 +59,315 @@
  */
 public class CTSMiscellaneousTest extends JBMServerTestCase
 {
-	// Constants -----------------------------------------------------
+   // Constants -----------------------------------------------------
 
-	// Static --------------------------------------------------------
+   // Static --------------------------------------------------------
 
-	// Attributes ----------------------------------------------------
-	protected static JBossConnectionFactory cf;
-	protected ServiceAttributeOverrides overrides;
-	private static final String ORG_JBOSS_MESSAGING_SERVICE_LBCONNECTION_FACTORY = "StrictTCKConnectionFactory";
+   // Attributes ----------------------------------------------------
+   protected static JBossConnectionFactory cf;
 
-	// Constructors --------------------------------------------------
+   protected ServiceAttributeOverrides overrides;
 
-	public CTSMiscellaneousTest(String name)
-	{
-		super(name);
-	}
+   private static final String ORG_JBOSS_MESSAGING_SERVICE_LBCONNECTION_FACTORY = "StrictTCKConnectionFactory";
 
-	protected void setUp() throws Exception
-	{
-		try
-		{
-			super.setUp();
-			//Deploy a connection factory with load balancing but no failover on node0
+   // Constructors --------------------------------------------------
+
+   public CTSMiscellaneousTest(String name)
+   {
+      super(name);
+   }
+
+   protected void setUp() throws Exception
+   {
+      try
+      {
+         super.setUp();
+         // Deploy a connection factory with load balancing but no failover on node0
          List<String> bindings = new ArrayList<String>();
          bindings.add("StrictTCKConnectionFactory");
-         
+
          getJmsServerManager().createConnectionFactory("StrictTCKConnectionFactory",
-                  new TransportConfiguration("org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory"), null, 5000, 5000,                  
-                  null,
-               1000, 1024 * 1024, -1, 1000, -1, true, true, true, false, "/StrictTCKConnectionFactory");
-                 
-         cf = (JBossConnectionFactory) getInitialContext().lookup("/StrictTCKConnectionFactory");
-		}
-		catch (Exception e)
-		{
-			e.printStackTrace();
-		}
+                                                       new TransportConfiguration("org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory"),
+                                                       null,
+                                                       5000,
+                                                       5,
+                                                       5000,
+                                                       null,
+                                                       1000,
+                                                       1024 * 1024,
+                                                       -1,
+                                                       1000,
+                                                       -1,
+                                                       true,
+                                                       true,
+                                                       true,
+                                                       false,
+                                                       8,
+                                                       "/StrictTCKConnectionFactory");
 
-	}
+         cf = (JBossConnectionFactory)getInitialContext().lookup("/StrictTCKConnectionFactory");
+      }
+      catch (Exception e)
+      {
+         e.printStackTrace();
+      }
 
-	// Public --------------------------------------------------------
+   }
 
-	public void testForiengMessageSetDestination() throws Exception
-	{
-		Connection c = null;
+   // Public --------------------------------------------------------
 
-		try
-		{
-			c = cf.createConnection();
-			Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
+   public void testForiengMessageSetDestination() throws Exception
+   {
+      Connection c = null;
 
-			MessageProducer p = s.createProducer(queue1);
+      try
+      {
+         c = cf.createConnection();
+         Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
 
-			// create a Bytes foreign message
-			SimpleJMSTextMessage txt = new SimpleJMSTextMessage("hello from Brazil!");
-			txt.setJMSDestination(null);
+         MessageProducer p = s.createProducer(queue1);
 
-			p.send(txt);
+         // create a Bytes foreign message
+         SimpleJMSTextMessage txt = new SimpleJMSTextMessage("hello from Brazil!");
+         txt.setJMSDestination(null);
 
-			assertNotNull(txt.getJMSDestination());
+         p.send(txt);
 
-			MessageConsumer cons = s.createConsumer(queue1);
-			c.start();
+         assertNotNull(txt.getJMSDestination());
 
-			TextMessage tm = (TextMessage)cons.receive();
-			assertNotNull(tm);
-			assertEquals("hello from Brazil!", txt.getText());
-		}
-		catch(Exception e)
-		{
-			e.printStackTrace();
-		}
-		finally
-		{
-			if (c != null)
-			{
-				c.close();
-			}
-		}
+         MessageConsumer cons = s.createConsumer(queue1);
+         c.start();
 
-	}
+         TextMessage tm = (TextMessage)cons.receive();
+         assertNotNull(tm);
+         assertEquals("hello from Brazil!", txt.getText());
+      }
+      catch (Exception e)
+      {
+         e.printStackTrace();
+      }
+      finally
+      {
+         if (c != null)
+         {
+            c.close();
+         }
+      }
 
-	public void testForeignByteMessage() throws Exception
-	{
-		Connection c = null;
+   }
 
-		try
-		{	      
-			c = cf.createConnection();
-			Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
+   public void testForeignByteMessage() throws Exception
+   {
+      Connection c = null;
 
-			MessageProducer p = s.createProducer(queue1);
+      try
+      {
+         c = cf.createConnection();
+         Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
 
-			// create a Bytes foreign message
-			SimpleJMSBytesMessage bfm = new SimpleJMSBytesMessage();
+         MessageProducer p = s.createProducer(queue1);
 
-			p.send(bfm);
+         // create a Bytes foreign message
+         SimpleJMSBytesMessage bfm = new SimpleJMSBytesMessage();
 
-			MessageConsumer cons = s.createConsumer(queue1);
-			c.start();
+         p.send(bfm);
 
-			BytesMessage bm = (BytesMessage)cons.receive();
-			assertNotNull(bm);
-		}
-		finally
-		{
-			if (c != null)
-			{
-				c.close();
-			}
-		}
+         MessageConsumer cons = s.createConsumer(queue1);
+         c.start();
 
-	}
+         BytesMessage bm = (BytesMessage)cons.receive();
+         assertNotNull(bm);
+      }
+      finally
+      {
+         if (c != null)
+         {
+            c.close();
+         }
+      }
 
-	public void testJMSMessageIDChanged() throws Exception
-	{
-		Connection c = null;
+   }
 
-		try
-		{
+   public void testJMSMessageIDChanged() throws Exception
+   {
+      Connection c = null;
 
-			c= cf.createConnection();
-			Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
+      try
+      {
 
-			MessageProducer p = s.createProducer(queue1);
+         c = cf.createConnection();
+         Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
 
-			Message m = new SimpleJMSMessage();
-			m.setJMSMessageID("something");
+         MessageProducer p = s.createProducer(queue1);
 
-			p.send(m);
+         Message m = new SimpleJMSMessage();
+         m.setJMSMessageID("something");
 
-			assertFalse("something".equals(m.getJMSMessageID()));
+         p.send(m);
 
-			c.close();
-		}
-		finally
-		{
-			if (c != null)
-			{
-				c.close();
-			}
+         assertFalse("something".equals(m.getJMSMessageID()));
 
-			removeAllMessages(queue1.getQueueName(), true, 0);
-		}
-	}
+         c.close();
+      }
+      finally
+      {
+         if (c != null)
+         {
+            c.close();
+         }
 
-	/**
-	 * com.sun.ts.tests.jms.ee.all.queueconn.QueueConnTest line 171
-	 */
-	public void test_1() throws Exception
-	{
-		QueueConnection qc = null;
+         removeAllMessages(queue1.getQueueName(), true, 0);
+      }
+   }
 
-		try
-		{	      
-			qc = cf.createQueueConnection();
-			QueueSession qs = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
+   /**
+    * com.sun.ts.tests.jms.ee.all.queueconn.QueueConnTest line 171
+    */
+   public void test_1() throws Exception
+   {
+      QueueConnection qc = null;
 
-			QueueReceiver qreceiver = qs.createReceiver(queue1, "targetMessage = TRUE");
+      try
+      {
+         qc = cf.createQueueConnection();
+         QueueSession qs = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
 
-			qc.start();
+         QueueReceiver qreceiver = qs.createReceiver(queue1, "targetMessage = TRUE");
 
-			TextMessage m = qs.createTextMessage();
-			m.setText("one");
-			m.setBooleanProperty("targetMessage", false);
+         qc.start();
 
-			QueueSender qsender = qs.createSender(queue1);
+         TextMessage m = qs.createTextMessage();
+         m.setText("one");
+         m.setBooleanProperty("targetMessage", false);
 
-			qsender.send(m);
+         QueueSender qsender = qs.createSender(queue1);
 
-			m.setText("two");
-			m.setBooleanProperty("targetMessage", true);
+         qsender.send(m);
 
-			qsender.send(m);
+         m.setText("two");
+         m.setBooleanProperty("targetMessage", true);
 
-			TextMessage rm = (TextMessage)qreceiver.receive(1000);
+         qsender.send(m);
 
-			assertEquals("two", rm.getText());
-		}
-		finally
-		{
-			if (qc != null)
-			{
-				qc.close();      		
-			}
-			Thread.sleep(2000);
-			log.info("****** removing merssages");
-			removeAllMessages(queue1.getQueueName(), true, 0);
-			checkEmpty(queue1);
-		}
-	}
+         TextMessage rm = (TextMessage)qreceiver.receive(1000);
 
-	public void testInvalidSelectorOnDurableSubscription() throws Exception
-	{
-		Connection c = null;
+         assertEquals("two", rm.getText());
+      }
+      finally
+      {
+         if (qc != null)
+         {
+            qc.close();
+         }
+         Thread.sleep(2000);
+         log.info("****** removing merssages");
+         removeAllMessages(queue1.getQueueName(), true, 0);
+         checkEmpty(queue1);
+      }
+   }
 
-		try
-		{      
-			c = cf.createConnection();
-			c.setClientID("something");
+   public void testInvalidSelectorOnDurableSubscription() throws Exception
+   {
+      Connection c = null;
 
-			Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
+      try
+      {
+         c = cf.createConnection();
+         c.setClientID("something");
 
-			try
-			{
-				s.createDurableSubscriber(topic1, "somename", "=TEST 'test'", false);
-				fail("this should fail");
-			}
-			catch(InvalidSelectorException e)
-			{
-				// OK
-			}
-		}
-		finally
-		{
-			c.close();
-		}
-	}
+         Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
 
-	public void testInvalidSelectorOnSubscription() throws Exception
-	{
-		TopicConnection c = null;      
-		try
-		{
-			c = cf.createTopicConnection();
-			c.setClientID("something");
+         try
+         {
+            s.createDurableSubscriber(topic1, "somename", "=TEST 'test'", false);
+            fail("this should fail");
+         }
+         catch (InvalidSelectorException e)
+         {
+            // OK
+         }
+      }
+      finally
+      {
+         c.close();
+      }
+   }
 
-			TopicSession s = c.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
+   public void testInvalidSelectorOnSubscription() throws Exception
+   {
+      TopicConnection c = null;
+      try
+      {
+         c = cf.createTopicConnection();
+         c.setClientID("something");
 
-			try
-			{
-				s.createSubscriber(topic1, "=TEST 'test'", false);
-				fail("this should fail");
-			}
-			catch(InvalidSelectorException e)
-			{
-				// OK
-			}
-		}
-		finally
-		{
-			c.close();
-		}
-	}
-	
-	/* By default we send non persistent messages asynchronously for performance reasons
-	 * when running with strictTCK we send them synchronously
-	 */
-	public void testNonPersistentMessagesSentSynchronously() throws Exception
-	{
-		Connection c = null;
+         TopicSession s = c.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
 
-		try
-		{
-			c= cf.createConnection();
-			Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
+         try
+         {
+            s.createSubscriber(topic1, "=TEST 'test'", false);
+            fail("this should fail");
+         }
+         catch (InvalidSelectorException e)
+         {
+            // OK
+         }
+      }
+      finally
+      {
+         c.close();
+      }
+   }
 
-			MessageProducer p = s.createProducer(queue1);
-			
-			p.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
-			
-			final int numMessages = 100;
-			
-			this.assertRemainingMessages(0);
-			
-			for (int i = 0; i < numMessages; i++)
-			{
-				p.send(s.createMessage());
-			}	
-			
-			this.assertRemainingMessages(numMessages);					
-		}
-		finally
-		{
-			if (c != null)
-			{
-				c.close();
-			}
+   /* By default we send non persistent messages asynchronously for performance reasons
+    * when running with strictTCK we send them synchronously
+    */
+   public void testNonPersistentMessagesSentSynchronously() throws Exception
+   {
+      Connection c = null;
 
-			removeAllMessages(queue1.getQueueName(), true, 0);
-		}
-	}
+      try
+      {
+         c = cf.createConnection();
+         Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
 
-	protected void tearDown() throws Exception
-	{
-		super.tearDown();
-		undeployConnectionFactory(ORG_JBOSS_MESSAGING_SERVICE_LBCONNECTION_FACTORY);
-	}
+         MessageProducer p = s.createProducer(queue1);
 
-	// Package protected ---------------------------------------------
+         p.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
 
-	// Protected -----------------------------------------------------
+         final int numMessages = 100;
 
-	// Private -------------------------------------------------------
+         this.assertRemainingMessages(0);
 
-	// Inner classes -------------------------------------------------   
+         for (int i = 0; i < numMessages; i++)
+         {
+            p.send(s.createMessage());
+         }
+
+         this.assertRemainingMessages(numMessages);
+      }
+      finally
+      {
+         if (c != null)
+         {
+            c.close();
+         }
+
+         removeAllMessages(queue1.getQueueName(), true, 0);
+      }
+   }
+
+   protected void tearDown() throws Exception
+   {
+      super.tearDown();
+      undeployConnectionFactory(ORG_JBOSS_MESSAGING_SERVICE_LBCONNECTION_FACTORY);
+   }
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   // Inner classes -------------------------------------------------
 }

Modified: trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/JMSTestCase.java
===================================================================
--- trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/JMSTestCase.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/JMSTestCase.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -1,11 +1,11 @@
 package org.jboss.test.messaging.jms;
 
+import javax.naming.InitialContext;
+
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.jms.client.JBossConnectionFactory;
 import org.jboss.test.messaging.JBMServerTestCase;
 
-import javax.naming.InitialContext;
-
 /**
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
  * @version <tt>$Revision: $</tt>23 Jul 2007
@@ -27,31 +27,44 @@
 
    protected boolean startMessagingServer = true;
 
-
    protected void setUp() throws Exception
    {
       super.setUp();
-                        
+
       ic = getInitialContext();
 
-      //All jms tests should use a specific cg which has blockOnAcknowledge = true and
-      //both np and p messages are sent synchronously
-      
+      // All jms tests should use a specific cg which has blockOnAcknowledge = true and
+      // both np and p messages are sent synchronously
+
       getJmsServerManager().createConnectionFactory("testsuitecf",
-               new TransportConfiguration("org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory"), null, 5000, 5000,      
-               null, 1000, 1024 * 1024, -1, 1000, -1, true, true, true, false, "/testsuitecf");
-      
-      cf = (JBossConnectionFactory) getInitialContext().lookup("/testsuitecf");      
+                                                    new TransportConfiguration("org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory"),
+                                                    null,
+                                                    5000,
+                                                    5,
+                                                    5000,
+                                                    null,
+                                                    1000,
+                                                    1024 * 1024,
+                                                    -1,
+                                                    1000,
+                                                    -1,
+                                                    true,
+                                                    true,
+                                                    true,
+                                                    false,
+                                                    8,
+                                                    "/testsuitecf");
+
+      cf = (JBossConnectionFactory)getInitialContext().lookup("/testsuitecf");
    }
-   
+
    protected void tearDown() throws Exception
    {
-      super.tearDown();   
+      super.tearDown();
       getJmsServerManager().destroyConnectionFactory("testsuitecf");
       cf = null;
    }
 
-
    public JMSTestCase(String name)
    {
       super(name);

Modified: trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/QueueRequestorTest.java
===================================================================
--- trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/QueueRequestorTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/QueueRequestorTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,14 +21,10 @@
   */
 package org.jboss.test.messaging.jms;
 
-import javax.jms.Connection;
-import javax.jms.DeliveryMode;
 import javax.jms.Destination;
 import javax.jms.JMSException;
 import javax.jms.Message;
-import javax.jms.MessageConsumer;
 import javax.jms.MessageListener;
-import javax.jms.MessageProducer;
 import javax.jms.QueueConnection;
 import javax.jms.QueueReceiver;
 import javax.jms.QueueRequestor;

Modified: trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/ScheduledDeliveryTest.java
===================================================================
--- trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/ScheduledDeliveryTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/ScheduledDeliveryTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,8 +21,6 @@
  */
 package org.jboss.test.messaging.jms;
 
-import org.jboss.messaging.jms.client.JBossMessage;
-
 import javax.jms.Connection;
 import javax.jms.MessageConsumer;
 import javax.jms.MessageProducer;
@@ -30,7 +28,9 @@
 import javax.jms.Session;
 import javax.jms.TextMessage;
 
+import org.jboss.messaging.jms.client.JBossMessage;
 
+
 /**
  * 
  * A ScheduledDeliveryTest

Modified: trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/SecurityTest.java
===================================================================
--- trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/SecurityTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/SecurityTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,9 +21,9 @@
   */
 package org.jboss.test.messaging.jms;
 
-import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.security.Role;
-import org.jboss.test.messaging.tools.ServerManagement;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Set;
 
 import javax.jms.Connection;
 import javax.jms.ConnectionFactory;
@@ -36,10 +36,11 @@
 import javax.jms.Queue;
 import javax.jms.Session;
 import javax.jms.Topic;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Set;
 
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.security.Role;
+import org.jboss.test.messaging.tools.ServerManagement;
+
 /**
  * Test JMS Security.
  *

Modified: trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/XARecoveryTest.java
===================================================================
--- trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/XARecoveryTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/XARecoveryTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -33,11 +33,11 @@
 import javax.transaction.xa.XAResource;
 import javax.transaction.xa.Xid;
 
-import org.jboss.messaging.core.transaction.impl.XidImpl;
-
 import com.arjuna.ats.arjuna.common.Uid;
 import com.arjuna.ats.jta.xa.XidImple;
 
+import org.jboss.messaging.core.transaction.impl.XidImpl;
+
 /**
  * 
  * A XARecoveryTest

Modified: trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/XAResourceRecoveryTest.java
===================================================================
--- trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/XAResourceRecoveryTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/XAResourceRecoveryTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -26,14 +26,14 @@
 import javax.transaction.Transaction;
 import javax.transaction.TransactionManager;
 
+import com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionManagerImple;
+
 import org.jboss.messaging.jms.client.JBossConnectionFactory;
 import org.jboss.test.messaging.JBMServerTestCase;
 import org.jboss.test.messaging.tools.ServerManagement;
 import org.jboss.test.messaging.tools.container.ServiceContainer;
 import org.jboss.tm.TxUtils;
 
-import com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionManagerImple;
-
 /**
  * 
  * A XAResourceRecoveryTest

Modified: trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/XATest.java
===================================================================
--- trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/XATest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/XATest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -42,6 +42,8 @@
 import javax.transaction.xa.XAResource;
 import javax.transaction.xa.Xid;
 
+import com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionManagerImple;
+
 import org.jboss.messaging.core.client.impl.ClientSessionImpl;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.transaction.impl.XidImpl;
@@ -51,8 +53,6 @@
 import org.jboss.tm.TransactionManagerLocator;
 import org.jboss.tm.TxUtils;
 
-import com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionManagerImple;
-
 /**
  *
  * A XATestBase

Modified: trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/message/JMSXDeliveryCountTest.java
===================================================================
--- trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/message/JMSXDeliveryCountTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/message/JMSXDeliveryCountTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -38,11 +38,11 @@
 import javax.transaction.xa.XAResource;
 import javax.transaction.xa.Xid;
 
+import com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionManagerImple;
+
 import org.jboss.test.messaging.JBMServerTestCase;
 import org.jboss.test.messaging.tools.ServerManagement;
 
-import com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionManagerImple;
-
 /**
  * 
  * A JMSXDeliveryCountTest

Modified: trunk/tests/jms-tests/src/org/jboss/test/messaging/tools/container/LocalTestServer.java
===================================================================
--- trunk/tests/jms-tests/src/org/jboss/test/messaging/tools/container/LocalTestServer.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/jms-tests/src/org/jboss/test/messaging/tools/container/LocalTestServer.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,6 +21,26 @@
 */
 package org.jboss.test.messaging.tools.container;
 
+import java.io.File;
+import java.lang.management.ManagementFactory;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Properties;
+import java.util.Set;
+
+import javax.management.MBeanServerInvocationHandler;
+import javax.management.NotificationListener;
+import javax.management.ObjectName;
+import javax.naming.InitialContext;
+import javax.sql.DataSource;
+import javax.transaction.TransactionManager;
+import javax.transaction.UserTransaction;
+
 import org.jboss.kernel.spi.deployment.KernelDeployment;
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.logging.Logger;
@@ -41,25 +61,6 @@
 import org.jboss.test.messaging.tools.jboss.MBeanConfigurationElement;
 import org.jboss.tm.TransactionManagerLocator;
 
-import javax.management.MBeanServerInvocationHandler;
-import javax.management.NotificationListener;
-import javax.management.ObjectName;
-import javax.naming.InitialContext;
-import javax.sql.DataSource;
-import javax.transaction.TransactionManager;
-import javax.transaction.UserTransaction;
-import java.io.File;
-import java.lang.management.ManagementFactory;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Properties;
-import java.util.Set;
-
 /**
  * @author <a href="mailto:ovidiu at feodorov.com">Ovidiu Feodorov</a>
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
@@ -72,8 +73,11 @@
    // Constants ------------------------------------------------------------------------------------
 
    private static final Logger log = Logger.getLogger(LocalTestServer.class);
+
    private boolean started = false;
+
    private HashMap<String, List<String>> allBindings = new HashMap<String, List<String>>();
+
    // Static ---------------------------------------------------------------------------------------
 
    public static void setEnvironmentServerIndex(int serverIndex)
@@ -118,10 +122,7 @@
       return serverIndex;
    }
 
-
-   public synchronized void start(String[] containerConfig,
-                                  HashMap<String, Object> configuration,
-                                  boolean clearDatabase) throws Exception
+   public synchronized void start(String[] containerConfig, HashMap<String, Object> configuration, boolean clearDatabase) throws Exception
    {
       if (isStarted())
       {
@@ -129,10 +130,10 @@
       }
 
       log.info("** deleting database?" + clearDatabase);
-      
+
       if (clearDatabase)
       {
-         //Delete the BDB environment
+         // Delete the BDB environment
 
          File dir = new File("data");
 
@@ -144,9 +145,9 @@
       ConfigurationHelper.addServerConfig(getServerID(), configuration);
 
       JBMPropertyKernelConfig propertyKernelConfig = new JBMPropertyKernelConfig(System.getProperties());
-      //propertyKernelConfig.setServerID(getServerID());
+      // propertyKernelConfig.setServerID(getServerID());
       bootstrap = new JBMBootstrapServer(containerConfig, propertyKernelConfig);
-      System.setProperty(Constants.SERVER_INDEX_PROPERTY_NAME, ""+getServerID());
+      System.setProperty(Constants.SERVER_INDEX_PROPERTY_NAME, "" + getServerID());
       bootstrap.run();
       started = true;
 
@@ -170,7 +171,6 @@
       return directory.delete();
    }
 
-
    protected void deleteAllData() throws Exception
    {
       log.info("DELETING ALL DATA FROM DATABASE!");
@@ -181,7 +181,7 @@
       // further commands after one fails
 
       TransactionManager mgr = TransactionManagerLocator.locateTransactionManager();
-      DataSource ds = (DataSource) ctx.lookup("java:/DefaultDS");
+      DataSource ds = (DataSource)ctx.lookup("java:/DefaultDS");
 
       javax.transaction.Transaction txOld = mgr.suspend();
 
@@ -254,18 +254,16 @@
          }
       }
 
-
    }
 
    public synchronized boolean stop() throws Exception
    {
       bootstrap.shutDown();
-      started=false;
+      started = false;
       unbindAll();
       return true;
    }
 
-
    public void ping() throws Exception
    {
       if (!isStarted())
@@ -294,11 +292,11 @@
          }
          else
          {
-            throw new Exception (e.toString(), e);
+            throw new Exception(e.toString(), e);
          }
       }
    }
-   
+
    public KernelDeployment deployXML(String name, String xml) throws Exception
    {
       try
@@ -314,7 +312,7 @@
          }
          else
          {
-            throw new Exception (e.toString(), e);
+            throw new Exception(e.toString(), e);
          }
       }
    }
@@ -334,7 +332,7 @@
          }
          else
          {
-            throw new Exception (e.toString(), e);
+            throw new Exception(e.toString(), e);
          }
       }
    }
@@ -346,28 +344,24 @@
 
    public void setAttribute(ObjectName on, String name, String valueAsString) throws Exception
    {
-      //sc.setAttribute(on, name, valueAsString);
+      // sc.setAttribute(on, name, valueAsString);
    }
 
-   public Object invoke(ObjectName on, String operationName, Object[] params, String[] signature)
-           throws Exception
+   public Object invoke(ObjectName on, String operationName, Object[] params, String[] signature) throws Exception
    {
-      return null;//sc.invoke(on, operationName, params, signature);
+      return null;// sc.invoke(on, operationName, params, signature);
    }
 
-   public void addNotificationListener(ObjectName on, NotificationListener listener)
-           throws Exception
+   public void addNotificationListener(ObjectName on, NotificationListener listener) throws Exception
    {
       // sc.addNotificationListener(on, listener);
    }
 
-   public void removeNotificationListener(ObjectName on, NotificationListener listener)
-           throws Exception
+   public void removeNotificationListener(ObjectName on, NotificationListener listener) throws Exception
    {
-      //sc.removeNotificationListener(on, listener);
+      // sc.removeNotificationListener(on, listener);
    }
 
-
    public void log(int level, String text)
    {
       if (ServerManagement.FATAL == level)
@@ -407,10 +401,10 @@
    }
 
    public synchronized void startServerPeer(int serverPeerID,
-                               String defaultQueueJNDIContext,
-                               String defaultTopicJNDIContext,
-                               ServiceAttributeOverrides attrOverrides,
-                               boolean clustered) throws Exception
+                                            String defaultQueueJNDIContext,
+                                            String defaultTopicJNDIContext,
+                                            ServiceAttributeOverrides attrOverrides,
+                                            boolean clustered) throws Exception
    {
       System.setProperty(Constants.SERVER_INDEX_PROPERTY_NAME, "" + getServerID());
       getMessagingServer().start();
@@ -420,12 +414,11 @@
    {
       System.setProperty(Constants.SERVER_INDEX_PROPERTY_NAME, "" + getServerID());
       getMessagingServer().stop();
-      //also unbind everything
+      // also unbind everything
       unbindAll();
    }
 
-   private void unbindAll()
-           throws Exception
+   private void unbindAll() throws Exception
    {
       Collection<List<String>> bindings = allBindings.values();
       for (List<String> binding : bindings)
@@ -454,6 +447,7 @@
    {
       return getMessagingServer();
    }
+
    public void destroyQueue(String name, String jndiName) throws Exception
    {
       this.getJMSServerManager().destroyQueue(name);
@@ -474,22 +468,17 @@
       this.getJMSServerManager().createTopic(name, "/topic/" + (jndiName != null ? jndiName : name));
    }
 
-   public void deployConnectionFactory(String clientId, String objectName,
-                                       List<String> jndiBindings) throws Exception
+   public void deployConnectionFactory(String clientId, String objectName, List<String> jndiBindings) throws Exception
    {
       deployConnectionFactory(clientId, objectName, jndiBindings, -1, -1, -1, -1, false, false, -1, false);
    }
 
-   public void deployConnectionFactory(String objectName,
-                                       List<String> jndiBindings,
-                                       int consumerWindowSize) throws Exception
+   public void deployConnectionFactory(String objectName, List<String> jndiBindings, int consumerWindowSize) throws Exception
    {
       deployConnectionFactory(null, objectName, jndiBindings, consumerWindowSize, -1, -1, -1, false, false, -1, false);
    }
 
-
-   public void deployConnectionFactory(String objectName,
-                                       List<String> jndiBindings) throws Exception
+   public void deployConnectionFactory(String objectName, List<String> jndiBindings) throws Exception
    {
       deployConnectionFactory(null, objectName, jndiBindings, -1, -1, -1, -1, false, false, -1, false);
    }
@@ -501,16 +490,35 @@
                                        int defaultTempQueuePageSize,
                                        int defaultTempQueueDownCacheSize) throws Exception
    {
-      this.deployConnectionFactory(null, objectName, jndiBindings, prefetchSize, defaultTempQueueFullSize,
-              defaultTempQueuePageSize, defaultTempQueueDownCacheSize, false, false, -1, false);
+      this.deployConnectionFactory(null,
+                                   objectName,
+                                   jndiBindings,
+                                   prefetchSize,
+                                   defaultTempQueueFullSize,
+                                   defaultTempQueuePageSize,
+                                   defaultTempQueueDownCacheSize,
+                                   false,
+                                   false,
+                                   -1,
+                                   false);
    }
 
    public void deployConnectionFactory(String objectName,
                                        List<String> jndiBindings,
-                                       boolean supportsFailover, boolean supportsLoadBalancing) throws Exception
+                                       boolean supportsFailover,
+                                       boolean supportsLoadBalancing) throws Exception
    {
-      this.deployConnectionFactory(null, objectName, jndiBindings, -1, -1,
-              -1, -1, supportsFailover, supportsLoadBalancing, -1, false);
+      this.deployConnectionFactory(null,
+                                   objectName,
+                                   jndiBindings,
+                                   -1,
+                                   -1,
+                                   -1,
+                                   -1,
+                                   supportsFailover,
+                                   supportsLoadBalancing,
+                                   -1,
+                                   false);
    }
 
    public void deployConnectionFactory(String clientId,
@@ -521,18 +529,31 @@
                                        int defaultTempQueuePageSize,
                                        int defaultTempQueueDownCacheSize,
                                        boolean supportsFailover,
-                                       boolean supportsLoadBalancing,                                     
+                                       boolean supportsLoadBalancing,
                                        int dupsOkBatchSize,
                                        boolean blockOnAcknowledge) throws Exception
    {
       log.info("deploying connection factory with name: " + objectName + " and dupsok: " + dupsOkBatchSize);
       getJMSServerManager().createConnectionFactory(objectName,
-               new TransportConfiguration("org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory"), null, 5000, 5000,      
-               clientId, dupsOkBatchSize,
-      		prefetchSize, -1, 1000, -1, blockOnAcknowledge, true, true, false, jndiBindings);
+                                                    new TransportConfiguration("org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory"),
+                                                    null,
+                                                    5000,
+                                                    5,
+                                                    5000,
+                                                    clientId,
+                                                    dupsOkBatchSize,
+                                                    prefetchSize,
+                                                    -1,
+                                                    1000,
+                                                    -1,
+                                                    blockOnAcknowledge,
+                                                    true,
+                                                    true,
+                                                    false,
+                                                    8,
+                                                    jndiBindings);
    }
 
-
    public void undeployConnectionFactory(String objectName) throws Exception
    {
       getJMSServerManager().destroyConnectionFactory(objectName);
@@ -558,19 +579,18 @@
 
    public UserTransaction getUserTransaction() throws Exception
    {
-      //return sc.getUserTransaction();
+      // return sc.getUserTransaction();
       return null;
    }
 
    public List pollNotificationListener(long listenerID) throws Exception
    {
-      throw new IllegalStateException("Poll doesn't make sense on a local server. " +
-              "Register listeners directly instead.");
+      throw new IllegalStateException("Poll doesn't make sense on a local server. " + "Register listeners directly instead.");
    }
 
    public void flushManagedConnectionPool()
    {
-      //sc.flushManagedConnectionPool();
+      // sc.flushManagedConnectionPool();
    }
 
    // Public ---------------------------------------------------------------------------------------
@@ -585,27 +605,27 @@
    }
 
    protected void overrideServerPeerConfiguration(MBeanConfigurationElement config,
-                                                  int serverPeerID, String defaultQueueJNDIContext, String defaultTopicJNDIContext)
-           throws Exception
+                                                  int serverPeerID,
+                                                  String defaultQueueJNDIContext,
+                                                  String defaultTopicJNDIContext) throws Exception
    {
       config.setAttribute("ServerPeerID", Integer.toString(serverPeerID));
-      config.setAttribute("DefaultQueueJNDIContext",
-              defaultQueueJNDIContext == null ? "/queue" : defaultQueueJNDIContext);
-      config.setAttribute("DefaultTopicJNDIContext",
-              defaultTopicJNDIContext == null ? "/topic" : defaultTopicJNDIContext);
+      config.setAttribute("DefaultQueueJNDIContext", defaultQueueJNDIContext == null ? "/queue"
+                                                                                    : defaultQueueJNDIContext);
+      config.setAttribute("DefaultTopicJNDIContext", defaultTopicJNDIContext == null ? "/topic"
+                                                                                    : defaultTopicJNDIContext);
    }
 
    // Private --------------------------------------------------------------------------------------
 
-
    public MessagingServer getMessagingServer()
    {
-      return (MessagingServer) bootstrap.getKernel().getRegistry().getEntry("MessagingServer").getTarget();
+      return (MessagingServer)bootstrap.getKernel().getRegistry().getEntry("MessagingServer").getTarget();
    }
 
    public JMSServerManager getJMSServerManager()
    {
-      return (JMSServerManager) bootstrap.getKernel().getRegistry().getEntry("JMSServerManager").getTarget();
+      return (JMSServerManager)bootstrap.getKernel().getRegistry().getEntry("JMSServerManager").getTarget();
    }
 
    public void addQueueSettings(String name, long redeliveryDelay)
@@ -625,9 +645,10 @@
    public InitialContext getInitialContext() throws Exception
    {
       Properties props = new Properties();
-      props.setProperty("java.naming.factory.initial", "org.jboss.test.messaging.tools.container.InVMInitialContextFactory");
+      props.setProperty("java.naming.factory.initial",
+                        "org.jboss.test.messaging.tools.container.InVMInitialContextFactory");
       props.setProperty(Constants.SERVER_INDEX_PROPERTY_NAME, "" + getServerID());
-      //props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
+      // props.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
       return new InitialContext(props);
    }
 
@@ -646,21 +667,22 @@
          }
          catch (InterruptedException e)
          {
-            //e.printStackTrace();
+            // e.printStackTrace();
          }
       }
 
    }
 
-
    public Integer getMessageCountForQueue(String queueName) throws Exception
    {
       ObjectName objectName = JMSManagementServiceImpl.getJMSQueueObjectName(queueName);
-      JMSQueueControlMBean queue = (JMSQueueControlMBean)getMessagingServer().getManagementService().getResource(objectName);
+      JMSQueueControlMBean queue = (JMSQueueControlMBean)getMessagingServer().getManagementService()
+                                                                             .getResource(objectName);
       if (queue != null)
       {
          return queue.getMessageCount();
-      } else
+      }
+      else
       {
          return -1;
       }
@@ -678,12 +700,13 @@
    public List<SubscriptionInfo> listAllSubscribersForTopic(String s) throws Exception
    {
       ObjectName objectName = JMSManagementServiceImpl.getJMSTopicObjectName(s);
-      TopicControlMBean topic = (TopicControlMBean) MBeanServerInvocationHandler.newProxyInstance(
-            ManagementFactory.getPlatformMBeanServer(), objectName, TopicControlMBean.class, false);
+      TopicControlMBean topic = (TopicControlMBean)MBeanServerInvocationHandler.newProxyInstance(ManagementFactory.getPlatformMBeanServer(),
+                                                                                                 objectName,
+                                                                                                 TopicControlMBean.class,
+                                                                                                 false);
       return Arrays.asList(topic.listAllSubscriptionInfos());
    }
 
-
    public Set<Role> getSecurityConfig() throws Exception
    {
       return getMessagingServer().getSecurityRepository().getMatch("*");
@@ -692,7 +715,7 @@
    public void setSecurityConfig(Set<Role> defConfig) throws Exception
    {
       getMessagingServer().getSecurityRepository().removeMatch("*");
-      getMessagingServer().getSecurityRepository().addMatch("*", defConfig);      
+      getMessagingServer().getSecurityRepository().addMatch("*", defConfig);
    }
 
    public void setRedeliveryDelayOnDestination(String dest, boolean queue, long delay) throws Exception
@@ -700,11 +723,10 @@
       SimpleString condition = new SimpleString((queue ? "queuejms." : "topicjms.") + dest);
       QueueSettings queueSettings = new QueueSettings();
       queueSettings.setRedeliveryDelay(delay);
-      //FIXME we need to expose queue attributes in another way
-//      getMessagingServer().getServerManagement().setQueueAttributes(condition, queueSettings);
+      // FIXME we need to expose queue attributes in another way
+      // getMessagingServer().getServerManagement().setQueueAttributes(condition, queueSettings);
    }
 
-
    // Inner classes --------------------------------------------------------------------------------
 
 }

Modified: trunk/tests/jms-tests/src/org/jboss/test/messaging/tools/container/RMITestServer.java
===================================================================
--- trunk/tests/jms-tests/src/org/jboss/test/messaging/tools/container/RMITestServer.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/jms-tests/src/org/jboss/test/messaging/tools/container/RMITestServer.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,22 +21,6 @@
   */
 package org.jboss.test.messaging.tools.container;
 
-import org.jboss.kernel.spi.deployment.KernelDeployment;
-import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.security.Role;
-import org.jboss.messaging.core.server.MessagingServer;
-import org.jboss.messaging.jms.JBossDestination;
-import org.jboss.messaging.jms.server.JMSServerManager;
-import org.jboss.messaging.jms.server.management.JMSQueueControlMBean;
-import org.jboss.messaging.jms.server.management.SubscriptionInfo;
-import org.jboss.messaging.jms.server.management.TopicControlMBean;
-import org.jboss.messaging.jms.server.management.impl.JMSManagementServiceImpl;
-
-import javax.management.MBeanServerInvocationHandler;
-import javax.management.NotificationListener;
-import javax.management.ObjectName;
-import javax.naming.InitialContext;
-import javax.transaction.UserTransaction;
 import java.lang.management.ManagementFactory;
 import java.rmi.registry.LocateRegistry;
 import java.rmi.registry.Registry;
@@ -49,6 +33,23 @@
 import java.util.Map;
 import java.util.Set;
 
+import javax.management.MBeanServerInvocationHandler;
+import javax.management.NotificationListener;
+import javax.management.ObjectName;
+import javax.naming.InitialContext;
+import javax.transaction.UserTransaction;
+
+import org.jboss.kernel.spi.deployment.KernelDeployment;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.security.Role;
+import org.jboss.messaging.core.server.MessagingServer;
+import org.jboss.messaging.jms.JBossDestination;
+import org.jboss.messaging.jms.server.JMSServerManager;
+import org.jboss.messaging.jms.server.management.JMSQueueControlMBean;
+import org.jboss.messaging.jms.server.management.SubscriptionInfo;
+import org.jboss.messaging.jms.server.management.TopicControlMBean;
+import org.jboss.messaging.jms.server.management.impl.JMSManagementServiceImpl;
+
 /**
  * An RMI wrapper to access the ServiceContainer from a different address space.
  *

Modified: trunk/tests/jms-tests/src/org/jboss/test/messaging/tools/container/Server.java
===================================================================
--- trunk/tests/jms-tests/src/org/jboss/test/messaging/tools/container/Server.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/jms-tests/src/org/jboss/test/messaging/tools/container/Server.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,6 +21,16 @@
 */
 package org.jboss.test.messaging.tools.container;
 
+import java.rmi.Remote;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Set;
+
+import javax.management.NotificationListener;
+import javax.management.ObjectName;
+import javax.naming.InitialContext;
+import javax.transaction.UserTransaction;
+
 import org.jboss.kernel.spi.deployment.KernelDeployment;
 import org.jboss.messaging.core.security.Role;
 import org.jboss.messaging.core.server.MessagingServer;
@@ -28,15 +38,6 @@
 import org.jboss.messaging.jms.server.JMSServerManager;
 import org.jboss.messaging.jms.server.management.SubscriptionInfo;
 
-import javax.management.NotificationListener;
-import javax.management.ObjectName;
-import javax.naming.InitialContext;
-import javax.transaction.UserTransaction;
-import java.rmi.Remote;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Set;
-
 /**
  * The remote interface exposed by TestServer.
  *

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/basic/AutoGroupClientTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/basic/AutoGroupClientTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/basic/AutoGroupClientTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,8 +21,16 @@
  */
 package org.jboss.messaging.tests.integration.basic;
 
+import java.util.concurrent.CountDownLatch;
+
 import junit.framework.TestCase;
-import org.jboss.messaging.core.client.*;
+
+import org.jboss.messaging.core.client.ClientConsumer;
+import org.jboss.messaging.core.client.ClientMessage;
+import org.jboss.messaging.core.client.ClientProducer;
+import org.jboss.messaging.core.client.ClientSession;
+import org.jboss.messaging.core.client.ClientSessionFactory;
+import org.jboss.messaging.core.client.MessageHandler;
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.Configuration;
 import org.jboss.messaging.core.config.TransportConfiguration;
@@ -35,8 +43,6 @@
 import org.jboss.messaging.jms.client.JBossTextMessage;
 import org.jboss.messaging.util.SimpleString;
 
-import java.util.concurrent.CountDownLatch;
-
 /**
  * @author <a href="mailto:andy.taylor at jboss.org">Andy Taylor</a>
  */

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/ClientCrashTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/ClientCrashTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/ClientCrashTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,6 +22,17 @@
 
 package org.jboss.messaging.tests.integration.clientcrash;
 
+import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP_ID;
+import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE;
+import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND;
+import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_PERSISTENT_SEND;
+import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE;
+import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_CONSUMER_WINDOW_SIZE;
+import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS;
+import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_PING_POOL_SIZE;
+import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE;
+import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_PRODUCER_WINDOW_SIZE;
+import static org.jboss.messaging.core.config.impl.ConfigurationImpl.DEFAULT_CALL_TIMEOUT;
 import junit.framework.TestCase;
 
 import org.jboss.messaging.core.client.ClientConsumer;
@@ -34,7 +45,6 @@
 import org.jboss.messaging.core.config.impl.ConfigurationImpl;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.message.Message;
-import org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory;
 import org.jboss.messaging.core.server.MessagingService;
 import org.jboss.messaging.core.server.impl.MessagingServiceImpl;
 import org.jboss.messaging.jms.client.JBossTextMessage;
@@ -144,9 +154,20 @@
       messagingService = MessagingServiceImpl.newNullStorageMessagingServer(config);
       messagingService.start();
 
-      sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory"));
-      sf.setPingPeriod(2000);
-      
+      sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory"),
+           null,
+           2000,
+           DEFAULT_PING_POOL_SIZE,
+           DEFAULT_CALL_TIMEOUT,
+           DEFAULT_CONSUMER_WINDOW_SIZE,
+           DEFAULT_CONSUMER_MAX_RATE,
+           DEFAULT_PRODUCER_WINDOW_SIZE,
+           DEFAULT_PRODUCER_MAX_RATE,
+           DEFAULT_BLOCK_ON_ACKNOWLEDGE,
+           DEFAULT_BLOCK_ON_PERSISTENT_SEND,
+           DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
+           DEFAULT_AUTO_GROUP_ID,
+           DEFAULT_MAX_CONNECTIONS);
    }
 
    @Override

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/ClientExitTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/ClientExitTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/ClientExitTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -32,7 +32,6 @@
 import org.jboss.messaging.core.config.impl.ConfigurationImpl;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.message.Message;
-import org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory;
 import org.jboss.messaging.core.server.MessagingService;
 import org.jboss.messaging.core.server.impl.MessagingServiceImpl;
 import org.jboss.messaging.tests.util.SpawnedVMSupport;

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/GracefulClient.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/GracefulClient.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/GracefulClient.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -32,7 +32,6 @@
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory;
 import org.jboss.messaging.jms.client.JBossTextMessage;
 
 /**

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/MultiThreadRandomFailoverTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/MultiThreadRandomFailoverTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/MultiThreadRandomFailoverTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -12,7 +12,19 @@
 
 package org.jboss.messaging.tests.integration.cluster;
 
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.Timer;
+import java.util.TimerTask;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
 import junit.framework.TestCase;
+
 import org.jboss.messaging.core.client.ClientConsumer;
 import org.jboss.messaging.core.client.ClientMessage;
 import org.jboss.messaging.core.client.ClientProducer;
@@ -20,13 +32,13 @@
 import org.jboss.messaging.core.client.ClientSessionFactory;
 import org.jboss.messaging.core.client.MessageHandler;
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
+import org.jboss.messaging.core.client.impl.ClientSessionFactoryInternal;
 import org.jboss.messaging.core.client.impl.ClientSessionImpl;
 import org.jboss.messaging.core.config.Configuration;
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.config.impl.ConfigurationImpl;
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.remoting.impl.ConnectionRegistryImpl;
 import org.jboss.messaging.core.remoting.impl.RemotingConnectionImpl;
 import org.jboss.messaging.core.remoting.impl.invm.InVMRegistry;
 import org.jboss.messaging.core.remoting.impl.invm.TransportConstants;
@@ -35,17 +47,6 @@
 import org.jboss.messaging.jms.client.JBossTextMessage;
 import org.jboss.messaging.util.SimpleString;
 
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.Timer;
-import java.util.TimerTask;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
 /**
  * A MultiThreadRandomFailoverTest
  * 
@@ -287,7 +288,10 @@
       {
          boolean ok = handler.latch.await(5000, TimeUnit.MILLISECONDS);
 
-         assertTrue("Didn't receive all messages", ok);
+         if (!ok)
+         {
+            throw new Exception("Timed out waiting for messages on handler " + System.identityHashCode(handler) + " threadnum " + threadNum);
+         }
 
          if (handler.failure != null)
          {
@@ -369,7 +373,10 @@
       {
          boolean ok = handler.latch.await(10000, TimeUnit.MILLISECONDS);
 
-         assertTrue(ok);
+         if (!ok)
+         {
+            throw new Exception("Timed out waiting for messages on handler " + System.identityHashCode(handler) + " threadnum " + threadNum);
+         }
 
          if (handler.failure != null)
          {
@@ -456,7 +463,10 @@
       {
          boolean ok = handler.latch.await(10000, TimeUnit.MILLISECONDS);
 
-         assertTrue(ok);
+         if (!ok)
+         {
+            throw new Exception("Timed out waiting for messages on handler " + System.identityHashCode(handler) + " threadnum " + threadNum);
+         }
 
          if (handler.failure != null)
          {
@@ -528,24 +538,25 @@
 
          sessions.add(sessConsume);
       }
+      
+      ClientSession sessSend = sf.createSession(false, false, false, false);
 
-      ClientSession sessSend = sf.createSession(false, true, true, false);
-
       ClientProducer producer = sessSend.createProducer(ADDRESS);
 
       sendMessages(sessSend, producer, numMessages, threadNum);
 
       sessSend.rollback();
-
+      
       sendMessages(sessSend, producer, numMessages, threadNum);
-
+      
       sessSend.commit();
+      
 
       for (ClientSession session : sessions)
       {
          session.start();
       }
-
+       
       Set<MyHandler> handlers = new HashSet<MyHandler>();
 
       for (ClientConsumer consumer : consumers)
@@ -561,16 +572,30 @@
       {
          boolean ok = handler.latch.await(10000, TimeUnit.MILLISECONDS);
 
-         assertTrue(ok);
+         if (!ok)
+         {
+            throw new Exception("Timed out waiting for messages on handler " + System.identityHashCode(handler) + " threadnum " + threadNum);
+         }
 
          if (handler.failure != null)
          {
             throw new Exception("Handler failed: " + handler.failure);
          }
       }
-
+      
       handlers.clear();
+      
+      // Set handlers to null
+      for (ClientConsumer consumer : consumers)
+      {
+         consumer.setMessageHandler(null);
+      }
 
+      for (ClientSession session : sessions)
+      {
+         session.rollback();
+      }
+      
       // New handlers
       for (ClientConsumer consumer : consumers)
       {
@@ -580,24 +605,27 @@
 
          handlers.add(handler);
       }
-
-      for (ClientSession session : sessions)
-      {
-         session.rollback();
-      }
-
+      
       for (MyHandler handler : handlers)
       {
          boolean ok = handler.latch.await(10000, TimeUnit.MILLISECONDS);
 
-         assertTrue(ok);
+         if (!ok)
+         {
+            throw new Exception("Timed out waiting for messages on handler " + System.identityHashCode(handler) + " threadnum " + threadNum);
+         }
+         
+         if (handler.failure != null)
+         {
+            throw new Exception("Handler failed on rollback: " + handler.failure);
+         }
       }
-
+        
       for (ClientSession session : sessions)
       {
          session.commit();
       }
-
+      
       sessSend.close();
       for (ClientSession session : sessions)
       {
@@ -656,7 +684,7 @@
 
       sendMessages(sessSend, producer, numMessages, threadNum);
 
-      consumeMessages(consumers, numMessages);
+      consumeMessages(consumers, numMessages, threadNum);
 
       sessSend.close();
       for (ClientSession session : sessions)
@@ -717,7 +745,7 @@
          session.start();
       }
 
-      consumeMessages(consumers, numMessages);
+      consumeMessages(consumers, numMessages, threadNum);
 
       sessSend.close();
       for (ClientSession session : sessions)
@@ -781,14 +809,14 @@
 
       sessSend.commit();
 
-      consumeMessages(consumers, numMessages);
+      consumeMessages(consumers, numMessages, threadNum);
 
       for (ClientSession session : sessions)
       {
          session.rollback();
       }
 
-      consumeMessages(consumers, numMessages);
+      consumeMessages(consumers, numMessages, threadNum);
 
       for (ClientSession session : sessions)
       {
@@ -860,14 +888,14 @@
          session.start();
       }
 
-      consumeMessages(consumers, numMessages);
+      consumeMessages(consumers, numMessages, threadNum);
 
       for (ClientSession session : sessions)
       {
          session.rollback();
       }
 
-      consumeMessages(consumers, numMessages);
+      consumeMessages(consumers, numMessages, threadNum);
 
       for (ClientSession session : sessions)
       {
@@ -1166,7 +1194,7 @@
 
    protected int getNumIterations()
    {
-      return 10;
+      return 20;
    }
 
    protected void setUp() throws Exception
@@ -1206,9 +1234,9 @@
          log.info("************ ITERATION: " + its);
          start();
 
-         final ClientSessionFactoryImpl sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
-                                                                          new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
-                                                                                                     backupParams));
+         final ClientSessionFactoryInternal sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
+                                                                              new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
+                                                                                                         backupParams));
 
          ClientSession session = sf.createSession(false, false, false, false);
 
@@ -1270,8 +1298,12 @@
 
          session.close();
 
-         assertEquals(0, sf.getSessionCount());
+         assertEquals(0, sf.numSessions());
 
+         assertEquals(0, sf.numConnections());
+
+         assertEquals(0, sf.numBackupConnections());
+
          stop();
       }
    }
@@ -1315,10 +1347,6 @@
 
    private void stop() throws Exception
    {
-      ConnectionRegistryImpl.instance.dump();
-
-      assertEquals(0, ConnectionRegistryImpl.instance.size());
-
       assertEquals(0, backupService.getServer().getRemotingService().getConnections().size());
 
       backupService.stop();
@@ -1349,7 +1377,7 @@
       }
    }
 
-   private void consumeMessages(final Set<ClientConsumer> consumers, final int numMessages) throws Exception
+   private void consumeMessages(final Set<ClientConsumer> consumers, final int numMessages, final int threadNum) throws Exception
    {
       // We make sure the messages arrive in the order they were sent from a particular producer
       Map<ClientConsumer, Map<Integer, Integer>> counts = new HashMap<ClientConsumer, Map<Integer, Integer>>();
@@ -1372,6 +1400,8 @@
 
             int tn = (Integer)msg.getProperty(new SimpleString("threadnum"));
             int cnt = (Integer)msg.getProperty(new SimpleString("count"));
+            
+           // log.info("Got message " + tn + ":" + cnt);
 
             Integer c = consumerCounts.get(tn);
             if (c == null)
@@ -1379,9 +1409,9 @@
                c = new Integer(cnt);
             }
 
-            if (cnt != c.intValue())
+            if (tn == threadNum && cnt != c.intValue())
             {
-               throw new Exception("Invalid count, expected " + c + " got " + cnt);
+               throw new Exception("Invalid count, expected " + tn + ": " + c + " got " + cnt);
             }
 
             c++;
@@ -1506,11 +1536,11 @@
             c = new Integer(cnt);
          }
 
-         // log.info("got message " + threadNum + "-" + cnt);
-
-         if (cnt != c.intValue())
+         //log.info(System.identityHashCode(this) + " consumed message " + threadNum + ":" + cnt);
+         
+         if (tn == threadNum && cnt != c.intValue())
          {
-            failure = "Invalid count, expected " + c + " got " + cnt;
+            failure = "Invalid count, expected " + threadNum + ":" + c + " got " + cnt;            
             log.error(failure);
 
             latch.countDown();
@@ -1523,8 +1553,8 @@
          }
 
          c++;
-         // Wrap around at 100
-         if (c == 100)
+         // Wrap around at numMessages
+         if (c == numMessages)
          {
             c = 0;
          }

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/RandomFailoverTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/RandomFailoverTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/RandomFailoverTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -30,14 +30,12 @@
 import org.jboss.messaging.core.client.ClientSessionFactory;
 import org.jboss.messaging.core.client.MessageHandler;
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
-import org.jboss.messaging.core.client.impl.ClientSessionImpl;
+import org.jboss.messaging.core.client.impl.ClientSessionInternal;
 import org.jboss.messaging.core.config.Configuration;
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.config.impl.ConfigurationImpl;
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.remoting.impl.ConnectionRegistryImpl;
-import org.jboss.messaging.core.remoting.impl.RemotingConnectionImpl;
 import org.jboss.messaging.core.remoting.impl.invm.InVMRegistry;
 import org.jboss.messaging.core.remoting.impl.invm.TransportConstants;
 import org.jboss.messaging.core.server.MessagingService;
@@ -52,11 +50,11 @@
  */
 public class RandomFailoverTest extends TestCase
 {
-   private static final Logger log = Logger.getLogger(SimpleAutomaticFailoverTest.class);
+   private static final Logger log = Logger.getLogger(RandomFailoverTest.class);
 
    // Constants -----------------------------------------------------
 
-   private static final int RECEIVE_TIMEOUT = 5000;
+   private static final int RECEIVE_TIMEOUT = 10000;
 
    // Attributes ----------------------------------------------------
 
@@ -204,10 +202,21 @@
       {
          public void run(final ClientSessionFactory sf) throws Exception
          {
-            doTestK(sf);
+            doTestL(sf);
          }
       });
    }
+   
+   public void testN() throws Exception
+   {
+      runTest(new RunnableT()
+      {
+         public void run(final ClientSessionFactory sf) throws Exception
+         {
+            doTestN(sf);
+         }
+      });
+   }
 
    public void runTest(final RunnableT runnable) throws Exception
    {
@@ -225,6 +234,7 @@
 
          Failer failer = startFailer(1000, session);
 
+         log.info("***************Iteration: " + its);
          do
          {
             runnable.run(sf);
@@ -233,7 +243,11 @@
 
          session.close();
 
-         assertEquals(0, sf.getSessionCount());
+         assertEquals(0, sf.numSessions());
+         
+         assertEquals(0, sf.numConnections());
+         
+         assertEquals(0, sf.numBackupConnections());
 
          stop();
       }
@@ -246,12 +260,14 @@
    protected void doTestA(final ClientSessionFactory sf) throws Exception
    {
       long start = System.currentTimeMillis();
+      
+      log.info("starting================");
 
       ClientSession s = sf.createSession(false, false, false, false);
 
       final int numMessages = 100;
 
-      final int numSessions = 50;
+      final int numSessions = 10;
 
       Set<ClientConsumer> consumers = new HashSet<ClientConsumer>();
       Set<ClientSession> sessions = new HashSet<ClientSession>();
@@ -340,11 +356,13 @@
          assertTrue("Didn't receive all messages", ok);
       }
 
+      log.info("*** closing sessions");
       sessSend.close();
       for (ClientSession session : sessions)
       {
          session.close();
       }
+      log.info("*** closed sessions");
 
       for (int i = 0; i < numSessions; i++)
       {
@@ -886,7 +904,7 @@
 
       Set<ClientConsumer> consumers = new HashSet<ClientConsumer>();
       Set<ClientSession> sessions = new HashSet<ClientSession>();
-
+      
       for (int i = 0; i < numSessions; i++)
       {
          SimpleString subName = new SimpleString("sub" + i);
@@ -917,18 +935,23 @@
          message.getBody().flip();
          producer.send(message);
       }
-
+      
       for (ClientSession session : sessions)
       {
          session.start();
       }
-
+      
       for (int i = 0; i < numMessages; i++)
       {
          for (ClientConsumer consumer : consumers)
          {
             ClientMessage msg = consumer.receive(RECEIVE_TIMEOUT);
 
+            if (msg == null)
+            {
+               throw new IllegalStateException("Failed to receive message " + i);
+            }
+            
             assertNotNull(msg);
 
             assertEquals(i, msg.getProperty(new SimpleString("count")));
@@ -961,6 +984,8 @@
       }
 
       s.close();
+      
+      assertEquals(1, ((ClientSessionFactoryImpl)sf).numSessions());
 
       long end = System.currentTimeMillis();
 
@@ -1028,6 +1053,8 @@
       }
 
       sessSend.commit();
+      
+      log.info("sent and committed");
 
       for (int i = 0; i < numMessages; i++)
       {
@@ -1355,16 +1382,64 @@
       s.close();
    }
    
+
+   protected void doTestN(final ClientSessionFactory sf) throws Exception
+   {
+      ClientSession sessCreate = sf.createSession(false, true, true, false);
+
+      sessCreate.createQueue(ADDRESS, new SimpleString(ADDRESS.toString()), null, false, false);
+
+      ClientSession sess = sf.createSession(false, true, true, false);
+
+      sess.stop();
+
+      sess.start();
+
+      sess.stop();
+
+      ClientConsumer consumer = sess.createConsumer(new SimpleString(ADDRESS.toString()));
+
+      ClientProducer producer = sess.createProducer(ADDRESS);
+
+      ClientMessage message = sess.createClientMessage(JBossTextMessage.TYPE,
+                                                       false,
+                                                       0,
+                                                       System.currentTimeMillis(),
+                                                       (byte)1);
+      message.getBody().flip();
+
+      producer.send(message);
+
+      sess.start();
+
+      ClientMessage message2 = consumer.receive(RECEIVE_TIMEOUT);
+
+      assertNotNull(message2);
+
+      message2.acknowledge();
+
+      sess.stop();
+
+      sess.start();
+
+      sess.close();
+
+      sessCreate.deleteQueue(new SimpleString(ADDRESS.toString()));
+
+      sessCreate.close();
+   }
+   
    protected int getNumIterations()
    {
-      return 10;
+      return 20;
    }
    
    protected void setUp() throws Exception
    {
       super.setUp();
       
-      timer = new Timer();
+      log.info("*********** created timer");
+      timer = new Timer(true);
       
       log.info("************ Starting test " + this.getName());
    }
@@ -1382,7 +1457,7 @@
    
    private Failer startFailer(final long time, final ClientSession session)
    {
-      Failer failer = new Failer(session);
+      Failer failer = new Failer((ClientSessionInternal)session);
 
       timer.schedule(failer, (long)(time * Math.random()), 100);
       
@@ -1419,12 +1494,6 @@
 
    private void stop() throws Exception
    {
-      ConnectionRegistryImpl.instance.dump();
-
-      assertEquals(0, ConnectionRegistryImpl.instance.size());
-
-      // ConnectionRegistryImpl.instance.clear();
-
       assertEquals(0, backupService.getServer().getRemotingService().getConnections().size());
 
       backupService.stop();
@@ -1439,24 +1508,22 @@
    // Inner classes -------------------------------------------------
    
    class Failer extends TimerTask
-   {
-      private final ClientSession session;
+   { 
+      private final ClientSessionInternal session;
 
       private boolean executed;
 
-      public Failer(final ClientSession session)
-      {
+      public Failer(final ClientSessionInternal session)
+      {     
          this.session = session;
       }
 
       public synchronized void run()
       {
          log.info("** Failing connection");
-
-         RemotingConnectionImpl conn = (RemotingConnectionImpl)((ClientSessionImpl)session).getConnection();
-
-         conn.fail(new MessagingException(MessagingException.NOT_CONNECTED, "blah"));
-
+ 
+         session.getConnection().fail(new MessagingException(MessagingException.NOT_CONNECTED, "oops"));
+         
          log.info("** Fail complete");
 
          cancel();

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/SimpleAutomaticFailoverTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/SimpleAutomaticFailoverTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/SimpleAutomaticFailoverTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -37,6 +37,7 @@
 import org.jboss.messaging.core.client.ClientSession;
 import org.jboss.messaging.core.client.ClientSessionFactory;
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
+import org.jboss.messaging.core.client.impl.ClientSessionFactoryInternal;
 import org.jboss.messaging.core.client.impl.ClientSessionImpl;
 import org.jboss.messaging.core.config.Configuration;
 import org.jboss.messaging.core.config.TransportConfiguration;
@@ -45,8 +46,6 @@
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.FailureListener;
 import org.jboss.messaging.core.remoting.RemotingConnection;
-import org.jboss.messaging.core.remoting.impl.ConnectionRegistryImpl;
-import org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory;
 import org.jboss.messaging.core.remoting.impl.invm.InVMRegistry;
 import org.jboss.messaging.core.remoting.impl.invm.TransportConstants;
 import org.jboss.messaging.core.server.MessagingService;
@@ -94,7 +93,7 @@
       ClientProducer producer = session.createProducer(ADDRESS);
 
       final int numMessages = 100;
-      
+
       log.info("Sending messages");
 
       for (int i = 0; i < numMessages; i++)
@@ -109,7 +108,7 @@
          message.getBody().flip();
          producer.send(message);
       }
-      
+
       log.info("sent messages");
 
       ClientConsumer consumer = session.createConsumer(ADDRESS);
@@ -128,18 +127,18 @@
          message2.acknowledge();
       }
 
-      //ClientMessage message3 = consumer.receive(250);
+      // ClientMessage message3 = consumer.receive(250);
 
-      //assertNull(message3);
+      // assertNull(message3);
 
       session.close();
    }
 
    public void testFailoverSameConnectionFactory() throws Exception
    {
-      ClientSessionFactory sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
-                                                             new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
-                                                                                        backupParams));
+      ClientSessionFactoryInternal sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
+                                                                     new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
+                                                                                                backupParams));
 
       ClientSession session = sf.createSession(false, true, true, false);
 
@@ -162,10 +161,10 @@
          producer.send(message);
       }
 
-      RemotingConnection conn = ((ClientSessionImpl)session).getConnection();
+      RemotingConnection conn1 = ((ClientSessionImpl)session).getConnection();
 
       // Simulate failure on connection
-      conn.fail(new MessagingException(MessagingException.NOT_CONNECTED));
+      conn1.fail(new MessagingException(MessagingException.NOT_CONNECTED));
 
       ClientConsumer consumer = session.createConsumer(ADDRESS);
 
@@ -206,13 +205,19 @@
       session.close();
 
       assertNull(message3);
+
+      assertEquals(0, sf.numSessions());
+
+      assertEquals(0, sf.numConnections());
+      
+      assertEquals(0, sf.numBackupConnections());
    }
 
    public void testFailoverChangeConnectionFactory() throws Exception
    {
-      ClientSessionFactory sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
-                                                             new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
-                                                                                        backupParams));
+      ClientSessionFactoryInternal sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
+                                                                     new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
+                                                                                                backupParams));
 
       ClientSession session = sf.createSession(false, true, true, false);
 
@@ -282,13 +287,19 @@
       assertNull(message3);
 
       session.close();
+
+      assertEquals(0, sf.numSessions());
+
+      assertEquals(0, sf.numConnections());
+      
+      assertEquals(0, sf.numBackupConnections());
    }
 
    public void testNoMessagesLeftAfterFailoverNewSession() throws Exception
    {
-      ClientSessionFactory sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
-                                                             new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
-                                                                                        backupParams));
+      ClientSessionFactoryInternal sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
+                                                                     new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
+                                                                                                backupParams));
 
       ClientSession session = sf.createSession(false, true, true, false);
 
@@ -345,13 +356,19 @@
       assertNull(message3);
 
       session.close();
+
+      assertEquals(0, sf.numSessions());
+
+      assertEquals(0, sf.numConnections());
+      
+      assertEquals(0, sf.numBackupConnections());
    }
 
    public void testCreateMoreSessionsAfterFailover() throws Exception
    {
-      ClientSessionFactory sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
-                                                             new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
-                                                                                        backupParams));
+      ClientSessionFactoryInternal sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
+                                                                     new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
+                                                                                                backupParams));
 
       ClientSession session = sf.createSession(false, true, true, false);
 
@@ -410,13 +427,19 @@
       session2.close();
 
       session3.close();
+
+      assertEquals(0, sf.numSessions());
+
+      assertEquals(0, sf.numConnections());
+      
+      assertEquals(0, sf.numBackupConnections());
    }
 
    public void testFailureListenerCalledOnFailure() throws Exception
    {
-      ClientSessionFactory sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
-                                                             new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
-                                                                                        backupParams));
+      ClientSessionFactoryInternal sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
+                                                                     new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
+                                                                                                backupParams));
 
       ClientSession session = sf.createSession(false, true, true, false);
 
@@ -489,15 +512,21 @@
       assertNull(message3);
 
       session.close();
+
+      assertEquals(0, sf.numSessions());
+
+      assertEquals(0, sf.numConnections());
+      
+      assertEquals(0, sf.numBackupConnections());
    }
 
    public void testFailoverMultipleSessions() throws Exception
    {
-      ClientSessionFactory sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
-                                                             new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
-                                                                                        backupParams));
+      ClientSessionFactoryInternal sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
+                                                                     new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
+                                                                                                backupParams));
 
-      final int numSessions = 10;
+      final int numSessions = ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS * 2;
 
       List<ClientSession> sessions = new ArrayList<ClientSession>();
 
@@ -553,12 +582,8 @@
             ClientMessage message2 = cons.receive();
 
             assertEquals("aardvarks", message2.getBody().getString());
-            
-           // log.info("actually got message " + message2.getMessageID());
 
             assertEquals(j, message2.getProperty(new SimpleString("count")));
-            
-            
 
             message2.acknowledge();
          }
@@ -576,85 +601,86 @@
 
          sess.close();
       }
+
+      assertEquals(0, sf.numSessions());
+
+      assertEquals(0, sf.numConnections());
+      
+      assertEquals(0, sf.numBackupConnections());
    }
 
-   public void testCantSetConnectorsAfterCreateSession() throws Exception
+   public void testAllConnectionsReturned() throws Exception
    {
-      ClientSessionFactory sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
-                                                             new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
-                                                                                        backupParams));
+      ClientSessionFactoryInternal sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
+                                                                     new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
+                                                                                                backupParams));
 
-      sf.setConnectorFactory(new InVMConnectorFactory());
-      sf.setTransportParams(new HashMap<String, Object>());
-      sf.setBackupConnectorFactory(new InVMConnectorFactory());
-      sf.setBackupTransportParams(new HashMap<String, Object>());
+      final int numSessions = ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS * 2;
 
-      ClientSession sess = null;
+      List<ClientSession> sessions = new ArrayList<ClientSession>();
 
-      try
+      for (int i = 0; i < numSessions; i++)
       {
-         sess = sf.createSession(false, true, true, false);
+         ClientSession sess = sf.createSession(false, true, true, false);
 
-         try
-         {
-            sf.setConnectorFactory(new InVMConnectorFactory());
+         sessions.add(sess);
+      }
 
-            fail("Should throw exception");
-         }
-         catch (IllegalStateException e)
-         {
-            // Ok
-         }
+      for (int i = 0; i < numSessions; i++)
+      {
+         ClientSession sess = sessions.get(i);
 
-         try
-         {
-            sf.setTransportParams(new HashMap<String, Object>());
+         sess.close();
+      }
 
-            fail("Should throw exception");
-         }
-         catch (IllegalStateException e)
-         {
-            // Ok
-         }
+      assertEquals(0, sf.numSessions());
 
-         try
-         {
-            sf.setBackupConnectorFactory(new InVMConnectorFactory());
+      assertEquals(0, sf.numConnections());
+      
+      assertEquals(0, sf.numBackupConnections());
+   }
 
-            fail("Should throw exception");
-         }
-         catch (IllegalStateException e)
-         {
-            // Ok
-         }
+   public void testAllConnectionsReturnedAfterFailover() throws Exception
+   {
+      ClientSessionFactoryInternal sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
+                                                                     new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
+                                                                                                backupParams));
 
-         try
-         {
-            sf.setBackupTransportParams(new HashMap<String, Object>());
+      final int numSessions = ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS * 2;
 
-            fail("Should throw exception");
-         }
-         catch (IllegalStateException e)
-         {
-            // Ok
-         }
+      List<ClientSession> sessions = new ArrayList<ClientSession>();
+
+      for (int i = 0; i < numSessions; i++)
+      {
+         ClientSession sess = sf.createSession(false, true, true, false);
+
+         sessions.add(sess);
       }
-      finally
+
+      RemotingConnection conn = ((ClientSessionImpl)sessions.get(0)).getConnection();
+
+      // Simulate failure on connection
+      conn.fail(new MessagingException(MessagingException.NOT_CONNECTED));
+
+      for (int i = 0; i < numSessions; i++)
       {
+         ClientSession sess = sessions.get(i);
+
          sess.close();
       }
 
-      sf.setConnectorFactory(new InVMConnectorFactory());
-      sf.setTransportParams(new HashMap<String, Object>());
-      sf.setBackupConnectorFactory(new InVMConnectorFactory());
-      sf.setBackupTransportParams(new HashMap<String, Object>());
+      assertEquals(0, sf.numSessions());
+
+      assertEquals(0, sf.numConnections());
+      
+      assertEquals(0, sf.numBackupConnections());
    }
 
    public void testFailureAfterFailover() throws Exception
    {
-      ClientSessionFactory sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
-                                                             new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
-                                                                                        backupParams));
+      ClientSessionFactoryInternal sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
+                                                                     new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
+                                                                                                backupParams));
 
       ClientSession session = sf.createSession(false, true, true, false);
 
@@ -729,10 +755,16 @@
       }
       catch (MessagingException me)
       {
-         assertEquals(MessagingException.NOT_CONNECTED, me.getCode());
+         assertEquals(MessagingException.OBJECT_CLOSED, me.getCode());
       }
 
       session.close();
+
+      assertEquals(0, sf.numSessions());
+
+      assertEquals(0, sf.numConnections());
+      
+      assertEquals(0, sf.numBackupConnections());
    }
 
    // Package protected ---------------------------------------------
@@ -767,8 +799,6 @@
    @Override
    protected void tearDown() throws Exception
    {
-      assertEquals(0, ConnectionRegistryImpl.instance.size());
-
       assertEquals(0, backupService.getServer().getRemotingService().getConnections().size());
 
       backupService.stop();

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/SimpleManualFailoverTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/SimpleManualFailoverTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/SimpleManualFailoverTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -35,6 +35,7 @@
 import org.jboss.messaging.core.client.ClientSession;
 import org.jboss.messaging.core.client.ClientSessionFactory;
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
+import org.jboss.messaging.core.client.impl.ClientSessionFactoryInternal;
 import org.jboss.messaging.core.client.impl.ClientSessionImpl;
 import org.jboss.messaging.core.config.Configuration;
 import org.jboss.messaging.core.config.TransportConfiguration;
@@ -43,7 +44,6 @@
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.FailureListener;
 import org.jboss.messaging.core.remoting.RemotingConnection;
-import org.jboss.messaging.core.remoting.impl.ConnectionRegistryImpl;
 import org.jboss.messaging.core.remoting.impl.invm.InVMRegistry;
 import org.jboss.messaging.core.remoting.impl.invm.TransportConstants;
 import org.jboss.messaging.core.server.MessagingService;
@@ -127,7 +127,7 @@
    
    public void testFailover() throws Exception
    {
-      ClientSessionFactory sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"));
+      ClientSessionFactoryInternal sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"));
 
       ClientSession session = sendAndConsume(sf);
 
@@ -165,6 +165,12 @@
       session = sendAndConsume(sf);
 
       session.close();
+      
+      assertEquals(0, sf.numSessions());
+      
+      assertEquals(0, sf.numConnections());
+      
+      assertEquals(0, sf.numBackupConnections());
    }
 
    // Package protected ---------------------------------------------
@@ -194,8 +200,6 @@
 
    protected void tearDown() throws Exception
    {
-      assertEquals(0, ConnectionRegistryImpl.instance.size());
-
       assertEquals(0, server1Service.getServer().getRemotingService().getConnections().size());
 
       server1Service.stop();

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/consumer/ConsumerTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/consumer/ConsumerTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/consumer/ConsumerTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -26,10 +26,12 @@
 import org.jboss.messaging.core.client.ClientProducer;
 import org.jboss.messaging.core.client.ClientSession;
 import org.jboss.messaging.core.client.ClientSessionFactory;
+import org.jboss.messaging.core.client.MessageHandler;
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.Configuration;
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.config.impl.ConfigurationImpl;
+import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.server.MessagingService;
 import org.jboss.messaging.core.server.impl.MessagingServiceImpl;
 import org.jboss.messaging.jms.client.JBossTextMessage;
@@ -41,6 +43,8 @@
  */
 public class ConsumerTest extends UnitTestCase
 {
+   private static final Logger log = Logger.getLogger(ConsumerTest.class);
+   
    private MessagingService messagingService;
 
    private SimpleString QUEUE = new SimpleString("ConsumerTestQueue");
@@ -51,7 +55,8 @@
 
       conf.setSecurityEnabled(false);
 
-      conf.getAcceptorConfigurations().add(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMAcceptorFactory"));
+      conf.getAcceptorConfigurations()
+          .add(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMAcceptorFactory"));
 
       messagingService = MessagingServiceImpl.newNullStorageMessagingServer(conf);
 
@@ -108,7 +113,6 @@
 
       session.close();
 
-
    }
 
    public void testConsumerBrowserWithSelector() throws Exception
@@ -155,7 +159,6 @@
 
       session.close();
 
-
    }
 
    public void testConsumerBrowserWithStringSelector() throws Exception
@@ -174,7 +177,7 @@
       for (int i = 0; i < numMessages; i++)
       {
          ClientMessage message = createMessage(session, "m" + i);
-         if(i % 2 == 0)
+         if (i % 2 == 0)
          {
             message.putStringProperty(new SimpleString("color"), new SimpleString("RED"));
          }
@@ -183,7 +186,7 @@
 
       ClientConsumer consumer = session.createConsumer(QUEUE, new SimpleString("color = 'RED'"), false, true);
 
-      for (int i = 0; i < numMessages; i+=2)
+      for (int i = 0; i < numMessages; i += 2)
       {
          ClientMessage message2 = consumer.receive(1000);
 
@@ -192,7 +195,6 @@
 
       session.close();
 
-
    }
 
    public void testConsumerMultipleBrowser() throws Exception
@@ -230,7 +232,6 @@
 
       session.close();
 
-
    }
 
    public void testConsumerMultipleBrowserWithSelector() throws Exception
@@ -275,7 +276,6 @@
 
       session.close();
 
-
    }
 
    public void testConsumerBrowserMessagesArentAcked() throws Exception
@@ -305,19 +305,15 @@
 
          assertEquals("m" + i, message2.getBody().getString());
       }
-      //assert that all the messages are there and none have been acked
+      // assert that all the messages are there and none have been acked
       assertEquals(messagingService.getServer().getPostOffice().getBinding(QUEUE).getQueue().getDeliveringCount(), 0);
       assertEquals(messagingService.getServer().getPostOffice().getBinding(QUEUE).getQueue().getMessageCount(), 100);
 
       session.close();
-
-
    }
 
-
    public void testConsumerBrowserMessageAckDoesNothing() throws Exception
    {
-
       ClientSessionFactory sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"));
 
       ClientSession session = sf.createSession(false, true, true, false);
@@ -344,19 +340,81 @@
 
          assertEquals("m" + i, message2.getBody().getString());
       }
-      //assert that all the messages are there and none have been acked
+      // assert that all the messages are there and none have been acked
       assertEquals(messagingService.getServer().getPostOffice().getBinding(QUEUE).getQueue().getDeliveringCount(), 0);
       assertEquals(messagingService.getServer().getPostOffice().getBinding(QUEUE).getQueue().getMessageCount(), 100);
 
       session.close();
+   }
+   
+   public void testSetMessageHandlerWithMessagesPending() throws Exception
+   {
+      ClientSessionFactory sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"));
 
+      ClientSession session = sf.createSession(false, true, true, false);
 
+      session.createQueue(QUEUE, QUEUE, null, false, false);
+
+      ClientProducer producer = session.createProducer(QUEUE);
+
+      final int numMessages = 100;
+
+      for (int i = 0; i < numMessages; i++)
+      {
+         ClientMessage message = createMessage(session, "m" + i);
+         producer.send(message);
+      }
+
+      ClientConsumer consumer = session.createConsumer(QUEUE, null, false, true);
+      
+      session.start();
+      
+      Thread.sleep(100);
+      
+      //Message should be in consumer
+      
+      class MyHandler implements MessageHandler
+      {
+         public void onMessage(final ClientMessage message)
+         {
+            try
+            {
+               Thread.sleep(10);
+               
+               message.acknowledge();
+            }
+            catch (Exception e)
+            {               
+            }                        
+         }                 
+      }
+      
+      consumer.setMessageHandler(new MyHandler());
+      
+      //Let a few messages get processed
+      Thread.sleep(100);
+      
+      //Now set null
+      
+      consumer.setMessageHandler(null);
+       
+      //Give a bit of time for some queued executors to run
+      
+      Thread.sleep(500);
+      
+      //Make sure no exceptions were thrown from onMessage
+      assertNull(consumer.getLastException());
+
+      session.close();
    }
 
    private ClientMessage createMessage(ClientSession session, String msg)
    {
-      ClientMessage message = session.createClientMessage(JBossTextMessage.TYPE, false, 0,
-            System.currentTimeMillis(), (byte) 1);
+      ClientMessage message = session.createClientMessage(JBossTextMessage.TYPE,
+                                                          false,
+                                                          0,
+                                                          System.currentTimeMillis(),
+                                                          (byte)1);
       message.getBody().putString(msg);
       message.getBody().flip();
       return message;

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/remoting/DestroyConsumerTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/remoting/DestroyConsumerTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/remoting/DestroyConsumerTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -23,17 +23,7 @@
 
 package org.jboss.messaging.tests.integration.remoting;
 
-import java.util.HashMap;
-
-import org.jboss.messaging.core.client.ClientConsumer;
-import org.jboss.messaging.core.client.ClientSession;
-import org.jboss.messaging.core.client.ClientSessionFactory;
-import org.jboss.messaging.core.client.impl.ClientSessionImpl;
-import org.jboss.messaging.core.postoffice.Binding;
-import org.jboss.messaging.core.server.MessagingService;
-import org.jboss.messaging.core.settings.impl.QueueSettings;
 import org.jboss.messaging.tests.integration.base.IntegrationTestBase;
-import org.jboss.messaging.util.SimpleString;
 
 public class DestroyConsumerTest extends IntegrationTestBase
 {

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/remoting/PingTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/remoting/PingTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/remoting/PingTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -32,12 +32,12 @@
 import org.jboss.messaging.core.config.impl.ConfigurationImpl;
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.remoting.ConnectionRegistry;
+import org.jboss.messaging.core.remoting.ConnectionManager;
 import org.jboss.messaging.core.remoting.FailureListener;
 import org.jboss.messaging.core.remoting.Interceptor;
 import org.jboss.messaging.core.remoting.Packet;
 import org.jboss.messaging.core.remoting.RemotingConnection;
-import org.jboss.messaging.core.remoting.impl.ConnectionRegistryImpl;
+import org.jboss.messaging.core.remoting.impl.ConnectionManagerImpl;
 import org.jboss.messaging.core.remoting.impl.RemotingConnectionImpl;
 import org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory;
 import org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl;
@@ -108,11 +108,11 @@
       ConnectorFactory cf = new NettyConnectorFactory();
       Map<String, Object> params = new HashMap<String, Object>();
       
-      ConnectionRegistry registry = ConnectionRegistryImpl.instance;
+      ConnectionManager cm = new ConnectionManagerImpl(cf, params, PING_INTERVAL, 5000, 1, 1);
       
-      RemotingConnection conn = registry.getConnection(cf, params, PING_INTERVAL, 5000);
+      RemotingConnection conn = cm.getConnection();
       assertNotNull(conn);
-      assertEquals(1, registry.getCount(cf, params));
+      assertEquals(1, cm.numConnections());
       
       Listener clientListener = new Listener();
       
@@ -148,8 +148,7 @@
       
       assertTrue(serverConn == serverConn2);    
         
-      registry.returnConnection(conn.getID());
-      
+      cm.returnConnection(conn.getID());
    }
    
    /*
@@ -160,11 +159,11 @@
       ConnectorFactory cf = new NettyConnectorFactory();
       Map<String, Object> params = new HashMap<String, Object>();
       
-      ConnectionRegistry registry = ConnectionRegistryImpl.instance;
+      ConnectionManager cm = new ConnectionManagerImpl(cf, params, PING_INTERVAL, 5000, 1, 1);
       
-      RemotingConnection conn = registry.getConnection(cf, params, -1, 5000);
+      RemotingConnection conn = cm.getConnection();
       assertNotNull(conn);
-      assertEquals(1, registry.getCount(cf, params));
+      assertEquals(1, cm.numConnections());
       
       Listener clientListener = new Listener();
       
@@ -200,7 +199,7 @@
       
       assertTrue(serverConn == serverConn2); 
       
-      registry.returnConnection(conn.getID());
+      cm.returnConnection(conn.getID());
    }
    
    /*
@@ -211,10 +210,10 @@
       ConnectorFactory cf = new NettyConnectorFactory();
       Map<String, Object> params = new HashMap<String, Object>();
       
-      ConnectionRegistry registry = ConnectionRegistryImpl.instance;
+      ConnectionManager cm = new ConnectionManagerImpl(cf, params, PING_INTERVAL, 5000, 1, 1);
       
-      RemotingConnectionImpl conn = (RemotingConnectionImpl)registry.getConnection(cf, params, PING_INTERVAL, 5000);
-      assertEquals(1, registry.getCount(cf, params));
+      RemotingConnectionImpl conn = (RemotingConnectionImpl)cm.getConnection();
+      assertEquals(1, cm.numConnections());
       assertNotNull(conn);
         
       //We need to get it to send one ping then stop         
@@ -257,12 +256,10 @@
       
       //Make sure we don't get the same connection back - it should have been removed from the registry
       
-      RemotingConnection conn2 = registry.getConnection(cf, params, PING_INTERVAL * 2, 5000);
+      RemotingConnection conn2 = cm.getConnection();
       assertNotNull(conn2);
       
-      assertFalse(conn == conn2);
-      
-      registry.returnConnection(conn2.getID());    
+      cm.returnConnection(conn2.getID());    
    }
 
    /*
@@ -291,11 +288,11 @@
      ConnectorFactory cf = new NettyConnectorFactory();
      Map<String, Object> params = new HashMap<String, Object>();
      
-     ConnectionRegistry registry = ConnectionRegistryImpl.instance;
+     ConnectionManager cm = new ConnectionManagerImpl(cf, params, PING_INTERVAL, 5000, 1, 1);
      
-     RemotingConnection conn = registry.getConnection(cf, params, PING_INTERVAL, 5000);
+     RemotingConnection conn = cm.getConnection();
      assertNotNull(conn);
-     assertEquals(1, registry.getCount(cf, params));
+     assertEquals(1, cm.numConnections());
             
      Listener clientListener = new Listener();
      
@@ -325,6 +322,9 @@
      
      assertNotNull(clientListener.getException());
      
+     //Sleep a bit more since it's async
+     Thread.sleep(PING_INTERVAL);
+     
      //We don't receive an exception on the server in this case
      assertNull(serverListener.getException());
      
@@ -332,12 +332,12 @@
      
      //Make sure we don't get the same connection back - it should have been removed from the registry
      
-     RemotingConnection conn2 = registry.getConnection(cf, params, PING_INTERVAL, 5000);
+     RemotingConnection conn2 = cm.getConnection();
      assertNotNull(conn2);        
 
      messagingService.getServer().getRemotingService().removeInterceptor(noPongInterceptor);
      
-     registry.returnConnection(conn2.getID());
+     cm.returnConnection(conn2.getID());
      
   }
    

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/scheduling/ScheduledMessageTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/scheduling/ScheduledMessageTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/scheduling/ScheduledMessageTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,6 +21,12 @@
  */
 package org.jboss.messaging.tests.integration.scheduling;
 
+import java.io.File;
+import java.util.Calendar;
+
+import javax.transaction.xa.XAResource;
+import javax.transaction.xa.Xid;
+
 import org.jboss.messaging.core.client.ClientConsumer;
 import org.jboss.messaging.core.client.ClientMessage;
 import org.jboss.messaging.core.client.ClientProducer;
@@ -39,11 +45,6 @@
 import org.jboss.messaging.util.SimpleString;
 import org.jboss.util.id.GUID;
 
-import javax.transaction.xa.XAResource;
-import javax.transaction.xa.Xid;
-import java.io.File;
-import java.util.Calendar;
-
 /**
  * @author <a href="mailto:andy.taylor at jboss.org">Andy Taylor</a>
  */

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/ssl/CoreClientOverSSL.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/ssl/CoreClientOverSSL.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/ssl/CoreClientOverSSL.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -31,9 +31,7 @@
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory;
 import org.jboss.messaging.core.remoting.impl.netty.TransportConstants;
-import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
 import org.jboss.messaging.jms.client.JBossTextMessage;
 
 /**

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/ssl/CoreClientOverSSLTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/ssl/CoreClientOverSSLTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/ssl/CoreClientOverSSLTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,27 +22,12 @@
 
 package org.jboss.messaging.tests.integration.ssl;
 
-import static java.lang.Boolean.FALSE;
-
-import java.util.HashMap;
-import java.util.Map;
-
 import junit.framework.TestCase;
 
 import org.jboss.messaging.core.client.ClientConsumer;
 import org.jboss.messaging.core.client.ClientSession;
-import org.jboss.messaging.core.client.ClientSessionFactory;
-import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
-import org.jboss.messaging.core.config.TransportConfiguration;
-import org.jboss.messaging.core.config.impl.ConfigurationImpl;
 import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.message.Message;
-import org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory;
-import org.jboss.messaging.core.remoting.impl.netty.TransportConstants;
-import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
 import org.jboss.messaging.core.server.MessagingService;
-import org.jboss.messaging.core.server.impl.MessagingServiceImpl;
-import org.jboss.messaging.tests.util.SpawnedVMSupport;
 import org.jboss.messaging.util.SimpleString;
 
 /**

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/xa/BasicXaRecoveryTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/xa/BasicXaRecoveryTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/xa/BasicXaRecoveryTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,7 +21,19 @@
  */
 package org.jboss.messaging.tests.integration.xa;
 
-import org.jboss.messaging.core.client.*;
+import java.io.File;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.transaction.xa.XAResource;
+import javax.transaction.xa.Xid;
+
+import org.jboss.messaging.core.client.ClientConsumer;
+import org.jboss.messaging.core.client.ClientMessage;
+import org.jboss.messaging.core.client.ClientProducer;
+import org.jboss.messaging.core.client.ClientSession;
+import org.jboss.messaging.core.client.ClientSessionFactory;
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.config.impl.ConfigurationImpl;
@@ -36,13 +48,6 @@
 import org.jboss.messaging.util.SimpleString;
 import org.jboss.util.id.GUID;
 
-import javax.transaction.xa.XAResource;
-import javax.transaction.xa.Xid;
-import java.io.File;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Map;
-
 /**
  * @author <a href="mailto:andy.taylor at jboss.org">Andy Taylor</a>
  */

Modified: trunk/tests/src/org/jboss/messaging/tests/performance/persistence/FakePostOffice.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/performance/persistence/FakePostOffice.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/performance/persistence/FakePostOffice.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -18,7 +18,7 @@
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */ 
+ */
 
 package org.jboss.messaging.tests.performance.persistence;
 
@@ -35,6 +35,7 @@
 import org.jboss.messaging.core.server.Queue;
 import org.jboss.messaging.core.server.QueueFactory;
 import org.jboss.messaging.core.server.ServerMessage;
+import org.jboss.messaging.core.server.impl.SendLockImpl;
 import org.jboss.messaging.tests.unit.core.server.impl.fakes.FakeQueueFactory;
 import org.jboss.messaging.util.ConcurrentHashSet;
 import org.jboss.messaging.util.SimpleString;
@@ -49,24 +50,26 @@
 public class FakePostOffice implements PostOffice
 {
    private ConcurrentHashMap<SimpleString, Binding> bindings = new ConcurrentHashMap<SimpleString, Binding>();
-   
+
    private QueueFactory queueFactory = new FakeQueueFactory();
-   
+
    private ConcurrentHashSet<SimpleString> addresses = new ConcurrentHashSet<SimpleString>();
-   
+
    private volatile boolean started;
-   
-   public Binding addBinding(SimpleString address, SimpleString queueName,
-         Filter filter, boolean durable, boolean temporary) throws Exception
+
+   public Binding addBinding(SimpleString address,
+                             SimpleString queueName,
+                             Filter filter,
+                             boolean durable,
+                             boolean temporary) throws Exception
    {
-      Queue queue = queueFactory.createQueue(-1, queueName, filter, durable, false); 
+      Queue queue = queueFactory.createQueue(-1, queueName, filter, durable, false);
       Binding binding = new FakeBinding(address, queue);
       bindings.put(address, binding);
       return binding;
    }
 
-   public boolean addDestination(SimpleString address, boolean temporary)
-         throws Exception
+   public boolean addDestination(SimpleString address, boolean temporary) throws Exception
    {
       return addresses.addIfAbsent(address);
    }
@@ -81,8 +84,7 @@
       return bindings.get(queueName);
    }
 
-   public List<Binding> getBindingsForAddress(SimpleString address)
-         throws Exception
+   public List<Binding> getBindingsForAddress(SimpleString address) throws Exception
    {
       return null;
    }
@@ -107,8 +109,7 @@
       return null;
    }
 
-   public boolean removeDestination(SimpleString address, boolean temporary)
-         throws Exception
+   public boolean removeDestination(SimpleString address, boolean temporary) throws Exception
    {
       return false;
    }
@@ -122,7 +123,7 @@
    {
       started = false;
    }
-   
+
    public boolean isStarted()
    {
       return started;
@@ -132,7 +133,7 @@
    {
       return null;
    }
-   
+
    public void activate()
    {
    }
@@ -142,5 +143,9 @@
       return null;
    }
 
-   
+   public SendLockImpl getAddressLock(SimpleString address)
+   {
+      return null;
+   }
+
 }

Modified: trunk/tests/src/org/jboss/messaging/tests/performance/persistence/StorageManagerTimingTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/performance/persistence/StorageManagerTimingTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/performance/persistence/StorageManagerTimingTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,6 +22,11 @@
 
 package org.jboss.messaging.tests.performance.persistence;
 
+import java.io.File;
+import java.nio.ByteBuffer;
+import java.util.HashMap;
+import java.util.concurrent.atomic.AtomicLong;
+
 import org.jboss.messaging.core.asyncio.impl.AsynchronousFileImpl;
 import org.jboss.messaging.core.config.impl.FileConfiguration;
 import org.jboss.messaging.core.logging.Logger;
@@ -34,11 +39,6 @@
 import org.jboss.messaging.tests.util.UnitTestCase;
 import org.jboss.messaging.util.SimpleString;
 
-import java.io.File;
-import java.nio.ByteBuffer;
-import java.util.HashMap;
-import java.util.concurrent.atomic.AtomicLong;
-
 /**
  * 
  * @author <a href="mailto:clebert.suconic at jboss.com">Clebert Suconic</a>

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/config/impl/ConfigurationImplTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/config/impl/ConfigurationImplTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/config/impl/ConfigurationImplTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,11 +22,10 @@
 
 package org.jboss.messaging.tests.unit.core.config.impl;
 
-import junit.framework.TestCase;
-import org.jboss.messaging.core.config.Configuration;
-import org.jboss.messaging.core.config.impl.ConfigurationImpl;
-import org.jboss.messaging.core.server.JournalType;
-import static org.jboss.messaging.tests.util.RandomUtil.*;
+import static org.jboss.messaging.tests.util.RandomUtil.randomBoolean;
+import static org.jboss.messaging.tests.util.RandomUtil.randomInt;
+import static org.jboss.messaging.tests.util.RandomUtil.randomLong;
+import static org.jboss.messaging.tests.util.RandomUtil.randomString;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
@@ -34,6 +33,12 @@
 import java.io.ObjectOutputStream;
 import java.util.List;
 
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.config.Configuration;
+import org.jboss.messaging.core.config.impl.ConfigurationImpl;
+import org.jboss.messaging.core.server.JournalType;
+
 /**
  * 
  * A ConfigurationImplTest

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/config/impl/FileConfigurationTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/config/impl/FileConfigurationTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/config/impl/FileConfigurationTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,12 +22,12 @@
 
 package org.jboss.messaging.tests.unit.core.config.impl;
 
+import java.util.Map;
+
 import org.jboss.messaging.core.config.Configuration;
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.config.impl.FileConfiguration;
 
-import java.util.Map;
-
 /**
  * @author <a href="ataylor at redhat.com">Andy Taylor</a>
  * @author <a href="tim.fox at jboss.com">Tim Fox</a>

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/filter/impl/FilterTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/filter/impl/FilterTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/filter/impl/FilterTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -23,6 +23,7 @@
 package org.jboss.messaging.tests.unit.core.filter.impl;
 
 import junit.framework.TestCase;
+
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.filter.Filter;
 import org.jboss.messaging.core.filter.impl.FilterImpl;

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PageManagerImplTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PageManagerImplTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PageManagerImplTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,6 +22,11 @@
 
 package org.jboss.messaging.tests.unit.core.paging.impl;
 
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+
 import org.easymock.EasyMock;
 import org.jboss.messaging.core.journal.SequentialFileFactory;
 import org.jboss.messaging.core.paging.LastPageRecord;
@@ -43,11 +48,6 @@
 import org.jboss.messaging.tests.util.UnitTestCase;
 import org.jboss.messaging.util.SimpleString;
 
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.Executors;
-
 public class PageManagerImplTest extends UnitTestCase
 {
 

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PagingStoreImplTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PagingStoreImplTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PagingStoreImplTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,6 +22,10 @@
 
 package org.jboss.messaging.tests.unit.core.paging.impl;
 
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+
 import org.jboss.messaging.core.journal.SequentialFileFactory;
 import org.jboss.messaging.core.paging.Page;
 import org.jboss.messaging.core.paging.PageMessage;
@@ -33,10 +37,6 @@
 import org.jboss.messaging.tests.unit.core.journal.impl.fakes.FakeSequentialFileFactory;
 import org.jboss.messaging.util.SimpleString;
 
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.List;
-
 /**
  * 
  * @author <a href="mailto:clebert.suconic at jboss.com">Clebert Suconic</a>

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/postoffice/impl/PostOfficeImplWildcardManagerTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/postoffice/impl/PostOfficeImplWildcardManagerTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/postoffice/impl/PostOfficeImplWildcardManagerTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -21,6 +21,9 @@
  */
 package org.jboss.messaging.tests.unit.core.postoffice.impl;
 
+import java.util.List;
+import java.util.Map;
+
 import org.easymock.EasyMock;
 import org.jboss.messaging.core.management.ManagementService;
 import org.jboss.messaging.core.paging.PagingManager;
@@ -35,9 +38,6 @@
 import org.jboss.messaging.core.transaction.ResourceManager;
 import org.jboss.messaging.util.SimpleString;
 
-import java.util.List;
-import java.util.Map;
-
 /**
  * @author <a href="mailto:andy.taylor at jboss.org">Andy Taylor</a>
  */

Deleted: trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/ConnectionRegistryLocatorTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/ConnectionRegistryLocatorTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/remoting/ConnectionRegistryLocatorTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -1,49 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-package org.jboss.messaging.tests.unit.core.remoting;
-
-import org.jboss.messaging.core.remoting.ConnectionRegistry;
-import org.jboss.messaging.core.remoting.impl.ConnectionRegistryImpl;
-import org.jboss.messaging.tests.util.UnitTestCase;
-
-/**
- * 
- * A ConnectionRegistryLocatorTest
- * 
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- *
- */
-public class ConnectionRegistryLocatorTest extends UnitTestCase
-{
-   public void testSingleton()
-   {
-      ConnectionRegistry reg1 = ConnectionRegistryImpl.instance;
-      
-      ConnectionRegistry reg2 = ConnectionRegistryImpl.instance;
-      
-      assertTrue(reg1 == reg2);
-      
-      assertTrue(reg1 instanceof ConnectionRegistryImpl);
-      
-      assertTrue(reg2 instanceof ConnectionRegistryImpl);
-   }   
-}

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/GroupingRoundRobinDistributionPolicyTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/GroupingRoundRobinDistributionPolicyTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/GroupingRoundRobinDistributionPolicyTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -24,10 +24,10 @@
 import org.easymock.EasyMock;
 import org.jboss.messaging.core.message.impl.MessageImpl;
 import org.jboss.messaging.core.server.Consumer;
+import org.jboss.messaging.core.server.DistributionPolicy;
+import org.jboss.messaging.core.server.HandleStatus;
+import org.jboss.messaging.core.server.MessageReference;
 import org.jboss.messaging.core.server.ServerMessage;
-import org.jboss.messaging.core.server.MessageReference;
-import org.jboss.messaging.core.server.HandleStatus;
-import org.jboss.messaging.core.server.DistributionPolicy;
 import org.jboss.messaging.core.server.impl.GroupingRoundRobinDistributionPolicy;
 import org.jboss.messaging.core.server.impl.RoundRobinDistributionPolicy;
 import org.jboss.messaging.tests.util.UnitTestCase;

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/QueueImplTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/QueueImplTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/QueueImplTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,7 +22,6 @@
 
 package org.jboss.messaging.tests.unit.core.server.impl;
 
-import org.easymock.EasyMock;
 import static org.easymock.EasyMock.anyLong;
 import static org.easymock.EasyMock.createMock;
 import static org.easymock.EasyMock.eq;
@@ -30,6 +29,17 @@
 import static org.easymock.EasyMock.isA;
 import static org.easymock.EasyMock.replay;
 import static org.easymock.EasyMock.verify;
+import static org.jboss.messaging.tests.util.RandomUtil.randomLong;
+
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+
+import org.easymock.EasyMock;
 import org.jboss.messaging.core.filter.Filter;
 import org.jboss.messaging.core.paging.PagingManager;
 import org.jboss.messaging.core.persistence.StorageManager;
@@ -47,18 +57,9 @@
 import org.jboss.messaging.core.settings.impl.QueueSettings;
 import org.jboss.messaging.tests.unit.core.server.impl.fakes.FakeConsumer;
 import org.jboss.messaging.tests.unit.core.server.impl.fakes.FakeFilter;
-import static org.jboss.messaging.tests.util.RandomUtil.randomLong;
 import org.jboss.messaging.tests.util.UnitTestCase;
 import org.jboss.messaging.util.SimpleString;
 
-import java.util.ArrayList;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.Executor;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-
 /**
  * A QueueTest
  *

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/RoundRobinDistributionPolicyTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/RoundRobinDistributionPolicyTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/RoundRobinDistributionPolicyTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,18 +22,14 @@
 
 package org.jboss.messaging.tests.unit.core.server.impl;
 
+import org.easymock.EasyMock;
 import org.jboss.messaging.core.server.Consumer;
 import org.jboss.messaging.core.server.DistributionPolicy;
-import org.jboss.messaging.core.server.MessageReference;
 import org.jboss.messaging.core.server.HandleStatus;
+import org.jboss.messaging.core.server.MessageReference;
 import org.jboss.messaging.core.server.impl.RoundRobinDistributionPolicy;
-import org.jboss.messaging.tests.unit.core.server.impl.fakes.FakeConsumer;
 import org.jboss.messaging.tests.util.UnitTestCase;
-import org.easymock.EasyMock;
 
-import java.util.ArrayList;
-import java.util.List;
-
 /**
  * 
  * A RoundRobinDistributionPolicyTest

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/settings/impl/QueueSettingsTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/settings/impl/QueueSettingsTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/settings/impl/QueueSettingsTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -23,6 +23,7 @@
 package org.jboss.messaging.tests.unit.core.settings.impl;
 
 import junit.framework.TestCase;
+
 import org.jboss.messaging.core.settings.impl.QueueSettings;
 import org.jboss.messaging.util.SimpleString;
 

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/transaction/impl/TransactionImplTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/transaction/impl/TransactionImplTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/transaction/impl/TransactionImplTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,6 +22,13 @@
 
 package org.jboss.messaging.tests.unit.core.transaction.impl;
 
+import static org.jboss.messaging.tests.util.RandomUtil.randomXid;
+
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+
+import javax.transaction.xa.Xid;
+
 import org.easymock.EasyMock;
 import org.jboss.messaging.core.persistence.StorageManager;
 import org.jboss.messaging.core.postoffice.PostOffice;
@@ -34,14 +41,9 @@
 import org.jboss.messaging.core.settings.impl.QueueSettings;
 import org.jboss.messaging.core.transaction.Transaction;
 import org.jboss.messaging.core.transaction.impl.TransactionImpl;
-import static org.jboss.messaging.tests.util.RandomUtil.randomXid;
 import org.jboss.messaging.tests.util.UnitTestCase;
 import org.jboss.messaging.util.SimpleString;
 
-import javax.transaction.xa.Xid;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-
 /**
  * 
  * A TransactionImplTest

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/JBossConnectionFactoryTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/JBossConnectionFactoryTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/JBossConnectionFactoryTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,22 +22,10 @@
 
 package org.jboss.messaging.tests.unit.jms.client;
 
-import static org.jboss.messaging.tests.util.RandomUtil.randomString;
-
-import java.util.HashMap;
-import java.util.Map;
-
 import javax.jms.Connection;
-import javax.jms.QueueConnection;
-import javax.jms.TopicConnection;
-import javax.jms.XAConnection;
-import javax.jms.XAQueueConnection;
-import javax.jms.XATopicConnection;
 
 import junit.framework.TestCase;
 
-import org.easymock.classextension.EasyMock;
-import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
 import org.jboss.messaging.jms.client.JBossConnectionFactory;
 
 /**

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/JBossConnectionMetaDataTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/JBossConnectionMetaDataTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/JBossConnectionMetaDataTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,16 +22,22 @@
 
 package org.jboss.messaging.tests.unit.jms.client;
 
-import junit.framework.TestCase;
-import static org.easymock.EasyMock.*;
-import org.jboss.messaging.core.version.Version;
-import org.jboss.messaging.jms.client.JBossConnectionMetaData;
+import static org.easymock.EasyMock.createStrictMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.verify;
 
-import javax.jms.ConnectionMetaData;
 import java.util.Enumeration;
 import java.util.HashSet;
 import java.util.Set;
 
+import javax.jms.ConnectionMetaData;
+
+import junit.framework.TestCase;
+
+import org.jboss.messaging.core.version.Version;
+import org.jboss.messaging.jms.client.JBossConnectionMetaData;
+
 /**
  * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
  * 

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/JBossMessageTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/JBossMessageTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/JBossMessageTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,9 +22,32 @@
 
 package org.jboss.messaging.tests.unit.jms.client;
 
+import static org.easymock.EasyMock.createNiceMock;
+import static org.easymock.EasyMock.createStrictMock;
+import static org.easymock.EasyMock.expect;
+import static org.easymock.EasyMock.replay;
+import static org.easymock.EasyMock.verify;
+import static org.jboss.messaging.tests.util.RandomUtil.randomByte;
+import static org.jboss.messaging.tests.util.RandomUtil.randomBytes;
+import static org.jboss.messaging.tests.util.RandomUtil.randomDouble;
+import static org.jboss.messaging.tests.util.RandomUtil.randomFloat;
+import static org.jboss.messaging.tests.util.RandomUtil.randomInt;
+import static org.jboss.messaging.tests.util.RandomUtil.randomLong;
+import static org.jboss.messaging.tests.util.RandomUtil.randomShort;
+import static org.jboss.messaging.tests.util.RandomUtil.randomSimpleString;
+import static org.jboss.messaging.tests.util.RandomUtil.randomString;
+
+import java.nio.ByteBuffer;
+import java.util.Collections;
+
+import javax.jms.DeliveryMode;
+import javax.jms.JMSException;
+import javax.jms.Message;
+import javax.jms.MessageFormatException;
+
 import junit.framework.TestCase;
+
 import org.easymock.EasyMock;
-import static org.easymock.EasyMock.*;
 import org.jboss.messaging.core.client.ClientMessage;
 import org.jboss.messaging.core.client.ClientSession;
 import org.jboss.messaging.core.client.impl.ClientMessageImpl;
@@ -32,17 +55,14 @@
 import org.jboss.messaging.core.message.impl.MessageImpl;
 import org.jboss.messaging.core.remoting.impl.ByteBufferWrapper;
 import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
-import org.jboss.messaging.jms.client.*;
-import static org.jboss.messaging.tests.util.RandomUtil.*;
+import org.jboss.messaging.jms.client.JBossBytesMessage;
+import org.jboss.messaging.jms.client.JBossMapMessage;
+import org.jboss.messaging.jms.client.JBossMessage;
+import org.jboss.messaging.jms.client.JBossObjectMessage;
+import org.jboss.messaging.jms.client.JBossStreamMessage;
+import org.jboss.messaging.jms.client.JBossTextMessage;
 import org.jboss.messaging.util.SimpleString;
 
-import javax.jms.DeliveryMode;
-import javax.jms.JMSException;
-import javax.jms.Message;
-import javax.jms.MessageFormatException;
-import java.nio.ByteBuffer;
-import java.util.Collections;
-
 /**
  * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
  * 

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/JBossSessionTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/JBossSessionTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/jms/client/JBossSessionTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,8 +22,6 @@
 
 package org.jboss.messaging.tests.unit.jms.client;
 
-import junit.framework.TestCase;
-import org.easymock.EasyMock;
 import static org.easymock.EasyMock.createStrictMock;
 import static org.easymock.EasyMock.eq;
 import static org.easymock.EasyMock.expect;
@@ -32,28 +30,13 @@
 import static org.easymock.EasyMock.isNull;
 import static org.easymock.EasyMock.replay;
 import static org.easymock.EasyMock.verify;
-import org.jboss.messaging.core.client.ClientConsumer;
-import org.jboss.messaging.core.client.ClientMessage;
-import org.jboss.messaging.core.client.ClientProducer;
-import org.jboss.messaging.core.client.ClientSession;
-import org.jboss.messaging.core.client.ClientSessionFactory;
-import org.jboss.messaging.core.client.impl.ClientMessageImpl;
-import org.jboss.messaging.core.exception.MessagingException;
-import org.jboss.messaging.core.remoting.impl.ByteBufferWrapper;
-import org.jboss.messaging.core.remoting.impl.wireformat.SessionBindingQueryResponseMessage;
-import org.jboss.messaging.core.remoting.impl.wireformat.SessionQueueQueryResponseMessage;
-import org.jboss.messaging.jms.JBossDestination;
-import org.jboss.messaging.jms.JBossQueue;
-import org.jboss.messaging.jms.JBossTemporaryQueue;
-import org.jboss.messaging.jms.JBossTemporaryTopic;
-import org.jboss.messaging.jms.JBossTopic;
-import org.jboss.messaging.jms.client.JBossConnection;
-import org.jboss.messaging.jms.client.JBossMessage;
-import org.jboss.messaging.jms.client.JBossSession;
 import static org.jboss.messaging.tests.util.RandomUtil.randomSimpleString;
 import static org.jboss.messaging.tests.util.RandomUtil.randomString;
-import org.jboss.messaging.util.SimpleString;
 
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+
 import javax.jms.BytesMessage;
 import javax.jms.Destination;
 import javax.jms.IllegalStateException;
@@ -79,10 +62,30 @@
 import javax.jms.TopicSession;
 import javax.jms.TransactionInProgressException;
 import javax.transaction.xa.XAResource;
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.List;
 
+import junit.framework.TestCase;
+
+import org.easymock.EasyMock;
+import org.jboss.messaging.core.client.ClientConsumer;
+import org.jboss.messaging.core.client.ClientMessage;
+import org.jboss.messaging.core.client.ClientProducer;
+import org.jboss.messaging.core.client.ClientSession;
+import org.jboss.messaging.core.client.ClientSessionFactory;
+import org.jboss.messaging.core.client.impl.ClientMessageImpl;
+import org.jboss.messaging.core.exception.MessagingException;
+import org.jboss.messaging.core.remoting.impl.ByteBufferWrapper;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionBindingQueryResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionQueueQueryResponseMessage;
+import org.jboss.messaging.jms.JBossDestination;
+import org.jboss.messaging.jms.JBossQueue;
+import org.jboss.messaging.jms.JBossTemporaryQueue;
+import org.jboss.messaging.jms.JBossTemporaryTopic;
+import org.jboss.messaging.jms.JBossTopic;
+import org.jboss.messaging.jms.client.JBossConnection;
+import org.jboss.messaging.jms.client.JBossMessage;
+import org.jboss.messaging.jms.client.JBossSession;
+import org.jboss.messaging.util.SimpleString;
+
 /**
  * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
  * 

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/jms/misc/ManifestTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/jms/misc/ManifestTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/jms/misc/ManifestTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -33,7 +33,6 @@
 
 import junit.framework.TestCase;
 
-import org.jboss.messaging.core.config.impl.ConfigurationImpl;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.server.MessagingServer;
 import org.jboss.messaging.core.server.impl.MessagingServerImpl;

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/jms/referenceable/ConnectionFactoryObjectFactoryTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/jms/referenceable/ConnectionFactoryObjectFactoryTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/jms/referenceable/ConnectionFactoryObjectFactoryTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,18 +22,8 @@
 
 package org.jboss.messaging.tests.unit.jms.referenceable;
 
-import static org.jboss.messaging.tests.util.RandomUtil.randomString;
-
-import java.util.Map;
-
-import javax.naming.Reference;
-
 import junit.framework.TestCase;
 
-import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
-import org.jboss.messaging.jms.client.JBossConnectionFactory;
-import org.jboss.messaging.jms.referenceable.ConnectionFactoryObjectFactory;
-
 /**
  * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
  *

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/jms/server/management/impl/JMSManagementServiceImplTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/jms/server/management/impl/JMSManagementServiceImplTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/jms/server/management/impl/JMSManagementServiceImplTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -32,15 +32,11 @@
 
 import java.util.ArrayList;
 import java.util.List;
-import java.util.Random;
 
-import javax.management.MBeanServer;
-import javax.management.ObjectInstance;
 import javax.management.ObjectName;
 
 import junit.framework.TestCase;
 
-import org.easymock.EasyMock;
 import org.jboss.messaging.core.management.ManagementService;
 import org.jboss.messaging.core.messagecounter.MessageCounter;
 import org.jboss.messaging.core.messagecounter.MessageCounterManager;
@@ -58,11 +54,7 @@
 import org.jboss.messaging.jms.server.management.JMSQueueControlMBean;
 import org.jboss.messaging.jms.server.management.JMSServerControlMBean;
 import org.jboss.messaging.jms.server.management.TopicControlMBean;
-import org.jboss.messaging.jms.server.management.impl.ConnectionFactoryControl;
 import org.jboss.messaging.jms.server.management.impl.JMSManagementServiceImpl;
-import org.jboss.messaging.jms.server.management.impl.JMSQueueControl;
-import org.jboss.messaging.jms.server.management.impl.TopicControl;
-import org.jboss.messaging.tests.util.RandomUtil;
 
 /*
  * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/jms/server/management/impl/JMSServerControlTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/jms/server/management/impl/JMSServerControlTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/jms/server/management/impl/JMSServerControlTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -28,15 +28,9 @@
 import static org.easymock.EasyMock.replay;
 import static org.easymock.EasyMock.verify;
 import static org.jboss.messaging.tests.util.RandomUtil.randomBoolean;
-import static org.jboss.messaging.tests.util.RandomUtil.randomInt;
-import static org.jboss.messaging.tests.util.RandomUtil.randomLong;
 import static org.jboss.messaging.tests.util.RandomUtil.randomString;
 
 import java.lang.management.ManagementFactory;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.atomic.AtomicReference;
 
@@ -47,8 +41,6 @@
 
 import junit.framework.TestCase;
 
-import org.easymock.EasyMock;
-import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
 import org.jboss.messaging.jms.server.JMSServerManager;
 import org.jboss.messaging.jms.server.management.impl.JMSManagementServiceImpl;
 import org.jboss.messaging.jms.server.management.impl.JMSServerControl;

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/util/SimpleStringTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/util/SimpleStringTest.java	2008-10-30 15:54:20 UTC (rev 5221)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/util/SimpleStringTest.java	2008-10-30 16:12:28 UTC (rev 5222)
@@ -22,8 +22,9 @@
 
 package org.jboss.messaging.tests.unit.util;
 
+import static org.jboss.messaging.tests.util.RandomUtil.randomString;
 import junit.framework.TestCase;
-import static org.jboss.messaging.tests.util.RandomUtil.randomString;
+
 import org.jboss.messaging.util.DataConstants;
 import org.jboss.messaging.util.SimpleString;
 




More information about the jboss-cvs-commits mailing list