[jboss-cvs] JBoss Messaging SVN: r4957 - in trunk: src/main/org/jboss/messaging/core/client/impl and 15 other directories.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Tue Sep 16 14:36:20 EDT 2008


Author: timfox
Date: 2008-09-16 14:36:19 -0400 (Tue, 16 Sep 2008)
New Revision: 4957

Added:
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionBrowseMessage.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionConsumerFlowCreditMessage.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionProducerFlowCreditMessage.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionReceiveMessage.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionSendMessage.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/cluster/
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/cluster/ReplicationResponseMessage.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/cluster/SessionReplicateDeliveryMessage.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/cluster/SessionReplicateSendMessage.java
Removed:
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/BrowseMessage.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/ProducerFlowCreditMessage.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/ReceiveMessage.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SendMessage.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionFlowCreditMessage.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionReplicateDeliveryMessage.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionReplicateDeliveryResponseMessage.java
Modified:
   trunk/src/config/log4j.xml
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientBrowserImpl.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/ClientSessionImpl.java
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionPacketHandler.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/remoting/Channel.java
   trunk/src/main/org/jboss/messaging/core/remoting/ConnectionRegistry.java
   trunk/src/main/org/jboss/messaging/core/remoting/RemotingConnection.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/ConnectionRegistryImpl.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/InVMAcceptor.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/invm/InVMRegistry.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/PacketImpl.java
   trunk/src/main/org/jboss/messaging/core/server/MessagingServer.java
   trunk/src/main/org/jboss/messaging/core/server/ServerSession.java
   trunk/src/main/org/jboss/messaging/core/server/impl/DeliveryImpl.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/QueueImpl.java
   trunk/src/main/org/jboss/messaging/core/server/impl/ServerConsumerImpl.java
   trunk/src/main/org/jboss/messaging/core/server/impl/ServerMessageImpl.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/server/impl/ServerSessionPacketHandler.java
   trunk/src/main/org/jboss/messaging/jms/client/JBossSession.java
   trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/DummyInterceptor.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/ReplicationTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/client/impl/ClientBrowserImplTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/client/impl/ClientConsumerImplTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/client/impl/ClientProducerImplTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/client/impl/ClientSessionImplTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/DeliveryImplTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerBrowserImplTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerConsumerPacketHandlerTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerProducerImplTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerProducerPacketHandlerTest.java
   trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerSessionImplTest.java
Log:
failover


Modified: trunk/src/config/log4j.xml
===================================================================
--- trunk/src/config/log4j.xml	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/config/log4j.xml	2008-09-16 18:36:19 UTC (rev 4957)
@@ -22,7 +22,7 @@
            for each test. We need to append if we want to preserve a full testsuite run log.
            Make sure the build script clears this log at the beginning of each run.
       -->
-      <param name="Append" value="true"/>
+      <param name="Append" value="false"/>
       <param name="DatePattern" value="'.'yyyy-MM-dd"/>
 
       <param name="Threshold" value="INFO"/>

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientBrowserImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientBrowserImpl.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientBrowserImpl.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -25,8 +25,8 @@
 import org.jboss.messaging.core.client.ClientMessage;
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.remoting.Channel;
-import org.jboss.messaging.core.remoting.impl.wireformat.BrowseMessage;
-import org.jboss.messaging.core.remoting.impl.wireformat.ReceiveMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionReceiveMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowserCloseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowserHasNextMessageMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowserHasNextMessageResponseMessage;
@@ -132,8 +132,8 @@
    {
       checkClosed();
       
-      BrowseMessage response =
-         (BrowseMessage)channel.sendBlocking(new SessionBrowserNextMessageMessage(id));
+      SessionBrowseMessage response =
+         (SessionBrowseMessage)channel.sendBlocking(new SessionBrowserNextMessageMessage(id));
       
       return response.getClientMessage();
    }

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientConsumerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientConsumerImpl.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientConsumerImpl.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -32,7 +32,7 @@
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.Channel;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionConsumerCloseMessage;
-import org.jboss.messaging.core.remoting.impl.wireformat.SessionFlowCreditMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionConsumerFlowCreditMessage;
 import org.jboss.messaging.util.Future;
 
 /**
@@ -392,7 +392,7 @@
          
          if (creditsToSend >= clientWindowSize)
          {            
-            channel.send(new SessionFlowCreditMessage(id, creditsToSend));
+            channel.send(new SessionConsumerFlowCreditMessage(id, creditsToSend));
             
             creditsToSend = 0;            
          }

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientProducerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientProducerImpl.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientProducerImpl.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -29,7 +29,7 @@
 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.impl.wireformat.SendMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionProducerCloseMessage;
 import org.jboss.messaging.util.SimpleString;
 import org.jboss.messaging.util.TokenBucketLimiter;
@@ -250,7 +250,7 @@
       
       boolean sendBlocking = msg.isDurable() ? blockOnPersistentSend : blockOnNonPersistentSend;
       
-      SendMessage message = new SendMessage(id, msg, sendBlocking);
+      SessionSendMessage message = new SessionSendMessage(id, msg, sendBlocking);
                
       if (sendBlocking)
       {        

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryImpl.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryImpl.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -27,7 +27,6 @@
 import java.util.Set;
 
 import org.jboss.messaging.core.client.ClientSession;
-import org.jboss.messaging.core.client.ClientSessionFactory;
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
@@ -120,7 +119,9 @@
    private volatile boolean failedOver;
 
    private final Set<ClientSessionInternal> sessions = new ConcurrentHashSet<ClientSessionInternal>();
-   
+
+   private volatile boolean sessionsCreated;
+
    // Static
    // ---------------------------------------------------------------------------------------
 
@@ -308,6 +309,11 @@
 
    public void setConnectorFactory(final ConnectorFactory connectorFactory)
    {
+      if (sessionsCreated)
+      {
+         throw new IllegalStateException("Cannot set connector factory after connections have been created");
+      }
+
       this.connectorFactory = connectorFactory;
    }
 
@@ -318,6 +324,11 @@
 
    public void setTransportParams(final Map<String, Object> transportParams)
    {
+      if (sessionsCreated)
+      {
+         throw new IllegalStateException("Cannot set transport params after connections have been created");
+      }
+
       this.transportParams = transportParams;
    }
 
@@ -326,8 +337,13 @@
       return backupConnectorFactory;
    }
 
-   public void setBqackupConnectorFactory(final ConnectorFactory connectorFactory)
+   public void setBackupConnectorFactory(final ConnectorFactory connectorFactory)
    {
+      if (sessionsCreated)
+      {
+         throw new IllegalStateException("Cannot set backup connector factory after connections have been created");
+      }
+
       this.backupConnectorFactory = connectorFactory;
    }
 
@@ -338,6 +354,11 @@
 
    public void setBackupTransportParams(final Map<String, Object> transportParams)
    {
+      if (sessionsCreated)
+      {
+         throw new IllegalStateException("Cannot set backup transport params after connections have been created");
+      }
+
       this.backupTransportParams = transportParams;
    }
 
@@ -393,37 +414,34 @@
 
    private void handleFailover(final MessagingException me)
    {
-      log.info(this + " Connection failure has been detected, initiating failover");
+      log.info("Connection failure has been detected, initiating failover");
 
       if (backupConnectorFactory == null)
       {
          throw new IllegalStateException("Cannot fail-over if backup connector factory is null");
       }
 
-      RemotingConnection liveConnection = connectionRegistry.getConnection(connectorFactory,
-                                                                           transportParams,
-                                                                           pingPeriod,
-                                                                           callTimeout);
-      
+      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);
+         session.handleFailover(backupConnection);
+      }
+
       this.connectorFactory = backupConnectorFactory;
       this.transportParams = backupTransportParams;
 
       this.backupConnectorFactory = null;
       this.backupTransportParams = null;
 
-      RemotingConnection backupConnection = connectionRegistry.getConnection(connectorFactory,
-                                                                             transportParams,
-                                                                             pingPeriod,
-                                                                             callTimeout);
-      
-      //log.info("*** Backup connection is " + System.identityHashCode(liveConnection));
+      failedOver = true;
 
-      for (ClientSessionInternal session : sessions)
-      {
-         session.handleFailover(backupConnection);
-      }
-
-      liveConnection.destroy();
+      log.info("Failover complete");
    }
 
    private ConnectorFactory instantiateConnectorFactory(final String connectorFactoryClassName)
@@ -451,22 +469,19 @@
    {
       Version clientVersion = VersionLoader.load();
 
-      RemotingConnection remotingConnection = null;
+      RemotingConnection connection = null;
       try
       {
-         remotingConnection = connectionRegistry.getConnection(connectorFactory,
-                                                               transportParams,
-                                                               pingPeriod,
-                                                               callTimeout);
-         
+         connection = connectionRegistry.getConnection(connectorFactory, transportParams, pingPeriod, callTimeout);
+
          if (backupConnectorFactory != null)
          {
-            remotingConnection.addFailureListener(this);
+            connection.addFailureListener(this);
          }
 
          String name = UUIDGenerator.getInstance().generateSimpleStringUUID().toString();
 
-         long sessionChannelID = remotingConnection.generateChannelID();
+         long sessionChannelID = connection.generateChannelID();
 
          Packet request = new CreateSessionMessage(name,
                                                    sessionChannelID,
@@ -477,7 +492,7 @@
                                                    autoCommitSends,
                                                    autoCommitAcks);
 
-         Channel channel1 = remotingConnection.getChannel(1, false, -1);
+         Channel channel1 = connection.getChannel(1, false, -1);
 
          Packet packet = channel1.sendBlocking(request);
 
@@ -490,9 +505,9 @@
 
          CreateSessionResponseMessage response = (CreateSessionResponseMessage) packet;
 
-         Channel sessionChannel = remotingConnection.getChannel(sessionChannelID,
-                                                                false,
-                                                                response.getPacketConfirmationBatchSize());
+         Channel sessionChannel = connection.getChannel(sessionChannelID,
+                                                        false,
+                                                        response.getPacketConfirmationBatchSize());
 
          ClientSessionInternal session = new ClientSessionImpl(this,
                                                                name,
@@ -502,7 +517,7 @@
                                                                autoCommitSends,
                                                                autoCommitAcks,
                                                                blockOnAcknowledge,
-                                                               remotingConnection,
+                                                               connection,
                                                                this,
                                                                response.getServerVersion(),
                                                                sessionChannel);
@@ -513,16 +528,17 @@
 
          sessionChannel.setHandler(handler);
 
+         sessionsCreated = true;
+
          return session;
-
       }
       catch (Throwable t)
       {
-         if (remotingConnection != null)
+         if (connection != null)
          {
             try
             {
-               connectionRegistry.returnConnection(remotingConnection.getID());
+               connectionRegistry.returnConnection(connection.getID());
             }
             catch (Throwable ignore)
             {

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -64,7 +64,7 @@
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateProducerResponseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateQueueMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionDeleteQueueMessage;
-import org.jboss.messaging.core.remoting.impl.wireformat.SessionFlowCreditMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionConsumerFlowCreditMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionQueueQueryMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionQueueQueryResponseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionRemoveDestinationMessage;
@@ -372,7 +372,7 @@
       // We even send it if windowSize == -1, since we need to start the
       // consumer
 
-      channel.send(new SessionFlowCreditMessage(consumerID, response.getWindowSize()));
+      channel.send(new SessionConsumerFlowCreditMessage(consumerID, response.getWindowSize()));
 
       return consumer;
    }

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionPacketHandler.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionPacketHandler.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionPacketHandler.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -30,8 +30,8 @@
 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.ProducerFlowCreditMessage;
-import org.jboss.messaging.core.remoting.impl.wireformat.ReceiveMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionProducerFlowCreditMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionReceiveMessage;
 
 /**
  *
@@ -61,7 +61,7 @@
          {
             case SESS_RECEIVETOKENS:
             {
-               ProducerFlowCreditMessage message = (ProducerFlowCreditMessage) packet;
+               SessionProducerFlowCreditMessage message = (SessionProducerFlowCreditMessage) packet;
    
                clientSession.receiveProducerCredits(message.getProducerID(), message.getTokens());
                
@@ -69,7 +69,7 @@
             }
             case SESS_RECEIVE_MSG:
             {
-               ReceiveMessage message = (ReceiveMessage) packet;
+               SessionReceiveMessage message = (SessionReceiveMessage) packet;
       
                clientSession.handleReceiveMessage(message.getConsumerID(), message.getClientMessage());
                

Modified: trunk/src/main/org/jboss/messaging/core/persistence/StorageManager.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/persistence/StorageManager.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/persistence/StorageManager.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -48,6 +48,8 @@
 	
    long generateID();
    
+   void setMaxID(long id);
+   
    long generateTransactionID();
    
       

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-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/persistence/impl/journal/JournalStorageManager.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -189,6 +189,17 @@
 		return idSequence.getAndIncrement();
 	}
 	
+	//Needed for replication
+	
+	//TODO can be optimised
+	public synchronized void setMaxID(final long id)
+	{
+	   if (1 + id > idSequence.get())
+	   {
+	      idSequence.set(id + 1);
+	   }
+	}
+	
 	public long generateTransactionID()
 	{
 		return messageJournal.getTransactionID();

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-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/persistence/impl/nullpm/NullStorageManager.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -138,6 +138,14 @@
 		return messageIDSequence.getAndIncrement();
 	}
 	
+	public synchronized void setMaxID(final long id)
+   {
+      if (1 + id > messageIDSequence.get())
+      {
+         messageIDSequence.set(id + 1);
+      }
+   }
+	
 	public long generateTransactionID()
 	{
 		return transactionIDSequence.getAndIncrement();

Modified: trunk/src/main/org/jboss/messaging/core/remoting/Channel.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/Channel.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/remoting/Channel.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -36,6 +36,8 @@
    void send(Packet packet);
    
    Packet sendBlocking(Packet packet) throws MessagingException;
+   
+   void replicatePacket(Packet packet, Runnable action);
       
    void setHandler(ChannelHandler handler);
    

Modified: trunk/src/main/org/jboss/messaging/core/remoting/ConnectionRegistry.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/ConnectionRegistry.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/remoting/ConnectionRegistry.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -44,4 +44,8 @@
    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/RemotingConnection.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/RemotingConnection.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/remoting/RemotingConnection.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -42,9 +42,9 @@
    
    long generateChannelID();
 
-   public void setBackup(final boolean backup);
+   public void setReplicating(final boolean backup);
    
-   boolean isBackup();
+   boolean isReplicating();
    
    void addFailureListener(FailureListener listener);
 
@@ -58,5 +58,5 @@
    
    boolean isExpired(final long now);
    
-   void startPinger();
+   void startPinger();      
 }

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/ConnectionRegistryImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/ConnectionRegistryImpl.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/ConnectionRegistryImpl.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -195,6 +195,19 @@
          return 0;
       }
    }
+   
+   public void clear()
+   {
+      connections.clear();
+   }
+   
+   public void dump()
+   {
+      for (ConnectionHolder holder: connections.values())
+      {
+         log.info("connection " + System.identityHashCode(holder.connection) + " count " + holder.count);
+      }
+   }
 
    // Constructors --------------------------------------------------
 

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingConnectionImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingConnectionImpl.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingConnectionImpl.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -30,6 +30,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.REPLICATION_RESP;
 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;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_BINDINGQUERY;
@@ -60,6 +61,8 @@
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_RECEIVE_MSG;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_RECOVER;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_REMOVE_DESTINATION;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_REPLICATE_DELIVERY;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_REPLICATE_SEND;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_ROLLBACK;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_SEND;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_START;
@@ -83,10 +86,8 @@
 
 import java.util.ArrayList;
 import java.util.HashSet;
-import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
-import java.util.Queue;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentLinkedQueue;
@@ -106,7 +107,6 @@
 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.wireformat.BrowseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.CreateSessionMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.CreateSessionResponseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.MessagingExceptionMessage;
@@ -114,15 +114,13 @@
 import org.jboss.messaging.core.remoting.impl.wireformat.PacketsConfirmedMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.Ping;
 import org.jboss.messaging.core.remoting.impl.wireformat.Pong;
-import org.jboss.messaging.core.remoting.impl.wireformat.ProducerFlowCreditMessage;
 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.ReceiveMessage;
-import org.jboss.messaging.core.remoting.impl.wireformat.SendMessage;
 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;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionBindingQueryResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowserCloseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowserHasNextMessageMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowserHasNextMessageResponseMessage;
@@ -130,6 +128,7 @@
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowserResetMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionCancelMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionConsumerCloseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionConsumerFlowCreditMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateBrowserMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateConsumerMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateConsumerResponseMessage;
@@ -137,14 +136,14 @@
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateProducerResponseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateQueueMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionDeleteQueueMessage;
-import org.jboss.messaging.core.remoting.impl.wireformat.SessionFlowCreditMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionNullResponseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionProducerCloseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionProducerFlowCreditMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionQueueQueryMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionQueueQueryResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionReceiveMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionRemoveDestinationMessage;
-import org.jboss.messaging.core.remoting.impl.wireformat.SessionReplicateDeliveryMessage;
-import org.jboss.messaging.core.remoting.impl.wireformat.SessionReplicateDeliveryResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXACommitMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAEndMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAForgetMessage;
@@ -158,6 +157,9 @@
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXASetTimeoutMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXASetTimeoutResponseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAStartMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.cluster.ReplicationResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.cluster.SessionReplicateDeliveryMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.cluster.SessionReplicateSendMessage;
 import org.jboss.messaging.core.remoting.spi.Connection;
 import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
 import org.jboss.messaging.util.ExecutorFactory;
@@ -218,7 +220,7 @@
 
    private final RemotingConnection replicatingConnection;
 
-   private volatile boolean backup;
+   private volatile boolean replicating;
 
    private final boolean client;
 
@@ -233,6 +235,8 @@
    // 1 is for session creation and attachment
    private final IDGenerator idGenerator = new IDGenerator(10);
 
+   private final Object failLock = new Object();
+
    // Constructors
    // ---------------------------------------------------------------------------------
 
@@ -246,6 +250,7 @@
                                  final boolean client)
 
    {
+      //log.info("creating connection " + System.identityHashCode(this) + " client " + client);
       this.transportConnection = transportConnection;
 
       this.blockingCallTimeout = blockingCallTimeout;
@@ -265,7 +270,7 @@
 
       this.client = client;
 
-      writePackets = client; // Gets changed when setBackup is called
+      writePackets = client; // Gets changed when setReplicating is called
 
       this.pingPeriod = pingPeriod;
 
@@ -285,7 +290,7 @@
       {
          pinger = new Pinger();
 
-         expirePeriod = (long) (EXPIRE_FACTOR * pingPeriod);
+         expirePeriod = (long)(EXPIRE_FACTOR * pingPeriod);
 
          future = pingExecutor.scheduleWithFixedDelay(pinger, 0, pingPeriod, TimeUnit.MILLISECONDS);
       }
@@ -320,16 +325,18 @@
    }
 
    // This is a bit hacky - can we somehow do this in the constructor?
-   public void setBackup(final boolean backup)
+   public void setReplicating(final boolean replicating)
    {
-      this.backup = backup;
+      this.replicating = replicating;
 
-      writePackets = client || !backup;
+      //log.info("set replicating " + System.identityHashCode(this) + " replicating " + replicating);
+
+      writePackets = client || !replicating;
    }
 
-   public boolean isBackup()
+   public boolean isReplicating()
    {
-      return backup;
+      return replicating;
    }
 
    public void addFailureListener(final FailureListener listener)
@@ -361,8 +368,6 @@
     * This can be called concurrently by more than one thread so needs to be locked
     */
 
-   private final Object failLock = new Object();
-
    public void fail(final MessagingException me)
    {
       synchronized (failLock)
@@ -445,40 +450,16 @@
 
    public synchronized void bufferReceived(final Object connectionID, final MessagingBuffer buffer)
    {
-      // log.info("** buffer received, client " + client + " backup " + backup);
       final Packet packet = decode(buffer);
 
       final long channelID = packet.getChannelID();
 
       final ChannelImpl channel = channels.get(channelID);
 
-      if (channel == null)
+      if (channel != null)
       {
-         // if (packet.getType() == PacketImpl.SESS_PACKETS_CONFIRMED)
-         // {
-         // /*
-         // Packets confirmed can arrive after channel has been closed, e.g.
-         // Sending session.close with packet confirmation batch size = 1
-         // Session close gets replicated to backup, session closed on backup,
-         // and null response written back to client
-         // null response arrives on client and packet confirmation sent to
-         // backup
-         // null response arrives on backup but session is already closed
-         // */
-         // return;
-         // }
-         // else
-         // {
-         // throw new IllegalArgumentException("Cannot handle packet " + packet
-         // +
-         // " no channel is registered with id " +
-         // channelID);
-         // }
-
-         return;
+         channel.handlePacket(packet);
       }
-
-      channel.handlePacket(packet);
    }
 
    // Package protected
@@ -494,9 +475,7 @@
    {
       if (destroyed)
       {
-         // return;
-
-         throw new IllegalStateException("Cannot write to connection - it is destroyed");
+         return;
       }
 
       final MessagingBuffer buffer = transportConnection.createBuffer(PacketImpl.INITIAL_BUFFER_SIZE);
@@ -641,7 +620,7 @@
          }
          case PacketImpl.SESS_BROWSER_MESSAGE:
          {
-            packet = new BrowseMessage();
+            packet = new SessionBrowseMessage();
             break;
          }
          case SESS_BROWSER_RESET:
@@ -756,22 +735,22 @@
          }
          case SESS_FLOWTOKEN:
          {
-            packet = new SessionFlowCreditMessage();
+            packet = new SessionConsumerFlowCreditMessage();
             break;
          }
          case SESS_SEND:
          {
-            packet = new SendMessage();
+            packet = new SessionSendMessage();
             break;
          }
          case SESS_RECEIVETOKENS:
          {
-            packet = new ProducerFlowCreditMessage();
+            packet = new SessionProducerFlowCreditMessage();
             break;
          }
          case SESS_RECEIVE_MSG:
          {
-            packet = new ReceiveMessage();
+            packet = new SessionReceiveMessage();
             break;
          }
          case SESS_PACKETS_CONFIRMED:
@@ -804,16 +783,21 @@
             packet = new SessionNullResponseMessage();
             break;
          }
-         case PacketImpl.SESS_REPLICATE_DELIVERY:
+         case SESS_REPLICATE_DELIVERY:
          {
             packet = new SessionReplicateDeliveryMessage();
             break;
          }
-         case PacketImpl.SESS_REPLICATE_DELIVERY_RESP:
+         case REPLICATION_RESP:
          {
-            packet = new SessionReplicateDeliveryResponseMessage();
+            packet = new ReplicationResponseMessage();
             break;
          }
+         case SESS_REPLICATE_SEND:
+         {
+            packet = new SessionReplicateSendMessage();
+            break;
+         }
          default:
          {
             throw new IllegalArgumentException("Invalid type: " + packetType);
@@ -828,8 +812,6 @@
    // Inner classes
    // --------------------------------------------------------------------------------
 
-   // FIXME - improve locking on this class
-
    // Needs to be static so we can re-assign it to another remotingconnection
    private static class ChannelImpl implements Channel
    {
@@ -858,6 +840,10 @@
 
       private volatile RemotingConnectionImpl connection;
 
+      private volatile boolean closed;
+
+      private final java.util.Queue<Runnable> replicationResponseActions = new ConcurrentLinkedQueue<Runnable>();
+
       private ChannelImpl(final RemotingConnectionImpl connection,
                           final long id,
                           final boolean ordered,
@@ -878,7 +864,7 @@
 
          this.packetConfirmationBatchSize = packetConfirmationBatchSize;
 
-         if (packetConfirmationBatchSize != -1 && (connection.client && !connection.backup || !connection.client && connection.replicatingConnection == null))
+         if (packetConfirmationBatchSize != -1 && (connection.client && !connection.replicating || !connection.client && connection.replicatingConnection == null))
          {
             resendCache = new ConcurrentLinkedQueue<Packet>();
 
@@ -901,13 +887,6 @@
          }
       }
 
-      public void setReplicatingChannel(final Channel replicatingChannel)
-      {
-         this.replicatingChannel = replicatingChannel;
-
-         replicatingChannel.setHandler(new ReplicatedPacketsConfirmedChannelHandler());
-      }
-
       public long getID()
       {
          return id;
@@ -932,8 +911,11 @@
                addToCache(packet);
             }
 
-            if (connection.writePackets || packet.getType() == PacketImpl.SESS_PACKETS_CONFIRMED ||
-                packet.getType() == PacketImpl.SESS_REPLICATE_DELIVERY_RESP)
+            final byte packetType = packet.getType();
+
+            if (connection.writePackets || packetType == SESS_PACKETS_CONFIRMED ||
+                packetType == REPLICATION_RESP ||
+                packetType == PONG)
             {
                connection.doWrite(packet);
             }
@@ -995,7 +977,7 @@
 
                if (response.getType() == PacketImpl.EXCEPTION)
                {
-                  final MessagingExceptionMessage mem = (MessagingExceptionMessage) response;
+                  final MessagingExceptionMessage mem = (MessagingExceptionMessage)response;
 
                   throw mem.getException();
                }
@@ -1011,6 +993,28 @@
          }
       }
 
+      public void replicatePacket(final Packet packet, final Runnable action)
+      {
+         if (replicatingChannel != null)
+         {
+            replicationResponseActions.add(action);
+
+            replicatingChannel.send(packet);
+         }
+      }
+
+      private void replicationResponseReceived()
+      {
+         Runnable action = replicationResponseActions.poll();
+
+         if (action == null)
+         {
+            throw new IllegalStateException("Cannot find action to run");
+         }
+
+         action.run();
+      }
+
       public void setHandler(final ChannelHandler handler)
       {
          this.handler = handler;
@@ -1018,6 +1022,11 @@
 
       public void close()
       {
+         if (closed)
+         {
+            return;
+         }
+
          if (!connection.destroyed && connection.channels.remove(id) == null)
          {
             throw new IllegalArgumentException("Cannot find channel with id " + id + " to close");
@@ -1028,14 +1037,7 @@
             replicatingChannel.close();
          }
 
-         if (resendCache != null)
-         {
-            // log.info(System.identityHashCode(this) + " backup:" + backup
-            // + " client:" + client + " replicatingconn:" +
-            // replicatingConnection +
-            // " pcbs:" + packetConfirmationBatchSize + " channelid:" + id +
-            // " at close resend cache size is " + this.resendCache.size());
-         }
+         closed = true;
       }
 
       public Channel getReplicatingChannel()
@@ -1045,8 +1047,9 @@
 
       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
+         // Needs to synchronize on the connection to make sure no packets from
+         // the old connection
+         // get processed after transfer has occurred
          synchronized (connection)
          {
             connection.channels.remove(id);
@@ -1062,13 +1065,13 @@
 
                if (!ok)
                {
-                  throw new IllegalStateException("Timed out waiting for executor to complete");
+                  log.warn("Timed out waiting for executor to complete");
                }
             }
 
             // And switch it
 
-            final RemotingConnectionImpl rnewConnection = (RemotingConnectionImpl) newConnection;
+            final RemotingConnectionImpl rnewConnection = (RemotingConnectionImpl)newConnection;
 
             rnewConnection.channels.put(id, this);
 
@@ -1082,21 +1085,10 @@
       {
          clearUpTo(otherLastReceivedCommandID);
 
-         Packet packet = null;
-
-         int count = 0;
-         
-         //log.info("replaying commands " + resendCache.size());
-
-         Queue<Packet> copy = new LinkedList<Packet>(resendCache);
-         while ((packet = copy.poll()) != null)
+         for (final Packet packet : resendCache)
          {
             connection.doWrite(packet);
-
-            count++;
          }
-         
-         //log.info("replayed commands, size is now " + resendCache.size());
 
          return lastReceivedCommandID;
       }
@@ -1117,7 +1109,7 @@
          {
             if (resendCache != null)
             {
-               final PacketsConfirmedMessage msg = (PacketsConfirmedMessage) packet;
+               final PacketsConfirmedMessage msg = (PacketsConfirmedMessage)packet;
 
                if (executor == null)
                {
@@ -1147,11 +1139,6 @@
          }
          else
          {
-            if (replicatingChannel != null && packet.getType() != PacketImpl.PING)
-            {
-               replicatingChannel.send(packet);
-            }
-
             if (connection.interceptors != null)
             {
                for (final Interceptor interceptor : connection.interceptors)
@@ -1192,6 +1179,8 @@
                   checkConfirmation(packet);
 
                   handler.handlePacket(packet);
+
+                  checkSendReplicationResponse(packet);
                }
                else
                {
@@ -1202,6 +1191,8 @@
                         checkConfirmation(packet);
 
                         handler.handlePacket(packet);
+
+                        checkSendReplicationResponse(packet);
                      }
                   });
                }
@@ -1213,17 +1204,24 @@
          }
       }
 
+      private void checkSendReplicationResponse(Packet packet)
+      {
+         if (connection.replicating && !connection.client &&
+             packet.getType() != PacketImpl.PING &&
+             packet.getType() != PacketImpl.PONG)
+         {
+            Packet response = new ReplicationResponseMessage();
+
+            response.setChannelID(id);
+
+            connection.doWrite(response);
+         }
+      }
+
       private void checkConfirmation(final Packet packet)
       {
          if (packet.isUsesConfirmations() && resendCache != null)
          {
-            // log.info(System.identityHashCode(connection) + " client " +
-            // connection.client +
-            // " backup " +
-            // connection.backup +
-            // " checking confirmation for packet " +
-            // packet.getType());
-
             lastReceivedCommandID++;
 
             if (lastReceivedCommandID == nextConfirmation)
@@ -1237,39 +1235,18 @@
                connection.doWrite(confirmed);
             }
          }
+
       }
 
       private void addToCache(final Packet packet)
       {
          resendCache.add(packet);
-
-//         log.info(System.identityHashCode(connection) + ":" +
-//                  System.identityHashCode(this) +
-//                  "client " +
-//                  connection.client +
-//                  " backup " +
-//                  connection.backup +
-//                  " addtocache cache size now " +
-//                  resendCache.size());
       }
 
       private void clearUpTo(final int lastReceivedCommandID)
       {
          final int numberToClear = 1 + lastReceivedCommandID - firstStoredCommandID;
 
-//         log.info(System.identityHashCode(connection) + ":" +
-//                  System.identityHashCode(this) +
-//                  " client " +
-//                  connection.client +
-//                  " backup " +
-//                  connection.backup +
-//                  " clearupto " +
-//                  lastReceivedCommandID +
-//                  " numberToClear " +
-//                  numberToClear +
-//                  " cache size " +
-//                  resendCache.size());
-
          if (numberToClear == -1)
          {
             throw new IllegalArgumentException("Invalid lastReceivedCommandID: " + lastReceivedCommandID);
@@ -1284,8 +1261,6 @@
                throw new IllegalStateException("Can't find packet to clear");
             }
          }
-         
-         //log.info("There are now "+ resendCache.size());
 
          firstStoredCommandID += numberToClear;
       }
@@ -1299,10 +1274,9 @@
                // Send it straight back to the client
                connection.doWrite(packet);
             }
-            else if (packet.getType() == PacketImpl.SESS_REPLICATE_DELIVERY_RESP)
+            else if (packet.getType() == REPLICATION_RESP)
             {
-               // Send it straight to the server handler
-               handler.handlePacket(packet);
+               replicationResponseReceived();
             }
             else
             {
@@ -1331,7 +1305,7 @@
 
          // Send ping
          final Packet ping = new Ping(expirePeriod);
-
+   
          pingChannel.send(ping);
       }
    }
@@ -1349,11 +1323,11 @@
             if (stopPinging)
             {
                future.cancel(true);
-            }
+            }           
          }
          else if (type == PING)
          {
-            expireTime = System.currentTimeMillis() + ((Ping) packet).getExpirePeriod();
+            expireTime = System.currentTimeMillis() + ((Ping)packet).getExpirePeriod();
 
             // Parameter is placeholder for future
             final Packet pong = new Pong(-1);

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingServiceImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingServiceImpl.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingServiceImpl.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -249,7 +249,7 @@
                                     replicatingConnection,
                                     false);
       
-      rc.setBackup(backup);
+      rc.setReplicating(backup);
             
       Channel channel1 = rc.getChannel(1, false, -1);
                   
@@ -264,10 +264,14 @@
 
    public void connectionDestroyed(Object connectionID)
    {
-      if (connections.remove(connectionID) == null)
+      RemotingConnection conn = connections.remove(connectionID);
+      
+      if (conn == null)
       {
          throw new IllegalStateException("Cannot find connection with id " + connectionID);
-      }
+      }            
+      
+      conn.destroy();
    }
 
    public void connectionException(Object connectionID, MessagingException me)
@@ -352,12 +356,10 @@
       {
          RemotingConnection conn = connections.get(connectionID);
          
-         if (conn == null)
+         if (conn != null)
          {
-            throw new IllegalStateException("Cannot find connection with id " + connectionID);
+            conn.bufferReceived(connectionID, buffer);
          }
-         
-         conn.bufferReceived(connectionID, buffer);
       }
    }
 

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/invm/InVMAcceptor.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/invm/InVMAcceptor.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/invm/InVMAcceptor.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -150,15 +150,13 @@
 
       public void connectionDestroyed(final Object connectionID)
       {
-         if (connections.remove(connectionID) == null)
-         {
-            throw new IllegalArgumentException("Cannot find connection with id " + connectionID + " to remove");
+         if (connections.remove(connectionID) != null)
+         {                    
+            //Remove on the other side too
+            connector.disconnect((String)connectionID);
+            
+            listener.connectionDestroyed(connectionID);
          }
-         
-         //Remove on the other side too
-         connector.disconnect((String)connectionID);
-         
-         listener.connectionDestroyed(connectionID);
       }
 
       public void connectionException(final Object connectionID, final MessagingException me)

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/invm/InVMRegistry.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/invm/InVMRegistry.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/invm/InVMRegistry.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -61,4 +61,14 @@
    {
       return acceptors.get(id);
    }
+   
+   public void clear()
+   {
+      this.acceptors.clear();
+   }
+   
+   public int size()
+   {
+      return this.acceptors.size();
+   }
 }

Deleted: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/BrowseMessage.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/BrowseMessage.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/BrowseMessage.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -1,107 +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.wireformat;
-
-import org.jboss.messaging.core.client.ClientMessage;
-import org.jboss.messaging.core.client.impl.ClientMessageImpl;
-import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
-import org.jboss.messaging.core.server.ServerMessage;
-
-/**
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- * 
- * @version <tt>$Revision$</tt>
- */
-public class BrowseMessage extends PacketImpl
-{
-   // Constants -----------------------------------------------------
-   
-   private static final Logger log = Logger.getLogger(ReceiveMessage.class);
-
-   // Attributes ----------------------------------------------------
-
-   private ClientMessage clientMessage;
-   
-   private ServerMessage serverMessage;
-
-
-   // Static --------------------------------------------------------
-
-   // Constructors --------------------------------------------------
-   
-   public BrowseMessage(final ServerMessage message)
-   {
-      super(SESS_BROWSER_MESSAGE);
-      
-      this.serverMessage = message;
-      
-      this.clientMessage = null;
-   }
-   
-   public BrowseMessage()
-   {
-      super(SESS_BROWSER_MESSAGE);
-   }
-
-   // Public --------------------------------------------------------
-
-   public boolean isResponse()
-   {
-      return true;
-   }
-   
-   public ClientMessage getClientMessage()
-   {
-      return clientMessage;
-   }
-   
-   public ServerMessage getServerMessage()
-   {
-      return serverMessage;
-   }
-
-   public void encodeBody(final MessagingBuffer buffer)
-   {
-      serverMessage.encode(buffer);
-   }
-   
-   public void decodeBody(final MessagingBuffer buffer)
-   {
-      //TODO can be optimised
-      
-      clientMessage = new ClientMessageImpl();
-      
-      clientMessage.decode(buffer);
-      
-      clientMessage.getBody().flip();
-   }
-
-   // Package protected ---------------------------------------------
-
-   // Protected -----------------------------------------------------
-
-   // Private -------------------------------------------------------
-
-   // Inner classes -------------------------------------------------
-}

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-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/PacketImpl.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -51,6 +51,7 @@
       
    public static final byte PING = 10;
    public static final byte PONG = 11;
+   public static final byte REPLICATION_RESP = 12;
    
    // Miscellaneous   
    public static final byte EXCEPTION = 20;   
@@ -114,8 +115,8 @@
    public static final byte SESS_RECEIVE_MSG = 89;   
    public static final byte SESS_PACKETS_CONFIRMED = 90;
    public static final byte SESS_NULL_RESPONSE = 91;
-   public static final byte SESS_REPLICATE_DELIVERY = 92;
-   public static final byte SESS_REPLICATE_DELIVERY_RESP = 93;
+   public static final byte SESS_REPLICATE_DELIVERY = 92;   
+   public static final byte SESS_REPLICATE_SEND = 93;
    
    // Static --------------------------------------------------------
 

Deleted: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/ProducerFlowCreditMessage.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/ProducerFlowCreditMessage.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/ProducerFlowCreditMessage.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -1,114 +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.wireformat;
-
-import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
-
-/**
- * 
- * A ProducerFlowCreditMessage
- * 
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- *
- */
-public class ProducerFlowCreditMessage extends PacketImpl
-{
-   // Constants -----------------------------------------------------
-
-   // Attributes ----------------------------------------------------
-
-   private long producerID;
-   
-   private int credits;
-
-   // Static --------------------------------------------------------
-
-   // Constructors --------------------------------------------------
-
-   public ProducerFlowCreditMessage(final long producerID, final int credits)
-   {
-      super(SESS_RECEIVETOKENS);
-
-      this.producerID = producerID;
-      
-      this.credits = credits;
-   }
-   
-   public ProducerFlowCreditMessage()
-   {
-      super(SESS_RECEIVETOKENS);
-   }
-
-   // Public --------------------------------------------------------
-
-   public long getProducerID()
-   {
-      return producerID;
-   }
-   
-   public int getTokens()
-   {
-      return credits;
-   }
-   
-   public void encodeBody(final MessagingBuffer buffer)
-   {
-      buffer.putLong(producerID);
-      buffer.putInt(credits);
-   }
-   
-   public void decodeBody(final MessagingBuffer buffer)
-   {
-      producerID = buffer.getLong();
-      credits = buffer.getInt();
-   }
-
-   @Override
-   public String toString()
-   {
-      StringBuffer buf = new StringBuffer(getParentString());
-      buf.append(", producerID=" + producerID + ", credits=" + credits);
-      buf.append("]");
-      return buf.toString();
-   }
-   
-   public boolean equals(Object other)
-   {
-      if (other instanceof ProducerFlowCreditMessage == false)
-      {
-         return false;
-      }
-            
-      ProducerFlowCreditMessage r = (ProducerFlowCreditMessage)other;
-      
-      return super.equals(other) && this.credits == r.credits && this.producerID == r.producerID;
-   }
-
-   // Package protected ---------------------------------------------
-
-   // Protected -----------------------------------------------------
-
-   // Private -------------------------------------------------------
-
-   // Inner classes -------------------------------------------------
-}

Deleted: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/ReceiveMessage.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/ReceiveMessage.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/ReceiveMessage.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -1,137 +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.wireformat;
-
-import org.jboss.messaging.core.client.ClientMessage;
-import org.jboss.messaging.core.client.impl.ClientMessageImpl;
-import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
-import org.jboss.messaging.core.server.ServerMessage;
-
-/**
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- * @author <a href="mailto:ovidiu at feodorov.com">Ovidiu Feodorov</a>
- * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
- * 
- * @version <tt>$Revision$</tt>
- */
-public class ReceiveMessage extends PacketImpl
-{
-   // Constants -----------------------------------------------------
-   
-   private static final Logger log = Logger.getLogger(ReceiveMessage.class);
-
-   // Attributes ----------------------------------------------------
-
-   private long consumerID;
-   
-   private ClientMessage clientMessage;
-   
-   private ServerMessage serverMessage;
-   
-   private int deliveryCount;
-   
-   private long deliveryID;
-
-   // Static --------------------------------------------------------
-
-   // Constructors --------------------------------------------------
-   
-   public ReceiveMessage(final long consumerID, final ServerMessage message, final int deliveryCount, final long deliveryID)
-   {
-      super(SESS_RECEIVE_MSG);
-      
-      this.consumerID = consumerID;
-
-      this.serverMessage = message;
-      
-      this.clientMessage = null;
-      
-      this.deliveryCount = deliveryCount;
-      
-      this.deliveryID = deliveryID;
-   }
-   
-   public ReceiveMessage()
-   {
-      super(SESS_RECEIVE_MSG);
-   }
-
-   // Public --------------------------------------------------------
-
-   public long getConsumerID()
-   {
-      return consumerID;
-   }
-   
-   public ClientMessage getClientMessage()
-   {
-      return clientMessage;
-   }
-   
-   public ServerMessage getServerMessage()
-   {
-      return serverMessage;
-   }
-
-   public int getDeliveryCount()
-   {
-      return deliveryCount;
-   }
-   
-   public long getDeliveryID()
-   {
-      return deliveryID;
-   }
-   
-   public void encodeBody(final MessagingBuffer buffer)
-   {
-      buffer.putLong(consumerID);
-      buffer.putInt(deliveryCount);
-      buffer.putLong(deliveryID);
-      serverMessage.encode(buffer);
-   }
-   
-   public void decodeBody(final MessagingBuffer buffer)
-   {
-      //TODO can be optimised
-      
-      consumerID = buffer.getLong();
-      deliveryCount = buffer.getInt();
-      deliveryID = buffer.getLong();
-      
-      clientMessage = new ClientMessageImpl(deliveryCount, deliveryID);
-      
-      clientMessage.decode(buffer);
-      
-      clientMessage.getBody().flip();
-   }
-
-   // Package protected ---------------------------------------------
-
-   // Protected -----------------------------------------------------
-
-   // Private -------------------------------------------------------
-
-   // Inner classes -------------------------------------------------
-}

Deleted: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SendMessage.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SendMessage.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SendMessage.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -1,135 +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.wireformat;
-
-import org.jboss.messaging.core.client.ClientMessage;
-import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
-import org.jboss.messaging.core.server.ServerMessage;
-import org.jboss.messaging.core.server.impl.ServerMessageImpl;
-
-/**
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
- * 
- * @version <tt>$Revision$</tt>
- */
-public class SendMessage extends PacketImpl
-{
-   // Constants -----------------------------------------------------
-
-   private static final Logger log = Logger.getLogger(SendMessage.class);
-   
-   // Attributes ----------------------------------------------------
-
-   private long producerID;
-   
-   private ClientMessage clientMessage;
-   
-   private ServerMessage serverMessage;
-   
-   private boolean requiresResponse;
-
-   // Static --------------------------------------------------------
-
-   // Constructors --------------------------------------------------
-
-   public SendMessage(final long producerID, final ClientMessage message, final boolean requiresResponse)
-   {
-      super(SESS_SEND);
-
-      this.producerID = producerID;
-      
-      this.clientMessage = message;
-      
-      this.requiresResponse = requiresResponse;
-   }
-      
-   public SendMessage()
-   {
-      super(SESS_SEND);
-   }
-
-   // Public --------------------------------------------------------
-
-   public long getProducerID()
-   {
-      return producerID;
-   }
-   
-   public ClientMessage getClientMessage()
-   {
-      return clientMessage;
-   }
-   
-   public ServerMessage getServerMessage()
-   {
-      return serverMessage;
-   }
-   
-   public boolean isRequiresResponse()
-   {
-      return requiresResponse;
-   }
-   
-   public void encodeBody(final MessagingBuffer buffer)
-   {
-      buffer.putLong(producerID);      
-      
-      if (clientMessage != null)
-      {
-         clientMessage.encode(buffer);
-      }
-      else
-      {
-         //If we're replicating a buffer to a backup node then we encode the serverMessage not the clientMessage
-         serverMessage.encode(buffer);
-      }
-      
-      buffer.putBoolean(requiresResponse);
-   }
-   
-   public void decodeBody(final MessagingBuffer buffer)
-   {
-      //TODO can be optimised
-      
-      producerID = buffer.getLong();
-                  
-      serverMessage = new ServerMessageImpl();
-      
-      serverMessage.decode(buffer);
-      
-      serverMessage.getBody().flip();
-      
-      requiresResponse = buffer.getBoolean();
-   }
-
-
-   // Package protected ---------------------------------------------
-
-   // Protected -----------------------------------------------------
-
-   // Private -------------------------------------------------------
-
-   // Inner classes -------------------------------------------------
-}

Copied: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionBrowseMessage.java (from rev 4941, trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/BrowseMessage.java)
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionBrowseMessage.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionBrowseMessage.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -0,0 +1,107 @@
+/*
+ * 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.wireformat;
+
+import org.jboss.messaging.core.client.ClientMessage;
+import org.jboss.messaging.core.client.impl.ClientMessageImpl;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
+import org.jboss.messaging.core.server.ServerMessage;
+
+/**
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * 
+ * @version <tt>$Revision$</tt>
+ */
+public class SessionBrowseMessage extends PacketImpl
+{
+   // Constants -----------------------------------------------------
+   
+   private static final Logger log = Logger.getLogger(SessionReceiveMessage.class);
+
+   // Attributes ----------------------------------------------------
+
+   private ClientMessage clientMessage;
+   
+   private ServerMessage serverMessage;
+
+
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+   
+   public SessionBrowseMessage(final ServerMessage message)
+   {
+      super(SESS_BROWSER_MESSAGE);
+      
+      this.serverMessage = message;
+      
+      this.clientMessage = null;
+   }
+   
+   public SessionBrowseMessage()
+   {
+      super(SESS_BROWSER_MESSAGE);
+   }
+
+   // Public --------------------------------------------------------
+
+   public boolean isResponse()
+   {
+      return true;
+   }
+   
+   public ClientMessage getClientMessage()
+   {
+      return clientMessage;
+   }
+   
+   public ServerMessage getServerMessage()
+   {
+      return serverMessage;
+   }
+
+   public void encodeBody(final MessagingBuffer buffer)
+   {
+      serverMessage.encode(buffer);
+   }
+   
+   public void decodeBody(final MessagingBuffer buffer)
+   {
+      //TODO can be optimised
+      
+      clientMessage = new ClientMessageImpl();
+      
+      clientMessage.decode(buffer);
+      
+      clientMessage.getBody().flip();
+   }
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   // Inner classes -------------------------------------------------
+}

Copied: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionConsumerFlowCreditMessage.java (from rev 4941, trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionFlowCreditMessage.java)
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionConsumerFlowCreditMessage.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionConsumerFlowCreditMessage.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -0,0 +1,110 @@
+/*
+ * 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.wireformat;
+
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
+
+/**
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>.
+ * 
+ * @version <tt>$Revision$</tt>
+ */
+public class SessionConsumerFlowCreditMessage extends PacketImpl
+{
+   // Constants -----------------------------------------------------
+
+   // Attributes ----------------------------------------------------
+
+   private long consumerID;
+   
+   private int credits;
+   
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   public SessionConsumerFlowCreditMessage(final long consumerID, final int credits)
+   {
+      super(SESS_FLOWTOKEN);
+
+      this.consumerID = consumerID;
+      
+      this.credits = credits;
+   }
+   
+   public SessionConsumerFlowCreditMessage()
+   {
+      super(SESS_FLOWTOKEN);
+   }
+
+   // Public --------------------------------------------------------
+
+   public long getConsumerID()
+   {
+      return consumerID;
+   }
+   
+   public int getCredits()
+   {
+      return credits;
+   }
+   
+   public void encodeBody(final MessagingBuffer buffer)
+   {
+      buffer.putLong(consumerID);
+      buffer.putInt(credits);
+   }
+   
+   public void decodeBody(final MessagingBuffer buffer)
+   {
+      consumerID = buffer.getLong();
+      credits = buffer.getInt();
+   }
+
+   @Override
+   public String toString()
+   {
+      return getParentString() + ", consumerID=" + consumerID + ", credits=" + credits + "]";
+   }
+   
+   public boolean equals(Object other)
+   {
+      if (other instanceof SessionConsumerFlowCreditMessage == false)
+      {
+         return false;
+      }
+            
+      SessionConsumerFlowCreditMessage r = (SessionConsumerFlowCreditMessage)other;
+      
+      return super.equals(other) && this.credits == r.credits
+       && this.consumerID == r.consumerID;
+   }
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   // Inner classes -------------------------------------------------
+}

Deleted: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionFlowCreditMessage.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionFlowCreditMessage.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionFlowCreditMessage.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -1,110 +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.wireformat;
-
-import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
-
-/**
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>.
- * 
- * @version <tt>$Revision$</tt>
- */
-public class SessionFlowCreditMessage extends PacketImpl
-{
-   // Constants -----------------------------------------------------
-
-   // Attributes ----------------------------------------------------
-
-   private long consumerID;
-   
-   private int credits;
-   
-   // Static --------------------------------------------------------
-
-   // Constructors --------------------------------------------------
-
-   public SessionFlowCreditMessage(final long consumerID, final int credits)
-   {
-      super(SESS_FLOWTOKEN);
-
-      this.consumerID = consumerID;
-      
-      this.credits = credits;
-   }
-   
-   public SessionFlowCreditMessage()
-   {
-      super(SESS_FLOWTOKEN);
-   }
-
-   // Public --------------------------------------------------------
-
-   public long getConsumerID()
-   {
-      return consumerID;
-   }
-   
-   public int getCredits()
-   {
-      return credits;
-   }
-   
-   public void encodeBody(final MessagingBuffer buffer)
-   {
-      buffer.putLong(consumerID);
-      buffer.putInt(credits);
-   }
-   
-   public void decodeBody(final MessagingBuffer buffer)
-   {
-      consumerID = buffer.getLong();
-      credits = buffer.getInt();
-   }
-
-   @Override
-   public String toString()
-   {
-      return getParentString() + ", consumerID=" + consumerID + ", credits=" + credits + "]";
-   }
-   
-   public boolean equals(Object other)
-   {
-      if (other instanceof SessionFlowCreditMessage == false)
-      {
-         return false;
-      }
-            
-      SessionFlowCreditMessage r = (SessionFlowCreditMessage)other;
-      
-      return super.equals(other) && this.credits == r.credits
-       && this.consumerID == r.consumerID;
-   }
-   // Package protected ---------------------------------------------
-
-   // Protected -----------------------------------------------------
-
-   // Private -------------------------------------------------------
-
-   // Inner classes -------------------------------------------------
-}

Copied: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionProducerFlowCreditMessage.java (from rev 4941, trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/ProducerFlowCreditMessage.java)
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionProducerFlowCreditMessage.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionProducerFlowCreditMessage.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -0,0 +1,114 @@
+/*
+ * 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.wireformat;
+
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
+
+/**
+ * 
+ * A SessionProducerFlowCreditMessage
+ * 
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ *
+ */
+public class SessionProducerFlowCreditMessage extends PacketImpl
+{
+   // Constants -----------------------------------------------------
+
+   // Attributes ----------------------------------------------------
+
+   private long producerID;
+   
+   private int credits;
+
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   public SessionProducerFlowCreditMessage(final long producerID, final int credits)
+   {
+      super(SESS_RECEIVETOKENS);
+
+      this.producerID = producerID;
+      
+      this.credits = credits;
+   }
+   
+   public SessionProducerFlowCreditMessage()
+   {
+      super(SESS_RECEIVETOKENS);
+   }
+
+   // Public --------------------------------------------------------
+
+   public long getProducerID()
+   {
+      return producerID;
+   }
+   
+   public int getTokens()
+   {
+      return credits;
+   }
+   
+   public void encodeBody(final MessagingBuffer buffer)
+   {
+      buffer.putLong(producerID);
+      buffer.putInt(credits);
+   }
+   
+   public void decodeBody(final MessagingBuffer buffer)
+   {
+      producerID = buffer.getLong();
+      credits = buffer.getInt();
+   }
+
+   @Override
+   public String toString()
+   {
+      StringBuffer buf = new StringBuffer(getParentString());
+      buf.append(", producerID=" + producerID + ", credits=" + credits);
+      buf.append("]");
+      return buf.toString();
+   }
+   
+   public boolean equals(Object other)
+   {
+      if (other instanceof SessionProducerFlowCreditMessage == false)
+      {
+         return false;
+      }
+            
+      SessionProducerFlowCreditMessage r = (SessionProducerFlowCreditMessage)other;
+      
+      return super.equals(other) && this.credits == r.credits && this.producerID == r.producerID;
+   }
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   // Inner classes -------------------------------------------------
+}

Copied: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionReceiveMessage.java (from rev 4941, trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/ReceiveMessage.java)
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionReceiveMessage.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionReceiveMessage.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -0,0 +1,137 @@
+/*
+ * 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.wireformat;
+
+import org.jboss.messaging.core.client.ClientMessage;
+import org.jboss.messaging.core.client.impl.ClientMessageImpl;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
+import org.jboss.messaging.core.server.ServerMessage;
+
+/**
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * @author <a href="mailto:ovidiu at feodorov.com">Ovidiu Feodorov</a>
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ * 
+ * @version <tt>$Revision$</tt>
+ */
+public class SessionReceiveMessage extends PacketImpl
+{
+   // Constants -----------------------------------------------------
+   
+   private static final Logger log = Logger.getLogger(SessionReceiveMessage.class);
+
+   // Attributes ----------------------------------------------------
+
+   private long consumerID;
+   
+   private ClientMessage clientMessage;
+   
+   private ServerMessage serverMessage;
+   
+   private int deliveryCount;
+   
+   private long deliveryID;
+
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+   
+   public SessionReceiveMessage(final long consumerID, final ServerMessage message, final int deliveryCount, final long deliveryID)
+   {
+      super(SESS_RECEIVE_MSG);
+      
+      this.consumerID = consumerID;
+
+      this.serverMessage = message;
+      
+      this.clientMessage = null;
+      
+      this.deliveryCount = deliveryCount;
+      
+      this.deliveryID = deliveryID;
+   }
+   
+   public SessionReceiveMessage()
+   {
+      super(SESS_RECEIVE_MSG);
+   }
+
+   // Public --------------------------------------------------------
+
+   public long getConsumerID()
+   {
+      return consumerID;
+   }
+   
+   public ClientMessage getClientMessage()
+   {
+      return clientMessage;
+   }
+   
+   public ServerMessage getServerMessage()
+   {
+      return serverMessage;
+   }
+
+   public int getDeliveryCount()
+   {
+      return deliveryCount;
+   }
+   
+   public long getDeliveryID()
+   {
+      return deliveryID;
+   }
+   
+   public void encodeBody(final MessagingBuffer buffer)
+   {
+      buffer.putLong(consumerID);
+      buffer.putInt(deliveryCount);
+      buffer.putLong(deliveryID);
+      serverMessage.encode(buffer);
+   }
+   
+   public void decodeBody(final MessagingBuffer buffer)
+   {
+      //TODO can be optimised
+      
+      consumerID = buffer.getLong();
+      deliveryCount = buffer.getInt();
+      deliveryID = buffer.getLong();
+      
+      clientMessage = new ClientMessageImpl(deliveryCount, deliveryID);
+      
+      clientMessage.decode(buffer);
+      
+      clientMessage.getBody().flip();
+   }
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   // Inner classes -------------------------------------------------
+}

Deleted: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionReplicateDeliveryMessage.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionReplicateDeliveryMessage.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionReplicateDeliveryMessage.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -1,116 +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.wireformat;
-
-import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
-
-
-/**
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- * 
- * @version <tt>$Revision$</tt>
- */
-public class SessionReplicateDeliveryMessage extends PacketImpl
-{
-   // Constants -----------------------------------------------------
-
-   // Attributes ----------------------------------------------------
-   
-   private long messageID;
-   
-   private long consumerID;
-   
-   // Static --------------------------------------------------------
-
-   // Constructors --------------------------------------------------
-
-   public SessionReplicateDeliveryMessage(final long consumerID, final long messageID)
-   {
-      super(SESS_REPLICATE_DELIVERY);
-      
-      this.messageID = messageID;
-      
-      this.consumerID = consumerID;
-   }
-   
-   public SessionReplicateDeliveryMessage()
-   {
-      super(SESS_REPLICATE_DELIVERY);
-   }
-
-   // Public --------------------------------------------------------
-   
-   public long getMessageID()
-   {
-      return messageID;
-   }
-   
-   public long getConsumerID()
-   {
-      return consumerID;
-   }
-   
-   public void encodeBody(final MessagingBuffer buffer)
-   {
-      buffer.putLong(messageID);
-      buffer.putLong(consumerID);
-   }
-   
-   public void decodeBody(final MessagingBuffer buffer)
-   {
-      messageID = buffer.getLong();
-      consumerID = buffer.getLong();
-   }
-   
-   public boolean isUsesConfirmations()
-   {
-      return false;
-   }
-
-   @Override
-   public String toString()
-   {
-      return getParentString() + ", messageID=" + messageID + ", consumerID=" + consumerID + "]";
-   }
-   
-   public boolean equals(Object other)
-   {
-      if (other instanceof SessionReplicateDeliveryMessage == false)
-      {
-         return false;
-      }
-            
-      SessionReplicateDeliveryMessage r = (SessionReplicateDeliveryMessage)other;
-      
-      return super.equals(other) && this.messageID == r.messageID && this.consumerID == r.consumerID;
-   }
-   
-   // Package protected ---------------------------------------------
-
-   // Protected -----------------------------------------------------
-
-   // Private -------------------------------------------------------
-
-   // Inner classes -------------------------------------------------
-}
-

Deleted: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionReplicateDeliveryResponseMessage.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionReplicateDeliveryResponseMessage.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionReplicateDeliveryResponseMessage.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -1,62 +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.wireformat;
-
-
-/**
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- * 
- * @version <tt>$Revision$</tt>
- */
-public class SessionReplicateDeliveryResponseMessage extends PacketImpl
-{
-   // Constants -----------------------------------------------------
-
-   // Attributes ----------------------------------------------------
-   
-   // Static --------------------------------------------------------
-
-   // Constructors --------------------------------------------------
-
-   public SessionReplicateDeliveryResponseMessage()
-   {
-      super(SESS_REPLICATE_DELIVERY_RESP);
-   }
-
-   // Public --------------------------------------------------------
-    
-   public boolean isUsesConfirmations()
-   {
-      return false;
-   }
-
-   // Package protected ---------------------------------------------
-
-   // Protected -----------------------------------------------------
-
-   // Private -------------------------------------------------------
-
-   // Inner classes -------------------------------------------------
-}
-
-

Copied: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionSendMessage.java (from rev 4941, trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SendMessage.java)
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionSendMessage.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionSendMessage.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -0,0 +1,135 @@
+/*
+ * 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.wireformat;
+
+import org.jboss.messaging.core.client.ClientMessage;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
+import org.jboss.messaging.core.server.ServerMessage;
+import org.jboss.messaging.core.server.impl.ServerMessageImpl;
+
+/**
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ * 
+ * @version <tt>$Revision$</tt>
+ */
+public class SessionSendMessage extends PacketImpl
+{
+   // Constants -----------------------------------------------------
+
+   private static final Logger log = Logger.getLogger(SessionSendMessage.class);
+   
+   // Attributes ----------------------------------------------------
+
+   private long producerID;
+   
+   private ClientMessage clientMessage;
+   
+   private ServerMessage serverMessage;
+   
+   private boolean requiresResponse;
+
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   public SessionSendMessage(final long producerID, final ClientMessage message, final boolean requiresResponse)
+   {
+      super(SESS_SEND);
+
+      this.producerID = producerID;
+      
+      this.clientMessage = message;
+      
+      this.requiresResponse = requiresResponse;
+   }
+      
+   public SessionSendMessage()
+   {
+      super(SESS_SEND);
+   }
+
+   // Public --------------------------------------------------------
+
+   public long getProducerID()
+   {
+      return producerID;
+   }
+   
+   public ClientMessage getClientMessage()
+   {
+      return clientMessage;
+   }
+   
+   public ServerMessage getServerMessage()
+   {
+      return serverMessage;
+   }
+   
+   public boolean isRequiresResponse()
+   {
+      return requiresResponse;
+   }
+   
+   public void encodeBody(final MessagingBuffer buffer)
+   {
+      buffer.putLong(producerID);      
+      
+      if (clientMessage != null)
+      {
+         clientMessage.encode(buffer);
+      }
+      else
+      {
+         //If we're replicating a buffer to a backup node then we encode the serverMessage not the clientMessage
+         serverMessage.encode(buffer);
+      }
+      
+      buffer.putBoolean(requiresResponse);
+   }
+   
+   public void decodeBody(final MessagingBuffer buffer)
+   {
+      //TODO can be optimised
+      
+      producerID = buffer.getLong();
+                  
+      serverMessage = new ServerMessageImpl();
+      
+      serverMessage.decode(buffer);
+      
+      serverMessage.getBody().flip();
+      
+      requiresResponse = buffer.getBoolean();
+   }
+
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   // Inner classes -------------------------------------------------
+}

Added: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/cluster/ReplicationResponseMessage.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/cluster/ReplicationResponseMessage.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/cluster/ReplicationResponseMessage.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -0,0 +1,62 @@
+/*
+ * 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.wireformat.cluster;
+
+import org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl;
+
+
+/**
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * 
+ * @version <tt>$Revision$</tt>
+ */
+public class ReplicationResponseMessage extends PacketImpl
+{
+   // Constants -----------------------------------------------------
+
+   // Attributes ----------------------------------------------------
+
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   public ReplicationResponseMessage()
+   {
+      super(REPLICATION_RESP);
+   }
+
+   // Public --------------------------------------------------------
+
+   public boolean isUsesConfirmations()
+   {
+      return false;
+   }
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   // Inner classes -------------------------------------------------
+}

Copied: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/cluster/SessionReplicateDeliveryMessage.java (from rev 4941, trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionReplicateDeliveryMessage.java)
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/cluster/SessionReplicateDeliveryMessage.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/cluster/SessionReplicateDeliveryMessage.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -0,0 +1,117 @@
+/*
+ * 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.wireformat.cluster;
+
+import org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
+
+
+/**
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * 
+ * @version <tt>$Revision$</tt>
+ */
+public class SessionReplicateDeliveryMessage extends PacketImpl
+{
+   // Constants -----------------------------------------------------
+
+   // Attributes ----------------------------------------------------
+   
+   private long messageID;
+   
+   private long consumerID;
+   
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   public SessionReplicateDeliveryMessage(final long consumerID, final long messageID)
+   {
+      super(SESS_REPLICATE_DELIVERY);
+      
+      this.messageID = messageID;
+      
+      this.consumerID = consumerID;
+   }
+   
+   public SessionReplicateDeliveryMessage()
+   {
+      super(SESS_REPLICATE_DELIVERY);
+   }
+
+   // Public --------------------------------------------------------
+   
+   public long getMessageID()
+   {
+      return messageID;
+   }
+   
+   public long getConsumerID()
+   {
+      return consumerID;
+   }
+   
+   public void encodeBody(final MessagingBuffer buffer)
+   {
+      buffer.putLong(messageID);
+      buffer.putLong(consumerID);
+   }
+   
+   public void decodeBody(final MessagingBuffer buffer)
+   {
+      messageID = buffer.getLong();
+      consumerID = buffer.getLong();
+   }
+   
+   public boolean isUsesConfirmations()
+   {
+      return false;
+   }
+
+   @Override
+   public String toString()
+   {
+      return getParentString() + ", messageID=" + messageID + ", consumerID=" + consumerID + "]";
+   }
+   
+   public boolean equals(Object other)
+   {
+      if (other instanceof SessionReplicateDeliveryMessage == false)
+      {
+         return false;
+      }
+            
+      SessionReplicateDeliveryMessage r = (SessionReplicateDeliveryMessage)other;
+      
+      return super.equals(other) && this.messageID == r.messageID && this.consumerID == r.consumerID;
+   }
+   
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   // Inner classes -------------------------------------------------
+}
+

Added: trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/cluster/SessionReplicateSendMessage.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/cluster/SessionReplicateSendMessage.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/wireformat/cluster/SessionReplicateSendMessage.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -0,0 +1,113 @@
+/*
+ * 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.wireformat.cluster;
+
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendMessage;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
+import org.jboss.messaging.core.server.ServerMessage;
+import org.jboss.messaging.core.server.impl.ServerMessageImpl;
+
+/**
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
+ * 
+ * @version <tt>$Revision$</tt>
+ */
+public class SessionReplicateSendMessage extends PacketImpl
+{
+   // Constants -----------------------------------------------------
+
+   private static final Logger log = Logger.getLogger(SessionSendMessage.class);
+   
+   // Attributes ----------------------------------------------------
+
+   private long producerID;
+   
+   private ServerMessage serverMessage;
+   
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   public SessionReplicateSendMessage(final long producerID, final ServerMessage message)
+   {
+      super(SESS_REPLICATE_SEND);
+
+      this.producerID = producerID;
+      
+      this.serverMessage = message;
+   }
+      
+   public SessionReplicateSendMessage()
+   {
+      super(SESS_REPLICATE_SEND);
+   }
+
+   // Public --------------------------------------------------------
+
+   public long getProducerID()
+   {
+      return producerID;
+   }
+   
+   public ServerMessage getServerMessage()
+   {
+      return serverMessage;
+   }
+   
+   public void encodeBody(final MessagingBuffer buffer)
+   {
+      buffer.putLong(producerID);      
+      
+      serverMessage.encode(buffer);
+      
+      buffer.putLong(serverMessage.getMessageID());
+   }
+   
+   public void decodeBody(final MessagingBuffer buffer)
+   {
+      //TODO can be optimised
+      
+      producerID = buffer.getLong();
+                  
+      serverMessage = new ServerMessageImpl();
+      
+      serverMessage.decode(buffer);
+      
+      serverMessage.getBody().flip();   
+      
+      serverMessage.setMessageID(buffer.getLong());
+   }
+
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   // Inner classes -------------------------------------------------
+}
+

Modified: trunk/src/main/org/jboss/messaging/core/server/MessagingServer.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/MessagingServer.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/server/MessagingServer.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -1,24 +1,24 @@
 /*
- * 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.
- */ 
+ * 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.server;
 
@@ -52,54 +52,54 @@
  * @author <a href="ataylor at redhat.com">Andy Taylor</a>
  */
 public interface MessagingServer extends MessagingComponent
-{  
+{
    void setConfiguration(Configuration configuration);
-   
-   Configuration getConfiguration(); 
-   
+
+   Configuration getConfiguration();
+
    void setRemotingService(RemotingService remotingService);
-   
+
    RemotingService getRemotingService();
-   
+
    void setStorageManager(StorageManager storageManager);
-      
+
    StorageManager getStorageManager();
 
    JBMSecurityManager getSecurityManager();
-      
+
    void setSecurityManager(JBMSecurityManager securityManager);
 
    ManagementService getManagementService();
-  
+
    void setManagementService(ManagementService managementService);
-   
+
    Version getVersion();
-   
-   ReattachSessionResponseMessage reattachSession(RemotingConnection connection,                                                  
-                                                  String name,
-                                                  int lastReceivedCommandID);
-  
-   CreateSessionResponseMessage createSession(String name, long channelID,
-                                              String username, String password,                                  
+
+   ReattachSessionResponseMessage reattachSession(RemotingConnection connection, String name, int lastReceivedCommandID) throws Exception;
+
+   CreateSessionResponseMessage createSession(String name,
+                                              long channelID,
+                                              String username,
+                                              String password,
                                               int incrementingVersion,
                                               RemotingConnection remotingConnection,
                                               boolean autoCommitSends,
                                               boolean autoCommitAcks,
                                               boolean xa) throws Exception;
-   
+
    void removeSession(String name);
-         
+
    boolean isStarted();
-   
-   MessagingServerControlMBean getServerManagement();  
-   
+
+   MessagingServerControlMBean getServerManagement();
+
    HierarchicalRepository<Set<Role>> getSecurityRepository();
-   
+
    HierarchicalRepository<QueueSettings> getQueueSettingsRepository();
-   
+
    int getConnectionCount();
-   
+
    PostOffice getPostOffice();
-   
+
    RemotingConnection getReplicatingConnection();
 }

Modified: trunk/src/main/org/jboss/messaging/core/server/ServerSession.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/ServerSession.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/server/ServerSession.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -62,12 +62,10 @@
 	
 	void handleDelivery(MessageReference reference, ServerConsumer consumer) throws Exception;
 	
-	void deliverDeferredDelivery(long messageID);
-	
 	void promptDelivery(Queue queue);
 	
 	void send(ServerMessage msg) throws Exception;
-
+		
    void acknowledge(long deliveryID, boolean allUpTo) throws Exception;
 
    void rollback() throws Exception;
@@ -138,8 +136,6 @@
    
    void handleReplicateDelivery(long consumerID, long messageID) throws Exception;
    
-   void handleDeferredDelivery();
-   
    void transferConnection(RemotingConnection newConnection);
    
    int replayCommands(int lastReceivedCommandID);

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/DeliveryImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/DeliveryImpl.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/DeliveryImpl.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -24,7 +24,7 @@
 
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.Channel;
-import org.jboss.messaging.core.remoting.impl.wireformat.ReceiveMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionReceiveMessage;
 import org.jboss.messaging.core.server.Delivery;
 import org.jboss.messaging.core.server.MessageReference;
 
@@ -74,8 +74,8 @@
    
    public void deliver()
    {
-      ReceiveMessage message =
-         new ReceiveMessage(consumerID, reference.getMessage(), reference.getDeliveryCount() + 1, deliveryID);
+      SessionReceiveMessage message =
+         new SessionReceiveMessage(consumerID, reference.getMessage(), reference.getDeliveryCount() + 1, deliveryID);
       
       channel.send(message);
    }

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServerImpl.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServerImpl.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -1,24 +1,24 @@
 /*
- * 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.
- */ 
+ * 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.server.impl;
 
@@ -83,13 +83,16 @@
  */
 public class MessagingServerImpl implements MessagingServer
 {
-   // Constants ------------------------------------------------------------------------------------
+   // Constants
+   // ------------------------------------------------------------------------------------
 
    private static final Logger log = Logger.getLogger(MessagingServerImpl.class);
 
-   // Static ---------------------------------------------------------------------------------------
+   // Static
+   // ---------------------------------------------------------------------------------------
 
-   // Attributes -----------------------------------------------------------------------------------
+   // Attributes
+   // -----------------------------------------------------------------------------------
 
    private final Version version;
 
@@ -98,39 +101,58 @@
    // wired components
 
    private SecurityStore securityStore;
+
    private final HierarchicalRepository<QueueSettings> queueSettingsRepository = new HierarchicalObjectRepository<QueueSettings>();
+
    private ScheduledExecutorService scheduledExecutor;
+
    private QueueFactory queueFactory;
+
    private PagingManager pagingManager;
+
    private PostOffice postOffice;
+
    private final ExecutorService asyncDeliveryPool = Executors.newCachedThreadPool(new JBMThreadFactory("JBM-async-session-delivery-threads"));
+
    private final ExecutorFactory executorFactory = new OrderedExecutorFactory(asyncDeliveryPool);
+
    private HierarchicalRepository<Set<Role>> securityRepository;
+
    private ResourceManager resourceManager;
+
    private MessagingServerControlMBean serverManagement;
+
    private final ConcurrentMap<String, ServerSession> sessions = new ConcurrentHashMap<String, ServerSession>();
+
    private ConnectorFactory backupConnectorFactory;
+
    private Map<String, Object> backupConnectorParams;
 
    // plugins
 
    private StorageManager storageManager;
+
    private RemotingService remotingService;
+
    private JBMSecurityManager securityManager;
+
    private Configuration configuration;
+
    private ManagementService managementService;
 
-   // Constructors ---------------------------------------------------------------------------------
+   // Constructors
+   // ---------------------------------------------------------------------------------
 
    public MessagingServerImpl()
    {
-      //We need to hard code the version information into a source file
+      // We need to hard code the version information into a source file
 
       version = VersionLoader.load();
    }
-   
-   // lifecycle methods ----------------------------------------------------------------
 
+   // lifecycle methods
+   // ----------------------------------------------------------------
+
    public synchronized void start() throws Exception
    {
       if (started)
@@ -146,7 +168,7 @@
       lifecycle will not be controlled here
       */
 
-      //We make sure the pluggable components have been injected
+      // We make sure the pluggable components have been injected
       if (configuration == null)
       {
          throw new IllegalStateException("Must inject Configuration before starting MessagingServer");
@@ -182,31 +204,43 @@
          throw new IllegalStateException("RemotingService must be started before MessagingServer is started");
       }
 
-      //The rest of the components are not pluggable and created and started here
+      // The rest of the components are not pluggable and created and started
+      // here
 
-      securityStore = new SecurityStoreImpl(configuration.getSecurityInvalidationInterval(), configuration.isSecurityEnabled());
+      securityStore = new SecurityStoreImpl(configuration.getSecurityInvalidationInterval(),
+                                            configuration.isSecurityEnabled());
       queueSettingsRepository.setDefault(new QueueSettings());
-      scheduledExecutor = new ScheduledThreadPoolExecutor(configuration.getScheduledThreadPoolMaxSize(), new JBMThreadFactory("JBM-scheduled-threads"));
+      scheduledExecutor = new ScheduledThreadPoolExecutor(configuration.getScheduledThreadPoolMaxSize(),
+                                                          new JBMThreadFactory("JBM-scheduled-threads"));
       queueFactory = new QueueFactoryImpl(scheduledExecutor, queueSettingsRepository);
 
-
       PagingStoreFactory storeFactory = new PagingManagerFactoryNIO(configuration.getPagingDirectory());
 
-      pagingManager = new PagingManagerImpl(storeFactory, storageManager, queueSettingsRepository, configuration.getPagingMaxGlobalSizeBytes());
-      
+      pagingManager = new PagingManagerImpl(storeFactory,
+                                            storageManager,
+                                            queueSettingsRepository,
+                                            configuration.getPagingMaxGlobalSizeBytes());
+
       storeFactory.setPagingManager(pagingManager);
 
       resourceManager = new ResourceManagerImpl(0);
-      postOffice =
-        new PostOfficeImpl(storageManager, pagingManager, queueFactory, managementService, configuration.isRequireDestinations(), resourceManager);
+      postOffice = new PostOfficeImpl(storageManager,
+                                      pagingManager,
+                                      queueFactory,
+                                      managementService,
+                                      configuration.isRequireDestinations(),
+                                      resourceManager);
 
       securityRepository = new HierarchicalObjectRepository<Set<Role>>();
       securityRepository.setDefault(new HashSet<Role>());
       securityStore.setSecurityRepository(securityRepository);
       securityStore.setSecurityManager(securityManager);
-      serverManagement = managementService.registerServer(postOffice, storageManager, configuration,
-            securityRepository,
-            queueSettingsRepository, this);
+      serverManagement = managementService.registerServer(postOffice,
+                                                          storageManager,
+                                                          configuration,
+                                                          securityRepository,
+                                                          queueSettingsRepository,
+                                                          this);
 
       postOffice.start();
       postOffice.setBackup(configuration.isBackup());
@@ -219,16 +253,18 @@
          try
          {
             Class<?> clz = loader.loadClass(backupConnector.getFactoryClassName());
-            this.backupConnectorFactory = (ConnectorFactory) clz.newInstance();            
+            this.backupConnectorFactory = (ConnectorFactory)clz.newInstance();
          }
          catch (Exception e)
          {
-            throw new IllegalArgumentException("Error instantiating interceptor \"" + backupConnector.getFactoryClassName() + "\"", e);
+            throw new IllegalArgumentException("Error instantiating interceptor \"" + backupConnector.getFactoryClassName() +
+                                                        "\"",
+                                               e);
          }
          this.backupConnectorParams = backupConnector.getParams();
       }
       remotingService.setMessagingServer(this);
-           
+
       started = true;
    }
 
@@ -249,9 +285,9 @@
       queueFactory = null;
       resourceManager = null;
       serverManagement = null;
-      
+
       asyncDeliveryPool.shutdown();
-      
+
       try
       {
          if (!asyncDeliveryPool.awaitTermination(10000, TimeUnit.MILLISECONDS))
@@ -261,15 +297,15 @@
       }
       catch (InterruptedException e)
       {
-         //Ignore
+         // Ignore
       }
 
       started = false;
    }
 
-   // MessagingServer implementation -----------------------------------------------------------
+   // MessagingServer implementation
+   // -----------------------------------------------------------
 
-
    // The plugabble components
 
    public void setConfiguration(Configuration configuration)
@@ -344,13 +380,13 @@
       return managementService;
    }
 
-   //This is needed for the security deployer
+   // This is needed for the security deployer
    public HierarchicalRepository<Set<Role>> getSecurityRepository()
    {
       return securityRepository;
    }
 
-   //This is needed for the queue settings deployer
+   // This is needed for the queue settings deployer
    public HierarchicalRepository<QueueSettings> getQueueSettingsRepository()
    {
       return queueSettingsRepository;
@@ -365,108 +401,125 @@
    {
       return started;
    }
-   
+
    public ReattachSessionResponseMessage reattachSession(final RemotingConnection connection,
-                                                         final String name,                                                        
-                                                         final int lastReceivedCommandID)
-   {     
+                                                         final String name,
+                                                         final int lastReceivedCommandID) throws Exception
+   {
       ServerSession session = sessions.get(name);
-      
+
       if (session == null)
       {
          throw new IllegalArgumentException("Cannot find session with name " + name + " to reattach");
-      }            
-      
-      //Reconnect the channel to the new connection
+      }
+
+      // Reconnect the channel to the new connection
       session.transferConnection(connection);
-      
-      //This is necessary for invm since the replicating connection will be the same connection
-      //as the original replicating connection since the key is the same in the registry, and that connection
-      //won't have any resend buffer etc
-      connection.setBackup(false);
-      
+
+      // This is necessary for invm since the replicating connection will be the
+      // same connection
+      // as the original replicating connection since the key is the same in the
+      // registry, and that connection
+      // won't have any resend buffer etc
+      connection.setReplicating(false);
+
+      int serverLastReceivedCommandID = session.replayCommands(lastReceivedCommandID);
+
       postOffice.setBackup(false);
-      
+
       configuration.setBackup(false);
-                  
+
       remotingService.setBackup(false);
-                  
-      int serverLastReceivedCommandID = session.replayCommands(lastReceivedCommandID);
-      
-      connection.setBackup(false);
-      
-      return new ReattachSessionResponseMessage(serverLastReceivedCommandID);            
+
+      connection.setReplicating(false);
+
+      // Re-prompt delivery
+      session.setStarted(true);
+
+      return new ReattachSessionResponseMessage(serverLastReceivedCommandID);
    }
 
    public CreateSessionResponseMessage createSession(final String name,
                                                      final long channelID,
-                                                     final String username, final String password,
+                                                     final String username,
+                                                     final String password,
                                                      final int incrementingVersion,
-                                                     final RemotingConnection remotingConnection,
+                                                     final RemotingConnection connection,
                                                      final boolean autoCommitSends,
                                                      final boolean autoCommitAcks,
-                                                     final boolean xa)
-           throws Exception
+                                                     final boolean xa) throws Exception
    {
       if (version.getIncrementingVersion() < incrementingVersion)
       {
          throw new MessagingException(MessagingException.INCOMPATIBLE_CLIENT_SERVER_VERSIONS,
-                 "client not compatible with version: " + version.getFullVersion());
+                                      "client not compatible with version: " + version.getFullVersion());
       }
 
-      //Is this comment relevant any more ?
+      // 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.
+      // 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 =
-         remotingConnection.getChannel(channelID, true, configuration.getPacketConfirmationBatchSize());
+      securityStore.authenticate(username, password);
 
-      final ServerSessionImpl session = new ServerSessionImpl(name, channelID, username, password,
-                                  autoCommitSends, autoCommitAcks, xa,
-                                  remotingConnection,
-                                  storageManager, postOffice,
-                                  queueSettingsRepository,
-                                  resourceManager,
-                                  securityStore,
-                                  executorFactory.getExecutor(),
-                                  channel,
-                                  this);
-      
+      Channel channel = connection.getChannel(channelID, true, configuration.getPacketConfirmationBatchSize());
+
+      final ServerSessionImpl session = new ServerSessionImpl(name,
+                                                              channelID,
+                                                              username,
+                                                              password,
+                                                              autoCommitSends,
+                                                              autoCommitAcks,
+                                                              xa,
+                                                              connection,
+                                                              storageManager,
+                                                              postOffice,
+                                                              queueSettingsRepository,
+                                                              resourceManager,
+                                                              securityStore,
+                                                              executorFactory.getExecutor(),
+                                                              channel,
+                                                              this);
+
       if (sessions.putIfAbsent(name, session) != null)
       {
          throw new IllegalArgumentException("Session with name " + name + " already exists");
       }
 
-      ChannelHandler handler = new ServerSessionPacketHandler(session, channel);
+      ChannelHandler handler = new ServerSessionPacketHandler(session, channel, storageManager);
 
       channel.setHandler(handler);
 
-      remotingConnection.addFailureListener(session);
+      connection.addFailureListener(session);
 
-      return
-         new CreateSessionResponseMessage(version.getIncrementingVersion(),
-                                          configuration.getPacketConfirmationBatchSize());
+      return new CreateSessionResponseMessage(version.getIncrementingVersion(),
+                                              configuration.getPacketConfirmationBatchSize());
    }
-   
+
    public RemotingConnection getReplicatingConnection()
    {
-      //Note we must always get a new connection each time - since there must be a one to one correspondence
-      //between connections to clients and replicating connections, since we need to preserve channel ids
-      //before and after failover
-      
+      // Note we must always get a new connection each time - since there must
+      // be a one to one correspondence
+      // between connections to clients and replicating connections, since we
+      // need to preserve channel ids
+      // before and after failover
+
       if (backupConnectorFactory != null)
       {
-         //TODO don't hardcode ping interval and code timeout
-         RemotingConnection replicatingConnection = 
-            ConnectionRegistryImpl.instance.getConnectionNoCache(backupConnectorFactory, backupConnectorParams, 5000, 30000);
-         
-         replicatingConnection.setBackup(true);
-         
+         // TODO don't hardcode ping interval and code timeout
+         RemotingConnection replicatingConnection = ConnectionRegistryImpl.instance.getConnectionNoCache(backupConnectorFactory,
+                                                                                                         backupConnectorParams,
+                                                                                                         -1,
+                                                                                                         30000);
+
+         replicatingConnection.setReplicating(true);
+
          return replicatingConnection;
       }
       else
@@ -474,7 +527,7 @@
          return null;
       }
    }
-   
+
    public void removeSession(final String name)
    {
       if (sessions.remove(name) == null)
@@ -498,13 +551,18 @@
       return postOffice;
    }
 
-   // Public ---------------------------------------------------------------------------------------
+   // Public
+   // ---------------------------------------------------------------------------------------
 
-   // Package protected ----------------------------------------------------------------------------
+   // Package protected
+   // ----------------------------------------------------------------------------
 
-   // Protected ------------------------------------------------------------------------------------
+   // Protected
+   // ------------------------------------------------------------------------------------
 
-   // Private --------------------------------------------------------------------------------------
-    
-   // Inner classes --------------------------------------------------------------------------------
+   // Private
+   // --------------------------------------------------------------------------------------
+
+   // 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-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServerPacketHandler.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -62,8 +62,29 @@
       
       this.connection = connection;
    }
+   
 
    public void handlePacket(final Packet packet)
+   {   
+      if (channel1.getReplicatingChannel() != null)
+      {
+         Runnable action = new Runnable()
+         {
+            public void run()
+            {
+               doHandlePacket(packet);
+            }
+         };
+         
+         channel1.replicatePacket(packet, action);
+      }
+      else
+      {
+         doHandlePacket(packet);
+      }
+   }
+   
+   private void doHandlePacket(final Packet packet)
    {      
       Packet response = null;
 
@@ -72,7 +93,7 @@
       try
       {
          if (type == CREATESESSION)
-         {
+         {                        
             CreateSessionMessage request = (CreateSessionMessage) packet;
                                     
             response =

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -1,24 +1,24 @@
 /*
- * 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.
- */ 
+ * 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.server.impl;
 
@@ -74,9 +74,9 @@
    private static final Logger log = Logger.getLogger(QueueImpl.class);
 
    private static final boolean trace = log.isTraceEnabled();
-   
+
    public static final int NUM_PRIORITIES = 10;
-   
+
    private volatile long persistenceID = -1;
 
    private final SimpleString name;
@@ -88,11 +88,10 @@
    private final boolean durable;
 
    private final ScheduledExecutorService scheduledExecutor;
-   
+
    private final PostOffice postOffice;
 
-   private final PriorityLinkedList<MessageReference> messageReferences =
-      new PriorityLinkedListImpl<MessageReference>(NUM_PRIORITIES);
+   private final PriorityLinkedList<MessageReference> messageReferences = new PriorityLinkedListImpl<MessageReference>(NUM_PRIORITIES);
 
    private final List<Consumer> consumers = new ArrayList<Consumer>();
 
@@ -105,7 +104,7 @@
    private boolean promptDelivery;
 
    private int pos;
-   
+
    private AtomicInteger sizeBytes = new AtomicInteger(0);
 
    private AtomicInteger messagesAdded = new AtomicInteger(0);
@@ -113,19 +112,22 @@
    private AtomicInteger deliveringCount = new AtomicInteger(0);
 
    private volatile FlowController flowController;
-   
-   private AtomicBoolean waitingToDeliver = new AtomicBoolean(false);  
-   
+
+   private AtomicBoolean waitingToDeliver = new AtomicBoolean(false);
+
    private final Runnable deliverRunner = new DeliverRunner();
-   
+
    private final Lock lock = new ReentrantLock(false);
-   
+
    private volatile boolean backup;
-         
-   public QueueImpl(final long persistenceID, final SimpleString name,
-         final Filter filter, final boolean clustered, final boolean durable,
-         final ScheduledExecutorService scheduledExecutor,
-         final PostOffice postOffice)
+
+   public QueueImpl(final long persistenceID,
+                    final SimpleString name,
+                    final Filter filter,
+                    final boolean clustered,
+                    final boolean durable,
+                    final ScheduledExecutorService scheduledExecutor,
+                    final PostOffice postOffice)
    {
       this.persistenceID = persistenceID;
 
@@ -138,7 +140,7 @@
       this.durable = durable;
 
       this.scheduledExecutor = scheduledExecutor;
-      
+
       this.postOffice = postOffice;
 
       direct = true;
@@ -147,7 +149,6 @@
    // Queue implementation
    // -------------------------------------------------------------------
 
-
    public boolean isClustered()
    {
       return clustered;
@@ -162,12 +163,12 @@
    {
       return name;
    }
-   
+
    public HandleStatus addLast(final MessageReference ref)
-   {     
+   {
       lock.lock();
       try
-      {         
+      {
          return add(ref, false);
       }
       finally
@@ -186,7 +187,7 @@
       }
       finally
       {
-         lock.unlock();       
+         lock.unlock();
       }
    }
 
@@ -203,40 +204,43 @@
 
       deliver();
    }
- 
+
    public void deliverAsync(final Executor executor)
    {
-      //Prevent too many executors running at once
-                  
+      // Prevent too many executors running at once
+
       if (waitingToDeliver.compareAndSet(false, true))
       {
          executor.execute(deliverRunner);
       }
    }
-      
+
    /*
     * Attempt to deliver all the messages in the queue
     */
    public void deliver()
    {
-      //We don't do actual delivery if the queue is on a backup node - this is because it's async and could get out of step
-      //with the live node. Instead, when we replicate the delivery we remove the ref from the queue
-       
+      // We don't do actual delivery if the queue is on a backup node - this is
+      // because it's async and could get out of step
+      // with the live node. Instead, when we replicate the delivery we remove
+      // the ref from the queue
+
       if (backup)
       {
          return;
       }
-      
-      //TODO - we need to lock during delivery since otherwise delivery could occur while we're rolling back a transaction
-      //which would mean messages got delivered in the wrong order
-      //We need to revise this for better concurrency
+
+      // TODO - we need to lock during delivery since otherwise delivery could
+      // occur while we're rolling back a transaction
+      // which would mean messages got delivered in the wrong order
+      // We need to revise this for better concurrency
       lock.lock();
       try
-      {  
+      {
          MessageReference reference;
-   
+
          Iterator<MessageReference> iterator = null;
-   
+
          while (true)
          {
             if (iterator == null)
@@ -254,26 +258,26 @@
                   reference = null;
                }
             }
-   
+
             if (reference == null)
             {
                if (iterator == null)
                {
                   // We delivered all the messages - go into direct delivery
                   direct = true;
-                  
+
                   promptDelivery = false;
                }
                return;
             }
-   
+
             HandleStatus status = deliver(reference);
-   
+
             if (status == HandleStatus.HANDLED)
             {
                if (iterator == null)
                {
-                  messageReferences.removeFirst();              
+                  messageReferences.removeFirst();
                }
                else
                {
@@ -287,7 +291,8 @@
             }
             else if (status == HandleStatus.NO_MATCH && iterator == null)
             {
-               // Consumers not all busy - but filter not accepting - iterate back
+               // Consumers not all busy - but filter not accepting - iterate
+               // back
                // through the queue
                iterator = messageReferences.iterator();
             }
@@ -307,12 +312,12 @@
    public synchronized boolean removeConsumer(final Consumer consumer) throws Exception
    {
       boolean removed = consumers.remove(consumer);
-      
+
       if (pos == consumers.size())
       {
          pos = 0;
       }
-      
+
       if (consumers.isEmpty())
       {
          promptDelivery = false;
@@ -404,7 +409,7 @@
    }
 
    public synchronized int getMessageCount()
-   {    
+   {
       return messageReferences.size() + getScheduledCount() + getDeliveringCount();
    }
 
@@ -421,13 +426,13 @@
    public void referenceAcknowledged(MessageReference ref) throws Exception
    {
       deliveringCount.decrementAndGet();
-      
+
       sizeBytes.addAndGet(-ref.getMessage().getEncodeSize());
 
-//      if (flowController != null)
-//      {
-//         flowController.messageAcknowledged();
-//      }
+      // if (flowController != null)
+      // {
+      // flowController.messageAcknowledged();
+      // }
    }
 
    public void referenceCancelled()
@@ -498,11 +503,11 @@
 
       tx.commit();
    }
-   
+
    public synchronized boolean deleteReference(final long messageID, final StorageManager storageManager) throws Exception
    {
       boolean deleted = false;
-      
+
       Transaction tx = new TransactionImpl(storageManager, postOffice);
 
       Iterator<MessageReference> iter = messageReferences.iterator();
@@ -511,7 +516,7 @@
       {
          MessageReference ref = iter.next();
          if (ref.getMessage().getMessageID() == messageID)
-         {        
+         {
             deliveringCount.incrementAndGet();
             tx.addAcknowledgement(ref);
             iter.remove();
@@ -521,14 +526,14 @@
       }
 
       tx.commit();
-      
+
       return deleted;
    }
-   
+
    public boolean expireMessage(final long messageID,
-         final StorageManager storageManager, final PostOffice postOffice,
-         final HierarchicalRepository<QueueSettings> queueSettingsRepository)
-         throws Exception
+                                final StorageManager storageManager,
+                                final PostOffice postOffice,
+                                final HierarchicalRepository<QueueSettings> queueSettingsRepository) throws Exception
    {
       Iterator<MessageReference> iter = messageReferences.iterator();
 
@@ -547,9 +552,9 @@
    }
 
    public boolean sendMessageToDLQ(final long messageID,
-         final StorageManager storageManager, final PostOffice postOffice,
-         final HierarchicalRepository<QueueSettings> queueSettingsRepository)
-         throws Exception
+                                   final StorageManager storageManager,
+                                   final PostOffice postOffice,
+                                   final HierarchicalRepository<QueueSettings> queueSettingsRepository) throws Exception
    {
       Iterator<MessageReference> iter = messageReferences.iterator();
 
@@ -568,8 +573,9 @@
    }
 
    public boolean moveMessage(final long messageID,
-         final Binding toBinding, final StorageManager storageManager,
-         final PostOffice postOffice) throws Exception
+                              final Binding toBinding,
+                              final StorageManager storageManager,
+                              final PostOffice postOffice) throws Exception
    {
       Iterator<MessageReference> iter = messageReferences.iterator();
 
@@ -586,11 +592,12 @@
       }
       return false;
    }
-   
-   public boolean changeMessagePriority(final long messageID, final byte newPriority,
-         final StorageManager storageManager, final PostOffice postOffice,
-         final HierarchicalRepository<QueueSettings> queueSettingsRepository)
-         throws Exception
+
+   public boolean changeMessagePriority(final long messageID,
+                                        final byte newPriority,
+                                        final StorageManager storageManager,
+                                        final PostOffice postOffice,
+                                        final HierarchicalRepository<QueueSettings> queueSettingsRepository) throws Exception
    {
       List<MessageReference> refs = list(null);
       for (MessageReference ref : refs)
@@ -608,42 +615,42 @@
       }
       return false;
    }
-   
+
    public void lock()
    {
       lock.lock();
    }
-   
+
    public void unlock()
-   {            
-      lock.unlock();     
+   {
+      lock.unlock();
    }
 
    public boolean isBackup()
    {
       return backup;
    }
-   
+
    public void setBackup(final boolean backup)
    {
       this.backup = backup;
       
+      this.direct = false;
+
       if (!backup)
       {
-         for (ScheduledDeliveryRunnable runnable: scheduledRunnables)
+         for (ScheduledDeliveryRunnable runnable : scheduledRunnables)
          {
             scheduleDelivery(runnable, runnable.getReference().getScheduledDeliveryTime());
          }
       }
-      
-      //TODO - what about waiting for the deliverAsync executor to finish?
    }
-   
+
    public MessageReference removeFirst()
    {
       return messageReferences.removeFirst();
    }
-   
+
    // Public
    // -----------------------------------------------------------------------------
 
@@ -654,7 +661,7 @@
          return true;
       }
 
-      QueueImpl qother = (QueueImpl) other;
+      QueueImpl qother = (QueueImpl)other;
 
       return name.equals(qother.name);
    }
@@ -672,13 +679,13 @@
       if (!first)
       {
          messagesAdded.incrementAndGet();
-         
+
          sizeBytes.addAndGet(ref.getMessage().getEncodeSize());
       }
-      
+
       if (checkAndSchedule(ref))
       {
-         return HandleStatus.HANDLED;         
+         return HandleStatus.HANDLED;
       }
 
       boolean add = false;
@@ -733,7 +740,7 @@
             // message
             deliver();
          }
-      }     
+      }
 
       return HandleStatus.HANDLED;
    }
@@ -741,32 +748,32 @@
    private boolean checkAndSchedule(final MessageReference ref)
    {
       long deliveryTime = ref.getScheduledDeliveryTime();
-      
+
       if (deliveryTime != 0 && scheduledExecutor != null)
-      {                     
+      {
          if (trace)
          {
-            log.trace("Scheduling delivery for " + ref + " to occur at "  + deliveryTime);
+            log.trace("Scheduling delivery for " + ref + " to occur at " + deliveryTime);
          }
-         
+
          ScheduledDeliveryRunnable runnable = new ScheduledDeliveryRunnable(ref);
 
          scheduledRunnables.add(runnable);
-         
+
          if (!backup)
-         {            
+         {
             scheduleDelivery(runnable, deliveryTime);
          }
 
-         return true;         
+         return true;
       }
-      return false;      
+      return false;
    }
-   
+
    private void scheduleDelivery(final ScheduledDeliveryRunnable runnable, final long deliveryTime)
    {
       long now = System.currentTimeMillis();
-      
+
       long delay = deliveryTime - now;
 
       Future<?> future = scheduledExecutor.schedule(runnable, delay, TimeUnit.MILLISECONDS);
@@ -788,7 +795,7 @@
       while (true)
       {
          Consumer consumer = consumers.get(pos);
-         
+
          pos = distributionPolicy.select(consumers, pos);
 
          HandleStatus status;
@@ -799,8 +806,10 @@
          }
          catch (Throwable t)
          {
-            log.warn("removing consumer which did not handle a message, " +
-                  "consumer=" + consumer + ", message=" + reference, t);
+            log.warn("removing consumer which did not handle a message, " + "consumer=" +
+                     consumer +
+                     ", message=" +
+                     reference, t);
 
             // If the consumer throws an exception we remove the consumer
             try
@@ -856,13 +865,13 @@
    {
       public void run()
       {
-         //Must be set to false *before* executing to avoid race
+         // Must be set to false *before* executing to avoid race
          waitingToDeliver.set(false);
-         
+
          deliver();
       }
-   }   
-   
+   }
+
    private class ScheduledDeliveryRunnable implements Runnable
    {
       private final MessageReference ref;
@@ -930,8 +939,9 @@
          {
             // Add back to the front of the queue
 
-            //TODO - need to replicate this so backup node also adds back to front of queue
-            
+            // TODO - need to replicate this so backup node also adds back to
+            // front of queue
+
             addFirst(ref);
          }
       }

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/ServerConsumerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/ServerConsumerImpl.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/ServerConsumerImpl.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -1,24 +1,24 @@
 /*
- * 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.
- */ 
+ * 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.server.impl;
 
@@ -36,6 +36,7 @@
 import org.jboss.messaging.core.server.ServerSession;
 import org.jboss.messaging.core.settings.HierarchicalRepository;
 import org.jboss.messaging.core.settings.impl.QueueSettings;
+import org.jboss.messaging.util.SimpleString;
 
 /**
  * Concrete implementation of a ClientConsumer. 
@@ -47,156 +48,162 @@
  */
 public class ServerConsumerImpl implements ServerConsumer
 {
-   // Constants ------------------------------------------------------------------------------------
+   // Constants
+   // ------------------------------------------------------------------------------------
 
    private static final Logger log = Logger.getLogger(ServerConsumerImpl.class);
 
-   // Static ---------------------------------------------------------------------------------------
+   // Static
+   // ---------------------------------------------------------------------------------------
 
-   // Attributes -----------------------------------------------------------------------------------
+   // Attributes
+   // -----------------------------------------------------------------------------------
 
    private final boolean trace = log.isTraceEnabled();
 
    private final long id;
-   
+
    private final Queue messageQueue;
-   
+
    private final Filter filter;
-   
+
    private final ServerSession session;
-         
+
    private final Object startStopLock = new Object();
 
    private final AtomicInteger availableCredits;
-   
+
    private boolean started;
-    
+
    private final StorageManager storageManager;
-   
+
    private final HierarchicalRepository<QueueSettings> queueSettingsRepository;
-   
+
    private final PostOffice postOffice;
-   
-   // Constructors ---------------------------------------------------------------------------------
- 
-   public ServerConsumerImpl(final long id, final ServerSession session,
-                      final Queue messageQueue, final Filter filter,
-   		             final boolean enableFlowControl, final int maxRate, 
-					       final boolean started,					      
-					       final StorageManager storageManager,
-					       final HierarchicalRepository<QueueSettings> queueSettingsRepository,
-					       final PostOffice postOffice)
+
+   // Constructors
+   // ---------------------------------------------------------------------------------
+
+   public ServerConsumerImpl(final long id,
+                             final ServerSession session,
+                             final Queue messageQueue,
+                             final Filter filter,
+                             final boolean enableFlowControl,
+                             final int maxRate,
+                             final boolean started,
+                             final StorageManager storageManager,
+                             final HierarchicalRepository<QueueSettings> queueSettingsRepository,
+                             final PostOffice postOffice)
    {
       this.id = id;
-      
+
       this.messageQueue = messageQueue;
-      
+
       this.filter = filter;
-      
-      this.session = session;              
-      
+
+      this.session = session;
+
       this.started = started;
-      
+
       if (enableFlowControl)
       {
          availableCredits = new AtomicInteger(0);
       }
       else
       {
-      	availableCredits = null;
+         availableCredits = null;
       }
-  
+
       this.storageManager = storageManager;
-      
+
       this.queueSettingsRepository = queueSettingsRepository;
-      
+
       this.postOffice = postOffice;
-                
+
       messageQueue.addConsumer(this);
    }
-   
-   // ServerConsumer implementation ----------------------------------------------------------------------
 
+   // ServerConsumer implementation
+   // ----------------------------------------------------------------------
+
    public long getID()
    {
-   	return id;
+      return id;
    }
-   
-   public void handleReplicatedDeliveryResponse(final long messageID) throws Exception
+
+   public HandleStatus handle(MessageReference ref) throws Exception
    {
-      session.deliverDeferredDelivery(messageID);
-   }
-   
-   public HandleStatus handle(MessageReference ref) throws Exception
-   {                    
       if (availableCredits != null && availableCredits.get() <= 0)
       {
          return HandleStatus.BUSY;
       }
-      
+
       if (ref.getMessage().isExpired())
-      {         
+      {
          ref.expire(storageManager, postOffice, queueSettingsRepository);
-         
+
          return HandleStatus.HANDLED;
       }
 
       synchronized (startStopLock)
       {
-         // If the consumer is stopped then we don't accept the message, it should go back into the
+         // 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;
          }
-         
+
          ServerMessage message = ref.getMessage();
-         
+
          if (filter != null && !filter.match(message))
          {
             return HandleStatus.NO_MATCH;
          }
-                          
+
          if (availableCredits != null)
          {
             availableCredits.addAndGet(-message.getEncodeSize());
          }
-                   
+         
+       //  log.info(System.identityHashCode(this) + " Handling delivery " + ref.getMessage().getProperty(new SimpleString("count")));
+
          session.handleDelivery(ref, this);
-         
+
          return HandleStatus.HANDLED;
       }
    }
-   
+
    public void close() throws Exception
-   {  
+   {
       setStarted(false);
 
       messageQueue.removeConsumer(this);
-           
-      session.removeConsumer(this);  
+
+      session.removeConsumer(this);
    }
-   
+
    public void setStarted(final boolean started)
    {
       boolean useStarted;
-      
+
       synchronized (startStopLock)
       {
-         this.started = started;   
-         
-         useStarted = started;         
+         this.started = started;
+
+         useStarted = started;
       }
-      
-      //Outside the lock
+
+      // Outside the lock
       if (useStarted)
       {
          promptDelivery();
       }
    }
-   
+
    public void receiveCredits(final int credits) throws Exception
-   {      
+   {
       if (availableCredits != null)
       {
          int previous = availableCredits.getAndAdd(credits);
@@ -205,9 +212,9 @@
          {
             promptDelivery();
          }
-      }  	
-   }      
-   
+      }
+   }
+
    public Queue getQueue()
    {
       return messageQueue;
@@ -215,35 +222,42 @@
 
    public void deliverMessage(final long messageID) throws Exception
    {
-      //Deliver a specific message from the queue - this is used when replicating delivery state
-      //We can't just deliver the next message since there may be multiple sessions on the same queue
-      //delivering concurrently
-      //and we could end up with different delivery state on backup compare to live
-      //So we need the message id so we can be sure the backup session has the same delivery state
+      // Deliver a specific message from the queue - this is used when
+      // replicating delivery state
+      // We can't just deliver the next message since there may be multiple
+      // sessions on the same queue
+      // delivering concurrently
+      // and we could end up with different delivery state on backup compare to
+      // live
+      // So we need the message id so we can be sure the backup session has the
+      // same delivery state
       MessageReference ref = messageQueue.removeReferenceWithID(messageID);
-      
+
       if (ref == null)
       {
          throw new IllegalStateException("Cannot find reference " + messageID);
       }
-      
+
       HandleStatus handled = handle(ref);
-                  
+
       if (handled != HandleStatus.HANDLED)
       {
          throw new IllegalStateException("Failed to handle replicated reference " + messageID);
       }
    }
-   
-   // Public -----------------------------------------------------------------------------
-     
-   // Private --------------------------------------------------------------------------------------
 
+   // Public
+   // -----------------------------------------------------------------------------
+
+   // Private
+   // --------------------------------------------------------------------------------------
+
    private void promptDelivery()
    {
       session.promptDelivery(messageQueue);
-   } 
-   
-   // Inner classes ------------------------------------------------------------------------
-   
+   }
+
+   // Inner classes
+   // ------------------------------------------------------------------------
+
 }

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/ServerMessageImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/ServerMessageImpl.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/ServerMessageImpl.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -1,24 +1,24 @@
 /*
- * 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.
- */ 
+ * 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.server.impl;
 
@@ -42,92 +42,96 @@
 public class ServerMessageImpl extends MessageImpl implements ServerMessage
 {
    private long messageID;
-    
+
    private final AtomicInteger durableRefCount = new AtomicInteger(0);
-   
+
    /** Global reference counts for paging control */
    private final AtomicInteger refCount = new AtomicInteger(0);
-              
+
    /*
     * Constructor for when reading from network
     */
    public ServerMessageImpl()
-   {      
+   {
    }
-   
+
    /*
     * Construct a MessageImpl from storage
     */
    public ServerMessageImpl(final long messageID)
    {
       super();
-      
-      this.messageID = messageID;      
+
+      this.messageID = messageID;
    }
-   
+
    /*
     * Copy constructor
     */
    public ServerMessageImpl(final ServerMessageImpl other)
    {
       super(other);
-      
+
       this.messageID = other.messageID;
    }
-   
+
    /**
     * Only used in testing
     */
-   public ServerMessageImpl(final byte type, final boolean durable, final long expiration,
-                            final long timestamp, final byte priority, MessagingBuffer buffer)
+   public ServerMessageImpl(final byte type,
+                            final boolean durable,
+                            final long expiration,
+                            final long timestamp,
+                            final byte priority,
+                            MessagingBuffer buffer)
    {
       super(type, durable, expiration, timestamp, priority, buffer);
    }
-   
+
    public long getMessageID()
    {
       return messageID;
    }
-   
+
    public void setMessageID(final long id)
    {
       this.messageID = id;
    }
-   
+
    public MessageReference createReference(final Queue queue)
    {
       MessageReference ref = new MessageReferenceImpl(this, queue);
-       
+
       if (durable && queue.isDurable())
       {
          durableRefCount.incrementAndGet();
       }
-      
+
       refCount.incrementAndGet();
-      
+
       return ref;
    }
-   
+
    public int getDurableRefCount()
    {
       return durableRefCount.get();
    }
-   
+
    public int decrementDurableRefCount()
    {
       return durableRefCount.decrementAndGet();
    }
-   
+
    public int incrementReference(boolean durable)
    {
       if (durable)
       {
          durableRefCount.incrementAndGet();
       }
-      
+
       return refCount.incrementAndGet();
    }
-     
+
    public int decrementRefCount()
    {
       return refCount.decrementAndGet();
@@ -137,13 +141,16 @@
    {
       return refCount.get();
    }
-   
+
    public int getMemoryEstimate()
    {
       // This is just an estimate...
-      // due to memory alignments and JVM implementation this could be very different from reality
-      return getEncodeSize() +
-             (16 + 4) * 2 +// Each AtomicInteger consumes 16 bytes for the Object and ObjectReference + 4 bytes for the internal integer
+      // due to memory alignments and JVM implementation this could be very
+      // different from reality
+      return getEncodeSize() + (16 + 4) * 2 + // Each AtomicInteger consumes
+                                                // 16 bytes for the Object and
+                                                // ObjectReference + 4 bytes for
+                                                // the internal integer
              8; // MessageID
 
    }
@@ -153,4 +160,3 @@
       return new ServerMessageImpl(this);
    }  
 }
-

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/ServerProducerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/ServerProducerImpl.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/ServerProducerImpl.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -28,7 +28,7 @@
 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.ProducerFlowCreditMessage;
+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;
@@ -126,7 +126,7 @@
 	{
 	   creditsToSend.addAndGet(-credits);
 	   
-		Packet packet = new ProducerFlowCreditMessage(id, credits);
+		Packet packet = new SessionProducerFlowCreditMessage(id, credits);
 		
 		channel.send( packet);	
 	}

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -3,17 +3,17 @@
  * 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
@@ -54,9 +54,9 @@
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateConsumerResponseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateProducerResponseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionQueueQueryResponseMessage;
-import org.jboss.messaging.core.remoting.impl.wireformat.SessionReplicateDeliveryMessage;
-import org.jboss.messaging.core.remoting.impl.wireformat.SessionReplicateDeliveryResponseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAResponseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.cluster.SessionReplicateDeliveryMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.cluster.SessionReplicateSendMessage;
 import org.jboss.messaging.core.security.CheckType;
 import org.jboss.messaging.core.security.SecurityStore;
 import org.jboss.messaging.core.server.Delivery;
@@ -99,7 +99,7 @@
    private final boolean trace = log.isTraceEnabled();
 
    private final String name;
-   
+
    private final long id;
 
    private final String username;
@@ -139,42 +139,39 @@
    private final SecurityStore securityStore;
 
    private final Channel channel;
-   
-   private final Channel replicatingChannel;
-   
-   private final java.util.Queue<Delivery> deferredDeliveries = new ConcurrentLinkedQueue<Delivery>();
-   
+
+   // private final Channel replicatingChannel;
+
    private final MessagingServer server;
-   
+
    private volatile boolean started = false;
 
    private final List<Runnable> failureRunners = new ArrayList<Runnable>();
-   
+
    private final IDGenerator idGenerator = new IDGenerator(0);
-   
+
    // Constructors
    // ---------------------------------------------------------------------------------
 
-   public ServerSessionImpl(
-            final String name,
-            final long id,
-            final String username,
-            final String password,
-            final boolean autoCommitSends,
-            final boolean autoCommitAcks,
-            final boolean xa,
-            final RemotingConnection remotingConnection,
-            final StorageManager storageManager,
-            final PostOffice postOffice,
-            final HierarchicalRepository<QueueSettings> queueSettingsRepository,
-            final ResourceManager resourceManager,
-            final SecurityStore securityStore,
-            final Executor executor,
-            final Channel channel,
-            final MessagingServer server) throws Exception
+   public ServerSessionImpl(final String name,
+                            final long id,
+                            final String username,
+                            final String password,
+                            final boolean autoCommitSends,
+                            final boolean autoCommitAcks,
+                            final boolean xa,
+                            final RemotingConnection remotingConnection,
+                            final StorageManager storageManager,
+                            final PostOffice postOffice,
+                            final HierarchicalRepository<QueueSettings> queueSettingsRepository,
+                            final ResourceManager resourceManager,
+                            final SecurityStore securityStore,
+                            final Executor executor,
+                            final Channel channel,
+                            final MessagingServer server) throws Exception
    {
       this.name = name;
-      
+
       this.id = id;
 
       this.username = username;
@@ -207,9 +204,9 @@
       }
 
       this.channel = channel;
-      
-      this.replicatingChannel = channel.getReplicatingChannel();
-      
+
+      // this.replicatingChannel = channel.getReplicatingChannel();
+
       this.server = server;
    }
 
@@ -243,8 +240,7 @@
    {
       if (consumers.remove(consumer.getID()) == null)
       {
-         throw new IllegalStateException("Cannot find consumer with id " + consumer.getID()
-                        + " to remove");
+         throw new IllegalStateException("Cannot find consumer with id " + consumer.getID() + " to remove");
       }
    }
 
@@ -252,50 +248,38 @@
    {
       if (producers.remove(producer.getID()) == null)
       {
-         throw new IllegalStateException("Cannot find producer with id " + producer.getID()
-                        + " to remove");
+         throw new IllegalStateException("Cannot find producer with id " + producer.getID() + " to remove");
       }
    }
 
    public void handleDelivery(final MessageReference ref, final ServerConsumer consumer)
    {
-      Delivery delivery;
-
       long nextID = deliveryIDSequence.getAndIncrement();
 
-      delivery = new DeliveryImpl(ref, consumer.getID(), nextID, channel);
+      final Delivery delivery = new DeliveryImpl(ref, consumer.getID(), nextID, channel);
 
       deliveries.add(delivery);
-      
-      if (replicatingChannel != null)
+
+      if (channel.getReplicatingChannel() != null)
       {
-         deferredDeliveries.add(delivery);
-         
          Packet msg = new SessionReplicateDeliveryMessage(consumer.getID(), ref.getMessage().getMessageID());
-       
-         replicatingChannel.send(msg);
+
+         Runnable action = new Runnable()
+         {
+            public void run()
+            {
+               delivery.deliver();
+            }
+         };
+
+         channel.replicatePacket(msg, action);
       }
       else
-      {      
+      {
          delivery.deliver();
       }
    }
-   
-   public void deliverDeferredDelivery(final long messageID)
-   {
-      for (Delivery del : deliveries)
-      {
-         long id = del.getReference().getMessage().getMessageID();
 
-         if (id == messageID)
-         {
-            del.deliver();
-
-            break;
-         }
-      }
-   }
-
    public void setStarted(final boolean s) throws Exception
    {
       Set<ServerConsumer> consumersClone = new HashSet<ServerConsumer>(consumers.values());
@@ -342,7 +326,7 @@
       deliveries.clear();
 
       channel.close();
-      
+
       server.removeSession(name);
    }
 
@@ -351,6 +335,8 @@
       queue.deliverAsync(executor);
    }
 
+   // long idSequence;
+
    public void send(final ServerMessage msg) throws Exception
    {
       // check the user has write access to this address.
@@ -371,9 +357,10 @@
       {
          if (!pager.page(msg))
          {
-            // We only set the messageID after we are sure the message is not being paged
+            // We only set the messageID after we are sure the message is not
+            // being paged
             // Paged messages won't have an ID until they are depaged
-            msg.setMessageID(storageManager.generateID());
+            // WHY?
 
             List<MessageReference> refs = postOffice.route(msg);
 
@@ -394,8 +381,7 @@
       }
    }
 
-   public void acknowledge(final long deliveryID, final boolean allUpTo)
-            throws Exception
+   public void acknowledge(final long deliveryID, final boolean allUpTo) throws Exception
    {
       /*
       Note that we do not consider it an error if the deliveries cannot be found to be acked.
@@ -537,8 +523,7 @@
       tx = new TransactionImpl(storageManager, postOffice);
    }
 
-   public void cancel(final long deliveryID, final boolean expired)
-            throws Exception
+   public void cancel(final long deliveryID, final boolean expired) throws Exception
    {
       if (deliveryID == -1)
       {
@@ -559,8 +544,7 @@
 
          try
          {
-            Transaction cancelTx = new TransactionImpl(storageManager,
-                     postOffice);
+            Transaction cancelTx = new TransactionImpl(storageManager, postOffice);
 
             for (Delivery del : deliveries)
             {
@@ -574,11 +558,11 @@
          finally
          {
          }
-         //finally (TODO: enable this back)
+         // finally (TODO: enable this back)
          {
-            //Now unlock
+            // Now unlock
 
-            for (Queue queue: locked)
+            for (Queue queue : locked)
             {
                queue.unlock();
             }
@@ -586,8 +570,10 @@
       }
       else if (expired)
       {
-         if (deliveryID == -1) { throw new IllegalArgumentException(
-                  "Invalid delivery id"); }
+         if (deliveryID == -1)
+         {
+            throw new IllegalArgumentException("Invalid delivery id");
+         }
 
          // Expire a single reference
 
@@ -597,8 +583,7 @@
 
             if (delivery.getDeliveryID() == deliveryID)
             {
-               delivery.getReference().expire(storageManager, postOffice,
-                        queueSettingsRepository);
+               delivery.getReference().expire(storageManager, postOffice, queueSettingsRepository);
 
                iter.remove();
 
@@ -624,13 +609,11 @@
       }
    }
 
-   public SessionXAResponseMessage XACommit(final boolean onePhase,
-            final Xid xid) throws Exception
+   public SessionXAResponseMessage XACommit(final boolean onePhase, final Xid xid) throws Exception
    {
       if (tx != null)
       {
-         final String msg = "Cannot commit, session is currently doing work in transaction "
-                  + tx.getXid();
+         final String msg = "Cannot commit, session is currently doing work in transaction " + tx.getXid();
 
          return new SessionXAResponseMessage(true, XAException.XAER_PROTO, msg);
       }
@@ -644,9 +627,12 @@
          return new SessionXAResponseMessage(true, XAException.XAER_NOTA, msg);
       }
 
-      if (theTx.getState() == Transaction.State.SUSPENDED) { return new SessionXAResponseMessage(
-               true, XAException.XAER_PROTO,
-               "Cannot commit transaction, it is suspended " + xid); }
+      if (theTx.getState() == Transaction.State.SUSPENDED)
+      {
+         return new SessionXAResponseMessage(true,
+                                             XAException.XAER_PROTO,
+                                             "Cannot commit transaction, it is suspended " + xid);
+      }
 
       theTx.commit();
 
@@ -662,8 +648,7 @@
       return new SessionXAResponseMessage(false, XAResource.XA_OK, null);
    }
 
-   public SessionXAResponseMessage XAEnd(final Xid xid, final boolean failed)
-            throws Exception
+   public SessionXAResponseMessage XAEnd(final Xid xid, final boolean failed) throws Exception
    {
       if (tx != null && tx.getXid().equals(xid))
       {
@@ -671,8 +656,7 @@
          {
             final String msg = "Cannot end, transaction is suspended";
 
-            return new SessionXAResponseMessage(true, XAException.XAER_PROTO,
-                     msg);
+            return new SessionXAResponseMessage(true, XAException.XAER_PROTO, msg);
          }
 
          tx = null;
@@ -687,19 +671,16 @@
 
          if (theTx == null)
          {
-            final String msg = "Cannot find suspended transaction to end "
-                     + xid;
+            final String msg = "Cannot find suspended transaction to end " + xid;
 
-            return new SessionXAResponseMessage(true, XAException.XAER_NOTA,
-                     msg);
+            return new SessionXAResponseMessage(true, XAException.XAER_NOTA, msg);
          }
 
          if (theTx.getState() != Transaction.State.SUSPENDED)
          {
             final String msg = "Transaction is not suspended " + xid;
 
-            return new SessionXAResponseMessage(true, XAException.XAER_PROTO,
-                     msg);
+            return new SessionXAResponseMessage(true, XAException.XAER_PROTO, msg);
          }
 
          theTx.resume();
@@ -727,9 +708,10 @@
          return new SessionXAResponseMessage(true, XAException.XAER_NOTA, msg);
       }
 
-      if (theTx.getState() == Transaction.State.SUSPENDED) { return new SessionXAResponseMessage(
-               true, XAException.XAER_PROTO, "Cannot join tx, it is suspended "
-                        + xid); }
+      if (theTx.getState() == Transaction.State.SUSPENDED)
+      {
+         return new SessionXAResponseMessage(true, XAException.XAER_PROTO, "Cannot join tx, it is suspended " + xid);
+      }
 
       tx = theTx;
 
@@ -740,8 +722,7 @@
    {
       if (tx != null)
       {
-         final String msg = "Cannot commit, session is currently doing work in a transaction "
-                  + tx.getXid();
+         final String msg = "Cannot commit, session is currently doing work in a transaction " + tx.getXid();
 
          return new SessionXAResponseMessage(true, XAException.XAER_PROTO, msg);
       }
@@ -755,9 +736,12 @@
          return new SessionXAResponseMessage(true, XAException.XAER_NOTA, msg);
       }
 
-      if (theTx.getState() == Transaction.State.SUSPENDED) { return new SessionXAResponseMessage(
-               true, XAException.XAER_PROTO,
-               "Cannot prepare transaction, it is suspended " + xid); }
+      if (theTx.getState() == Transaction.State.SUSPENDED)
+      {
+         return new SessionXAResponseMessage(true,
+                                             XAException.XAER_PROTO,
+                                             "Cannot prepare transaction, it is suspended " + xid);
+      }
 
       if (theTx.isEmpty())
       {
@@ -769,8 +753,7 @@
          {
             final String msg = "Failed to remove transaction: " + xid;
 
-            return new SessionXAResponseMessage(true, XAException.XAER_PROTO,
-                     msg);
+            return new SessionXAResponseMessage(true, XAException.XAER_PROTO, msg);
          }
 
          return new SessionXAResponseMessage(false, XAResource.XA_RDONLY, null);
@@ -787,8 +770,7 @@
    {
       if (tx != null)
       {
-         final String msg = "Cannot resume, session is currently doing work in a transaction "
-                  + tx.getXid();
+         final String msg = "Cannot resume, session is currently doing work in a transaction " + tx.getXid();
 
          return new SessionXAResponseMessage(true, XAException.XAER_PROTO, msg);
       }
@@ -802,9 +784,12 @@
          return new SessionXAResponseMessage(true, XAException.XAER_NOTA, msg);
       }
 
-      if (theTx.getState() != Transaction.State.SUSPENDED) { return new SessionXAResponseMessage(
-               true, XAException.XAER_PROTO,
-               "Cannot resume transaction, it is not suspended " + xid); }
+      if (theTx.getState() != Transaction.State.SUSPENDED)
+      {
+         return new SessionXAResponseMessage(true,
+                                             XAException.XAER_PROTO,
+                                             "Cannot resume transaction, it is not suspended " + xid);
+      }
 
       tx = theTx;
 
@@ -817,8 +802,7 @@
    {
       if (tx != null)
       {
-         final String msg = "Cannot roll back, session is currently doing work in a transaction "
-                  + tx.getXid();
+         final String msg = "Cannot roll back, session is currently doing work in a transaction " + tx.getXid();
 
          return new SessionXAResponseMessage(true, XAException.XAER_PROTO, msg);
       }
@@ -832,9 +816,12 @@
          return new SessionXAResponseMessage(true, XAException.XAER_NOTA, msg);
       }
 
-      if (theTx.getState() == Transaction.State.SUSPENDED) { return new SessionXAResponseMessage(
-               true, XAException.XAER_PROTO,
-               "Cannot rollback transaction, it is suspended " + xid); }
+      if (theTx.getState() == Transaction.State.SUSPENDED)
+      {
+         return new SessionXAResponseMessage(true,
+                                             XAException.XAER_PROTO,
+                                             "Cannot rollback transaction, it is suspended " + xid);
+      }
 
       theTx.rollback(queueSettingsRepository);
 
@@ -854,8 +841,7 @@
    {
       if (tx != null)
       {
-         final String msg = "Cannot start, session is already doing work in a transaction "
-                  + tx.getXid();
+         final String msg = "Cannot start, session is already doing work in a transaction " + tx.getXid();
 
          return new SessionXAResponseMessage(true, XAException.XAER_PROTO, msg);
       }
@@ -866,8 +852,7 @@
 
       if (!added)
       {
-         final String msg = "Cannot start, there is already a xid "
-                  + tx.getXid();
+         final String msg = "Cannot start, there is already a xid " + tx.getXid();
 
          return new SessionXAResponseMessage(true, XAException.XAER_DUPID, msg);
       }
@@ -886,8 +871,7 @@
 
       if (tx.getState() == Transaction.State.SUSPENDED)
       {
-         final String msg = "Cannot suspend, transaction is already suspended "
-                  + tx.getXid();
+         final String msg = "Cannot suspend, transaction is already suspended " + tx.getXid();
 
          return new SessionXAResponseMessage(true, XAException.XAER_PROTO, msg);
       }
@@ -914,14 +898,14 @@
       return resourceManager.setTimeoutSeconds(timeoutSeconds);
    }
 
-   public void addDestination(final SimpleString address,
-            final boolean durable, final boolean temporary) throws Exception
+   public void addDestination(final SimpleString address, final boolean durable, final boolean temporary) throws Exception
    {
       securityStore.check(address, CheckType.CREATE, this);
 
-      if (!postOffice.addDestination(address, durable)) { throw new MessagingException(
-               MessagingException.ADDRESS_EXISTS, "Address already exists: "
-                        + address); }
+      if (!postOffice.addDestination(address, durable))
+      {
+         throw new MessagingException(MessagingException.ADDRESS_EXISTS, "Address already exists: " + address);
+      }
 
       if (temporary)
       {
@@ -931,40 +915,38 @@
          // session is closed.
          // It is up to the user to delete the address when finished with it
 
-        failureRunners.add(
-              new Runnable()
-              {
-                 public void run()
-                 {
-                    try
-                    {
-                       postOffice.removeDestination(address, durable);
-                    }
-                    catch (Exception e)
-                    {
-                       log.error("Failed to remove temporary address " + address);
-                    }
-                 }
-              }
-         );
+         failureRunners.add(new Runnable()
+         {
+            public void run()
+            {
+               try
+               {
+                  postOffice.removeDestination(address, durable);
+               }
+               catch (Exception e)
+               {
+                  log.error("Failed to remove temporary address " + address);
+               }
+            }
+         });
       }
    }
-   
-   public void removeDestination(final SimpleString address,
-            final boolean durable) throws Exception
+
+   public void removeDestination(final SimpleString address, final boolean durable) throws Exception
    {
       securityStore.check(address, CheckType.CREATE, this);
 
       if (!postOffice.removeDestination(address, durable))
       {
-         throw new MessagingException(MessagingException.ADDRESS_DOES_NOT_EXIST,
-               "Address does not exist: " + address);
+         throw new MessagingException(MessagingException.ADDRESS_DOES_NOT_EXIST, "Address does not exist: " + address);
       }
    }
 
    public void createQueue(final SimpleString address,
-            final SimpleString queueName, final SimpleString filterString,
-            final boolean durable, final boolean temporary) throws Exception
+                           final SimpleString queueName,
+                           final SimpleString filterString,
+                           final boolean durable,
+                           final boolean temporary) throws Exception
    {
       // make sure the user has privileges to create this queue
       if (!postOffice.containsDestination(address))
@@ -974,8 +956,10 @@
 
       Binding binding = postOffice.getBinding(queueName);
 
-      if (binding != null) { throw new MessagingException(
-               MessagingException.QUEUE_EXISTS); }
+      if (binding != null)
+      {
+         throw new MessagingException(MessagingException.QUEUE_EXISTS);
+      }
 
       Filter filter = null;
 
@@ -995,24 +979,21 @@
          // It is up to the user to delete the queue when finished with it
 
          final Queue queue = binding.getQueue();
-         
-         failureRunners.add(
-                  new Runnable()
-                  {
-                     public void run()
-                     {
-                        try
-                        {
-                           postOffice.removeBinding(queue.getName());
-                        }
-                        catch (Exception e)
-                        {
-                           log.error("Failed to remove temporary queue "
-                                    + queue.getName());
-                        }
-                     }
-                  }
-             );        
+
+         failureRunners.add(new Runnable()
+         {
+            public void run()
+            {
+               try
+               {
+                  postOffice.removeBinding(queue.getName());
+               }
+               catch (Exception e)
+               {
+                  log.error("Failed to remove temporary queue " + queue.getName());
+               }
+            }
+         });
       }
    }
 
@@ -1027,9 +1008,10 @@
 
       Queue queue = binding.getQueue();
 
-      if (queue.getConsumerCount() != 0) { throw new MessagingException(
-               MessagingException.ILLEGAL_STATE,
-               "Cannot delete queue - it has consumers"); }
+      if (queue.getConsumerCount() != 0)
+      {
+         throw new MessagingException(MessagingException.ILLEGAL_STATE, "Cannot delete queue - it has consumers");
+      }
 
       if (queue.isDurable())
       {
@@ -1037,10 +1019,10 @@
       }
    }
 
-   public SessionCreateConsumerResponseMessage createConsumer(
-            final SimpleString queueName,
-            final SimpleString filterString, int windowSize, int maxRate)
-            throws Exception
+   public SessionCreateConsumerResponseMessage createConsumer(final SimpleString queueName,
+                                                              final SimpleString filterString,
+                                                              int windowSize,
+                                                              int maxRate) throws Exception
    {
       Binding binding = postOffice.getBinding(queueName);
 
@@ -1063,19 +1045,25 @@
 
       QueueSettings qs = queueSettingsRepository.getMatch(queueName.toString());
 
-      Integer queueWindowSize = (Integer) qs.getConsumerWindowSize();
+      Integer queueWindowSize = (Integer)qs.getConsumerWindowSize();
 
       windowSize = queueWindowSize != null ? queueWindowSize : windowSize;
 
-      Integer queueMaxRate = queueSettingsRepository.getMatch(
-               queueName.toString()).getConsumerMaxRate();
+      Integer queueMaxRate = queueSettingsRepository.getMatch(queueName.toString()).getConsumerMaxRate();
 
       maxRate = queueMaxRate != null ? queueMaxRate : maxRate;
-      
-      ServerConsumer consumer = new ServerConsumerImpl(idGenerator.generateID(), this,
-               binding.getQueue(), filter, windowSize != -1, maxRate, started,
-               storageManager, queueSettingsRepository, postOffice);
 
+      ServerConsumer consumer = new ServerConsumerImpl(idGenerator.generateID(),
+                                                       this,
+                                                       binding.getQueue(),
+                                                       filter,
+                                                       windowSize != -1,
+                                                       maxRate,
+                                                       started,
+                                                       storageManager,
+                                                       queueSettingsRepository,
+                                                       postOffice);
+
       SessionCreateConsumerResponseMessage response = new SessionCreateConsumerResponseMessage(windowSize);
 
       consumers.put(consumer.getID(), consumer);
@@ -1100,12 +1088,13 @@
 
          Filter filter = queue.getFilter();
 
-         SimpleString filterString = filter == null ? null : filter
-                  .getFilterString();
+         SimpleString filterString = filter == null ? null : filter.getFilterString();
          // TODO: Remove MAX-SIZE-BYTES from SessionQueueQueryResponse.
-         response = new SessionQueueQueryResponseMessage(queue.isDurable(), 
-                 queue.getConsumerCount(), queue.getMessageCount(),
-                 filterString, binding.getAddress());
+         response = new SessionQueueQueryResponseMessage(queue.isDurable(),
+                                                         queue.getConsumerCount(),
+                                                         queue.getMessageCount(),
+                                                         filterString,
+                                                         binding.getAddress());
       }
       else
       {
@@ -1115,11 +1104,12 @@
       return response;
    }
 
-   public SessionBindingQueryResponseMessage executeBindingQuery(
-            final SimpleString address) throws Exception
+   public SessionBindingQueryResponseMessage executeBindingQuery(final SimpleString address) throws Exception
    {
-      if (address == null) { throw new IllegalArgumentException(
-               "Address is null"); }
+      if (address == null)
+      {
+         throw new IllegalArgumentException("Address is null");
+      }
 
       boolean exists = postOffice.containsDestination(address);
 
@@ -1138,8 +1128,7 @@
       return new SessionBindingQueryResponseMessage(exists, queueNames);
    }
 
-   public void createBrowser(final SimpleString queueName, final SimpleString filterString)
-            throws Exception
+   public void createBrowser(final SimpleString queueName, final SimpleString filterString) throws Exception
    {
       Binding binding = postOffice.getBinding(queueName);
 
@@ -1150,9 +1139,10 @@
 
       securityStore.check(binding.getAddress(), CheckType.READ, this);
 
-      ServerBrowserImpl browser = new ServerBrowserImpl(idGenerator.generateID(), this, binding
-               .getQueue(), filterString == null ? null : filterString
-               .toString());
+      ServerBrowserImpl browser = new ServerBrowserImpl(idGenerator.generateID(),
+                                                        this,
+                                                        binding.getQueue(),
+                                                        filterString == null ? null : filterString.toString());
 
       browsers.put(browser.getID(), browser);
    }
@@ -1166,9 +1156,9 @@
     *                   The actual window size used may be less than the specified window size if
     *                   it is overridden by any producer-window-size specified on the queue
     */
-   public SessionCreateProducerResponseMessage createProducer(
-            final SimpleString address,
-            final int windowSize, final int maxRate) throws Exception
+   public SessionCreateProducerResponseMessage createProducer(final SimpleString address,
+                                                              final int windowSize,
+                                                              final int maxRate) throws Exception
    {
       FlowController flowController = null;
 
@@ -1176,8 +1166,7 @@
 
       if (address != null)
       {
-         flowController = windowSize == -1 ? null : postOffice
-                  .getFlowController(address);
+         flowController = windowSize == -1 ? null : postOffice.getFlowController(address);
       }
 
       final int windowToUse = flowController == null ? -1 : windowSize;
@@ -1185,20 +1174,21 @@
       // Server window size is 0.75 client window size for producer flow control
       // (other way round to consumer flow control)
 
-      final int serverWindowSize = windowToUse == -1 ? -1
-               : (int) (windowToUse * 0.75);
+      final int serverWindowSize = windowToUse == -1 ? -1 : (int)(windowToUse * 0.75);
 
-      ServerProducerImpl producer = new ServerProducerImpl(idGenerator.generateID(), this,
-               address, flowController, serverWindowSize,
-               channel);
+      ServerProducerImpl producer = new ServerProducerImpl(idGenerator.generateID(),
+                                                           this,
+                                                           address,
+                                                           flowController,
+                                                           serverWindowSize,
+                                                           channel);
 
       producers.put(producer.getID(), producer);
 
       // Get some initial credits to send to the producer - we try for
       // windowToUse
 
-      int initialCredits = flowController == null ? -1 : flowController
-               .getInitialCredits(windowToUse, producer);
+      int initialCredits = flowController == null ? -1 : flowController.getInitialCredits(windowToUse, producer);
 
       return new SessionCreateProducerResponseMessage(initialCredits, maxRateToUse);
    }
@@ -1242,47 +1232,31 @@
    {
       producers.get(producerID).send(message);
    }
-   
+
    public void handleReplicateDelivery(final long consumerID, final long messageID) throws Exception
    {
       consumers.get(consumerID).deliverMessage(messageID);
-      
-      Packet response = new SessionReplicateDeliveryResponseMessage();
-      
-      channel.send(response);
    }
-      
-   public void handleDeferredDelivery()
-   {  
-      Delivery delivery = deferredDeliveries.poll();
-      
-      if (delivery == null)
-      {
-         throw new IllegalStateException("Cannot find deferred delivery to deliver");
-      }
-      
-      delivery.deliver();
-   }
-   
+
    public void transferConnection(final RemotingConnection newConnection)
-   {           
+   {
       remotingConnection.removeFailureListener(this);
-      
-      channel.transferConnection(newConnection);            
-                        
-      //Destroy the old connection
+
+      channel.transferConnection(newConnection);
+
+      // Destroy the old connection
       remotingConnection.destroy();
-      
+
       remotingConnection = newConnection;
-      
-      remotingConnection.addFailureListener(this);      
+
+      remotingConnection.addFailureListener(this);
    }
-   
+
    public int replayCommands(final int lastReceivedCommandID)
-   {    
+   {
       return channel.replayCommands(lastReceivedCommandID);
    }
-   
+
    // FailureListener implementation
    // --------------------------------------------------------------------
 
@@ -1290,7 +1264,7 @@
    {
       try
       {
-         for (Runnable runner: failureRunners)
+         for (Runnable runner : failureRunners)
          {
             try
             {
@@ -1301,7 +1275,7 @@
                log.error("Failed to execute failure runner", t);
             }
          }
-         
+
          close();
       }
       catch (Throwable t)
@@ -1347,8 +1321,7 @@
          }
          else
          {
-            storageManager.storeAcknowledge(queue.getPersistenceID(), message
-                     .getMessageID());
+            storageManager.storeAcknowledge(queue.getPersistenceID(), message.getMessageID());
          }
       }
 

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionPacketHandler.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionPacketHandler.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionPacketHandler.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -1,32 +1,65 @@
 /*
- * 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.
+ * 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.server.impl;
 
+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;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_BINDINGQUERY;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_BROWSER_CLOSE;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_BROWSER_HASNEXTMESSAGE;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_BROWSER_NEXTMESSAGE;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_BROWSER_RESET;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_CANCEL;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_CLOSE;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_COMMIT;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_CONSUMER_CLOSE;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_CREATEBROWSER;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_CREATECONSUMER;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_CREATEPRODUCER;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_CREATEQUEUE;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_DELETE_QUEUE;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_FLOWTOKEN;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_PRODUCER_CLOSE;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_QUEUEQUERY;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_REMOVE_DESTINATION;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_REPLICATE_DELIVERY;
-import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_REPLICATE_DELIVERY_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_REPLICATE_SEND;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_ROLLBACK;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_SEND;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_START;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_STOP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_XA_COMMIT;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_XA_END;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_XA_FORGET;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_XA_GET_TIMEOUT;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_XA_INDOUBT_XIDS;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_XA_JOIN;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_XA_PREPARE;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_XA_RESUME;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_XA_ROLLBACK;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_XA_SET_TIMEOUT;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_XA_START;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_XA_SUSPEND;
 
 import java.util.List;
 
@@ -34,16 +67,15 @@
 
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.persistence.StorageManager;
 import org.jboss.messaging.core.remoting.Channel;
 import org.jboss.messaging.core.remoting.ChannelHandler;
 import org.jboss.messaging.core.remoting.Packet;
-import org.jboss.messaging.core.remoting.impl.wireformat.BrowseMessage;
 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.SendMessage;
 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;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowserCloseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowserHasNextMessageMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowserHasNextMessageResponseMessage;
@@ -51,17 +83,17 @@
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionBrowserResetMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionCancelMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionConsumerCloseMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionConsumerFlowCreditMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateBrowserMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateConsumerMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateProducerMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionCreateQueueMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionDeleteQueueMessage;
-import org.jboss.messaging.core.remoting.impl.wireformat.SessionFlowCreditMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionNullResponseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionProducerCloseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionQueueQueryMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionRemoveDestinationMessage;
-import org.jboss.messaging.core.remoting.impl.wireformat.SessionReplicateDeliveryMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXACommitMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAEndMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAForgetMessage;
@@ -74,6 +106,8 @@
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXASetTimeoutMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXASetTimeoutResponseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAStartMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.cluster.SessionReplicateDeliveryMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.cluster.SessionReplicateSendMessage;
 import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.core.server.ServerSession;
 
@@ -87,92 +121,155 @@
  */
 public class ServerSessionPacketHandler implements ChannelHandler
 {
-	private static final Logger log = Logger.getLogger(ServerSessionPacketHandler.class);
+   private static final Logger log = Logger.getLogger(ServerSessionPacketHandler.class);
 
-	private final ServerSession session;
-	
-	private final Channel channel;
+   private final ServerSession session;
 
-	public ServerSessionPacketHandler(final ServerSession session,
-	                                  final Channel channel)
+   private final Channel channel;
+
+   private final StorageManager storageManager;
+
+   public ServerSessionPacketHandler(final ServerSession session,
+                                     final Channel channel,
+                                     final StorageManager storageManager)
+
    {
-		this.session = session;
+      this.session = session;
 
-		this.channel = channel;
+      this.channel = channel;
+
+      this.storageManager = storageManager;
    }
 
    public long getID()
    {
       return session.getID();
    }
-   
+
    public void handlePacket(final Packet packet)
    {
+      if (packet.getType() == SESS_SEND)
+      {
+         SessionSendMessage req = (SessionSendMessage)packet;
+
+         ServerMessage msg = req.getServerMessage();
+
+         msg.setMessageID(storageManager.generateID());
+
+         if (channel.getReplicatingChannel() == null)
+         {
+            doHandlePacket(packet);
+         }
+         else
+         {
+            Runnable action = new Runnable()
+            {
+               public void run()
+               {
+                  doHandlePacket(packet);
+               }
+            };
+
+            Packet replPacket = new SessionReplicateSendMessage(req.getProducerID(), msg);
+
+            channel.replicatePacket(replPacket, action);
+         }
+      }
+      else
+      {
+         if (channel.getReplicatingChannel() == null || packet.getType() == SESS_REPLICATE_DELIVERY ||
+             packet.getType() == SESS_REPLICATE_SEND)
+         {
+            doHandlePacket(packet);
+         }
+         else
+         {            
+            Runnable action = new Runnable()
+            {
+               public void run()
+               {
+                  doHandlePacket(packet);
+               }
+            };
+
+            channel.replicatePacket(packet, action);
+         }
+      }
+
+   }
+
+   private void doHandlePacket(final Packet packet)
+   {
       Packet response = null;
 
       byte type = packet.getType();
-      
+
       try
       {
          switch (type)
          {
-            case PacketImpl.SESS_CREATECONSUMER:
+            case SESS_CREATECONSUMER:
             {
-               SessionCreateConsumerMessage request = (SessionCreateConsumerMessage) packet;
-               
-               response = session.createConsumer(request.getQueueName(), request.getFilterString(),            		                            
-               		                            request.getWindowSize(), request.getMaxRate());
+               SessionCreateConsumerMessage request = (SessionCreateConsumerMessage)packet;
+
+               response = session.createConsumer(request.getQueueName(),
+                                                 request.getFilterString(),
+                                                 request.getWindowSize(),
+                                                 request.getMaxRate());
                break;
             }
-            case PacketImpl.SESS_CREATEQUEUE:
+            case SESS_CREATEQUEUE:
             {
-               SessionCreateQueueMessage request = (SessionCreateQueueMessage) packet;
-               session.createQueue(request.getAddress(), request.getQueueName(), request
-                     .getFilterString(), request.isDurable(), request.isTemporary());
+               SessionCreateQueueMessage request = (SessionCreateQueueMessage)packet;
+               session.createQueue(request.getAddress(),
+                                   request.getQueueName(),
+                                   request.getFilterString(),
+                                   request.isDurable(),
+                                   request.isTemporary());
                response = new SessionNullResponseMessage();
                break;
             }
-            case PacketImpl.SESS_DELETE_QUEUE:
+            case SESS_DELETE_QUEUE:
             {
-               SessionDeleteQueueMessage request = (SessionDeleteQueueMessage) packet;
+               SessionDeleteQueueMessage request = (SessionDeleteQueueMessage)packet;
                session.deleteQueue(request.getQueueName());
                response = new SessionNullResponseMessage();
                break;
             }
-            case PacketImpl.SESS_QUEUEQUERY:
+            case SESS_QUEUEQUERY:
             {
-               SessionQueueQueryMessage request = (SessionQueueQueryMessage) packet;
+               SessionQueueQueryMessage request = (SessionQueueQueryMessage)packet;
                response = session.executeQueueQuery(request.getQueueName());
                break;
             }
-            case PacketImpl.SESS_BINDINGQUERY:
+            case SESS_BINDINGQUERY:
             {
                SessionBindingQueryMessage request = (SessionBindingQueryMessage)packet;
                response = session.executeBindingQuery(request.getAddress());
                break;
             }
-            case PacketImpl.SESS_CREATEBROWSER:
+            case SESS_CREATEBROWSER:
             {
-               SessionCreateBrowserMessage request = (SessionCreateBrowserMessage) packet;
+               SessionCreateBrowserMessage request = (SessionCreateBrowserMessage)packet;
                session.createBrowser(request.getQueueName(), request.getFilterString());
                response = new SessionNullResponseMessage();
                break;
             }
-            case PacketImpl.SESS_CREATEPRODUCER:
+            case SESS_CREATEPRODUCER:
             {
-               SessionCreateProducerMessage request = (SessionCreateProducerMessage) packet;
+               SessionCreateProducerMessage request = (SessionCreateProducerMessage)packet;
                response = session.createProducer(request.getAddress(), request.getWindowSize(), request.getMaxRate());
                break;
             }
-            case PacketImpl.SESS_CLOSE:
-            {;
+            case SESS_CLOSE:
+            {
                session.close();
                response = new SessionNullResponseMessage();
                break;
             }
-            case PacketImpl.SESS_ACKNOWLEDGE:
+            case SESS_ACKNOWLEDGE:
             {
-               SessionAcknowledgeMessage message = (SessionAcknowledgeMessage) packet;
+               SessionAcknowledgeMessage message = (SessionAcknowledgeMessage)packet;
                session.acknowledge(message.getDeliveryID(), message.isAllUpTo());
                if (message.isRequiresResponse())
                {
@@ -180,158 +277,166 @@
                }
                break;
             }
-            case PacketImpl.SESS_COMMIT:
+            case SESS_COMMIT:
             {
                session.commit();
                response = new SessionNullResponseMessage();
                break;
             }
-            case PacketImpl.SESS_ROLLBACK:
+            case SESS_ROLLBACK:
             {
                session.rollback();
                response = new SessionNullResponseMessage();
                break;
             }
-            case PacketImpl.SESS_CANCEL:
+            case SESS_CANCEL:
             {
-               SessionCancelMessage message = (SessionCancelMessage) packet;
+               SessionCancelMessage message = (SessionCancelMessage)packet;
                session.cancel(message.getDeliveryID(), message.isExpired());
-               //one way
+               // one way
                break;
             }
-            case PacketImpl.SESS_XA_COMMIT:
+            case SESS_XA_COMMIT:
             {
-               SessionXACommitMessage message = (SessionXACommitMessage) packet;
+               SessionXACommitMessage message = (SessionXACommitMessage)packet;
                response = session.XACommit(message.isOnePhase(), message.getXid());
                break;
             }
-            case PacketImpl.SESS_XA_END:
+            case SESS_XA_END:
             {
-               SessionXAEndMessage message = (SessionXAEndMessage) packet;
+               SessionXAEndMessage message = (SessionXAEndMessage)packet;
                response = session.XAEnd(message.getXid(), message.isFailed());
                break;
             }
-            case PacketImpl.SESS_XA_FORGET:
+            case SESS_XA_FORGET:
             {
-               SessionXAForgetMessage message = (SessionXAForgetMessage) packet;
+               SessionXAForgetMessage message = (SessionXAForgetMessage)packet;
                response = session.XAForget(message.getXid());
                break;
             }
-            case PacketImpl.SESS_XA_JOIN:
+            case SESS_XA_JOIN:
             {
-               SessionXAJoinMessage message = (SessionXAJoinMessage) packet;
+               SessionXAJoinMessage message = (SessionXAJoinMessage)packet;
                response = session.XAJoin(message.getXid());
                break;
             }
-            case PacketImpl.SESS_XA_RESUME:
+            case SESS_XA_RESUME:
             {
-               SessionXAResumeMessage message = (SessionXAResumeMessage) packet;
+               SessionXAResumeMessage message = (SessionXAResumeMessage)packet;
                response = session.XAResume(message.getXid());
                break;
             }
-            case PacketImpl.SESS_XA_ROLLBACK:
+            case SESS_XA_ROLLBACK:
             {
-               SessionXARollbackMessage message = (SessionXARollbackMessage) packet;
+               SessionXARollbackMessage message = (SessionXARollbackMessage)packet;
                response = session.XARollback(message.getXid());
                break;
             }
-            case PacketImpl.SESS_XA_START:
+            case SESS_XA_START:
             {
-               SessionXAStartMessage message = (SessionXAStartMessage) packet;
+               SessionXAStartMessage message = (SessionXAStartMessage)packet;
                response = session.XAStart(message.getXid());
                break;
             }
-            case PacketImpl.SESS_XA_SUSPEND:
+            case SESS_XA_SUSPEND:
             {
                response = session.XASuspend();
                break;
             }
-            case PacketImpl.SESS_XA_PREPARE:
+            case SESS_XA_PREPARE:
             {
-               SessionXAPrepareMessage message = (SessionXAPrepareMessage) packet;
+               SessionXAPrepareMessage message = (SessionXAPrepareMessage)packet;
                response = session.XAPrepare(message.getXid());
                break;
             }
-            case PacketImpl.SESS_XA_INDOUBT_XIDS:
+            case SESS_XA_INDOUBT_XIDS:
             {
                List<Xid> xids = session.getInDoubtXids();
                response = new SessionXAGetInDoubtXidsResponseMessage(xids);
                break;
             }
-            case PacketImpl.SESS_XA_GET_TIMEOUT:
+            case SESS_XA_GET_TIMEOUT:
             {
                response = new SessionXAGetTimeoutResponseMessage(session.getXATimeout());
                break;
             }
-            case PacketImpl.SESS_XA_SET_TIMEOUT:
+            case SESS_XA_SET_TIMEOUT:
             {
-               SessionXASetTimeoutMessage message = (SessionXASetTimeoutMessage) packet;
-               response = new SessionXASetTimeoutResponseMessage(session.setXATimeout(message
-                     .getTimeoutSeconds()));
+               SessionXASetTimeoutMessage message = (SessionXASetTimeoutMessage)packet;
+               response = new SessionXASetTimeoutResponseMessage(session.setXATimeout(message.getTimeoutSeconds()));
                break;
             }
-            case PacketImpl.SESS_ADD_DESTINATION:
+            case SESS_ADD_DESTINATION:
             {
-               SessionAddDestinationMessage message = (SessionAddDestinationMessage) packet;
+               SessionAddDestinationMessage message = (SessionAddDestinationMessage)packet;
                session.addDestination(message.getAddress(), message.isDurable(), message.isTemporary());
                response = new SessionNullResponseMessage();
                break;
             }
-            case PacketImpl.SESS_REMOVE_DESTINATION:
+            case SESS_REMOVE_DESTINATION:
             {
-               SessionRemoveDestinationMessage message = (SessionRemoveDestinationMessage) packet;
+               SessionRemoveDestinationMessage message = (SessionRemoveDestinationMessage)packet;
                session.removeDestination(message.getAddress(), message.isDurable());
                response = new SessionNullResponseMessage();
                break;
             }
-            case PacketImpl.SESS_START:
-            {            
-               session.setStarted(true);           
+            case SESS_START:
+            {
+               session.setStarted(true);
                break;
             }
-            case PacketImpl.SESS_STOP:
-            {            
-               session.setStarted(false);       
+            case SESS_STOP:
+            {
+               session.setStarted(false);
                response = new SessionNullResponseMessage();
                break;
             }
-            case PacketImpl.SESS_CONSUMER_CLOSE:
-            { 
+            case SESS_CONSUMER_CLOSE:
+            {
                SessionConsumerCloseMessage message = (SessionConsumerCloseMessage)packet;
                session.closeConsumer(message.getConsumerID());
                response = new SessionNullResponseMessage();
                break;
             }
-            case PacketImpl.SESS_PRODUCER_CLOSE:
-            { 
+            case SESS_PRODUCER_CLOSE:
+            {
                SessionProducerCloseMessage message = (SessionProducerCloseMessage)packet;
                session.closeProducer(message.getProducerID());
                response = new SessionNullResponseMessage();
                break;
             }
-            case PacketImpl.SESS_BROWSER_CLOSE:
-            { 
+            case SESS_BROWSER_CLOSE:
+            {
                SessionBrowserCloseMessage message = (SessionBrowserCloseMessage)packet;
                session.closeBrowser(message.getBrowserID());
                response = new SessionNullResponseMessage();
                break;
             }
-            case PacketImpl.SESS_FLOWTOKEN:
+            case SESS_FLOWTOKEN:
             {
-               SessionFlowCreditMessage message = (SessionFlowCreditMessage)packet;
+               SessionConsumerFlowCreditMessage message = (SessionConsumerFlowCreditMessage)packet;
                session.receiveConsumerCredits(message.getConsumerID(), message.getCredits());
                break;
             }
-            case PacketImpl.SESS_SEND:
-            {
-               SendMessage message = (SendMessage) packet;
-               session.sendProducerMessage(message.getProducerID(), message.getServerMessage());               
+            case SESS_SEND:
+            {               
+               SessionSendMessage message = (SessionSendMessage)packet;
+              // log.info("Got send " + message.getServerMessage().getMessageID());
+               session.sendProducerMessage(message.getProducerID(), message.getServerMessage());
                if (message.isRequiresResponse())
                {
                   response = new SessionNullResponseMessage();
                }
                break;
             }
+            case SESS_REPLICATE_SEND:
+            {               
+               SessionReplicateSendMessage message = (SessionReplicateSendMessage)packet;
+               //log.info("Got replicated send " + message.getServerMessage().getMessageID());
+               storageManager.setMaxID(message.getServerMessage().getMessageID());
+               session.sendProducerMessage(message.getProducerID(), message.getServerMessage());
+               break;
+            }
             case SESS_BROWSER_HASNEXTMESSAGE:
             {
                SessionBrowserHasNextMessageMessage message = (SessionBrowserHasNextMessageMessage)packet;
@@ -342,7 +447,7 @@
             {
                SessionBrowserNextMessageMessage message = (SessionBrowserNextMessageMessage)packet;
                ServerMessage smsg = session.browserNextMessage(message.getBrowserID());
-               response = new BrowseMessage(smsg);
+               response = new SessionBrowseMessage(smsg);
                break;
             }
             case SESS_BROWSER_RESET:
@@ -358,17 +463,12 @@
                session.handleReplicateDelivery(message.getConsumerID(), message.getMessageID());
                break;
             }
-            case SESS_REPLICATE_DELIVERY_RESP:
-            {
-               session.handleDeferredDelivery();
-               break;
-            }
             default:
             {
                response = new MessagingExceptionMessage(new MessagingException(MessagingException.UNSUPPORTED_PACKET,
-                     "Unsupported packet " + type));
+                                                                               "Unsupported packet " + type));
             }
-         }      
+         }
       }
       catch (Throwable t)
       {
@@ -383,14 +483,14 @@
          else
          {
             me = new MessagingException(MessagingException.INTERNAL_ERROR);
-         }   
-         
-         response = new MessagingExceptionMessage(me);                      
+         }
+
+         response = new MessagingExceptionMessage(me);
       }
 
       if (response != null)
       {
-         channel.send(response);   
+         channel.send(response);
       }
    }
 }

Modified: trunk/src/main/org/jboss/messaging/jms/client/JBossSession.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/client/JBossSession.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/src/main/org/jboss/messaging/jms/client/JBossSession.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -87,8 +87,7 @@
  * 
  * $Id$
  */
-public class JBossSession implements Session, XASession, QueueSession,
-         XAQueueSession, TopicSession, XATopicSession
+public class JBossSession implements Session, XASession, QueueSession, XAQueueSession, TopicSession, XATopicSession
 {
    // Constants -----------------------------------------------------
 
@@ -117,14 +116,17 @@
    private final boolean xa;
 
    private boolean recoverCalled;
-   
+
    private final Set<JBossMessageConsumer> consumers = new HashSet<JBossMessageConsumer>();
 
    // Constructors --------------------------------------------------
 
    public JBossSession(final JBossConnection connection,
-            final boolean transacted, final boolean xa, final int ackMode,
-            final ClientSession session, final int sessionType)
+                       final boolean transacted,
+                       final boolean xa,
+                       final int ackMode,
+                       final ClientSession session,
+                       final int sessionType)
    {
       this.connection = connection;
 
@@ -169,8 +171,7 @@
       return new JBossObjectMessage(session);
    }
 
-   public ObjectMessage createObjectMessage(final Serializable object)
-            throws JMSException
+   public ObjectMessage createObjectMessage(final Serializable object) throws JMSException
    {
       checkClosed();
 
@@ -222,10 +223,14 @@
 
    public void commit() throws JMSException
    {
-      if (!transacted) { throw new IllegalStateException(
-               "Cannot commit a non-transacted session"); }
-      if (xa) { throw new TransactionInProgressException(
-               "Cannot call commit on an XA session"); }
+      if (!transacted)
+      {
+         throw new IllegalStateException("Cannot commit a non-transacted session");
+      }
+      if (xa)
+      {
+         throw new TransactionInProgressException("Cannot call commit on an XA session");
+      }
       try
       {
          session.commit();
@@ -238,10 +243,14 @@
 
    public void rollback() throws JMSException
    {
-      if (!transacted) { throw new IllegalStateException(
-               "Cannot rollback a non-transacted session"); }
-      if (xa) { throw new TransactionInProgressException(
-               "Cannot call rollback on an XA session"); }
+      if (!transacted)
+      {
+         throw new IllegalStateException("Cannot rollback a non-transacted session");
+      }
+      if (xa)
+      {
+         throw new TransactionInProgressException("Cannot call rollback on an XA session");
+      }
 
       try
       {
@@ -257,11 +266,11 @@
    {
       try
       {
-         for (JBossMessageConsumer cons: new HashSet<JBossMessageConsumer>(consumers))
-         {            
+         for (JBossMessageConsumer cons : new HashSet<JBossMessageConsumer>(consumers))
+         {
             cons.close();
          }
- 
+
          session.close();
 
          connection.removeSession(this);
@@ -274,8 +283,10 @@
 
    public void recover() throws JMSException
    {
-      if (transacted) { throw new IllegalStateException(
-               "Cannot recover a transacted session"); }
+      if (transacted)
+      {
+         throw new IllegalStateException("Cannot recover a transacted session");
+      }
 
       try
       {
@@ -296,8 +307,7 @@
       return null;
    }
 
-   public void setMessageListener(final MessageListener listener)
-            throws JMSException
+   public void setMessageListener(final MessageListener listener) throws JMSException
    {
       checkClosed();
    }
@@ -306,18 +316,18 @@
    {
    }
 
-   public MessageProducer createProducer(final Destination destination)
-            throws JMSException
+   public MessageProducer createProducer(final Destination destination) throws JMSException
    {
-      if (destination != null && !(destination instanceof JBossDestination)) { throw new InvalidDestinationException(
-               "Not a JBoss Destination:" + destination); }
+      if (destination != null && !(destination instanceof JBossDestination))
+      {
+         throw new InvalidDestinationException("Not a JBoss Destination:" + destination);
+      }
 
       JBossDestination jbd = (JBossDestination) destination;
 
       try
       {
-         ClientProducer producer = session.createProducer(jbd == null ? null
-                  : jbd.getSimpleAddress());
+         ClientProducer producer = session.createProducer(jbd == null ? null : jbd.getSimpleAddress());
 
          return new JBossMessageProducer(connection, producer, jbd, session);
       }
@@ -327,32 +337,33 @@
       }
    }
 
-   public MessageConsumer createConsumer(final Destination destination)
-            throws JMSException
+   public MessageConsumer createConsumer(final Destination destination) throws JMSException
    {
       return createConsumer(destination, null, false);
    }
 
-   public MessageConsumer createConsumer(final Destination destination,
-            final String messageSelector) throws JMSException
+   public MessageConsumer createConsumer(final Destination destination, final String messageSelector) throws JMSException
    {
       return createConsumer(destination, messageSelector, false);
    }
 
    public MessageConsumer createConsumer(final Destination destination,
-            final String messageSelector, final boolean noLocal)
-            throws JMSException
+                                         final String messageSelector,
+                                         final boolean noLocal) throws JMSException
    {
-      if (destination == null) { throw new InvalidDestinationException(
-               "Cannot create a consumer with a null destination"); }
+      if (destination == null)
+      {
+         throw new InvalidDestinationException("Cannot create a consumer with a null destination");
+      }
 
-      if (!(destination instanceof JBossDestination)) { throw new InvalidDestinationException(
-               "Not a JBossDestination:" + destination); }
+      if (!(destination instanceof JBossDestination))
+      {
+         throw new InvalidDestinationException("Not a JBossDestination:" + destination);
+      }
 
       JBossDestination jbdest = (JBossDestination) destination;
 
-      JBossMessageConsumer consumer = createConsumer(jbdest, null,
-               messageSelector, noLocal);
+      JBossMessageConsumer consumer = createConsumer(jbdest, null, messageSelector, noLocal);
 
       return consumer;
    }
@@ -360,15 +371,16 @@
    public Queue createQueue(final String queueName) throws JMSException
    {
       // As per spec. section 4.11
-      if (sessionType == TYPE_TOPIC_SESSION) { throw new IllegalStateException(
-               "Cannot create a queue using a TopicSession"); }
+      if (sessionType == TYPE_TOPIC_SESSION)
+      {
+         throw new IllegalStateException("Cannot create a queue using a TopicSession");
+      }
 
       JBossQueue queue = new JBossQueue(queueName);
 
       try
       {
-         SessionQueueQueryResponseMessage response = session.queueQuery(queue
-                  .getSimpleAddress());
+         SessionQueueQueryResponseMessage response = session.queueQuery(queue.getSimpleAddress());
 
          if (!response.isExists())
          {
@@ -388,15 +400,16 @@
    public Topic createTopic(final String topicName) throws JMSException
    {
       // As per spec. section 4.11
-      if (sessionType == TYPE_QUEUE_SESSION) { throw new IllegalStateException(
-               "Cannot create a topic on a QueueSession"); }
+      if (sessionType == TYPE_QUEUE_SESSION)
+      {
+         throw new IllegalStateException("Cannot create a topic on a QueueSession");
+      }
 
       JBossTopic topic = new JBossTopic(topicName);
 
       try
       {
-         SessionBindingQueryResponseMessage response = session
-                  .bindingQuery(topic.getSimpleAddress());
+         SessionBindingQueryResponseMessage response = session.bindingQuery(topic.getSimpleAddress());
 
          if (!response.isExists())
          {
@@ -413,23 +426,29 @@
       }
    }
 
-   public TopicSubscriber createDurableSubscriber(final Topic topic,
-            final String name) throws JMSException
+   public TopicSubscriber createDurableSubscriber(final Topic topic, final String name) throws JMSException
    {
       return createDurableSubscriber(topic, name, null, false);
    }
 
    public TopicSubscriber createDurableSubscriber(final Topic topic,
-            final String name, String messageSelector, final boolean noLocal)
-            throws JMSException
+                                                  final String name,
+                                                  String messageSelector,
+                                                  final boolean noLocal) throws JMSException
    {
       // As per spec. section 4.11
-      if (sessionType == TYPE_QUEUE_SESSION) { throw new IllegalStateException(
-               "Cannot create a durable subscriber on a QueueSession"); }
-      if (topic == null) { throw new InvalidDestinationException(
-               "Cannot create a durable subscriber on a null topic"); }
-      if (!(topic instanceof JBossTopic)) { throw new InvalidDestinationException(
-               "Not a JBossTopic:" + topic); }
+      if (sessionType == TYPE_QUEUE_SESSION)
+      {
+         throw new IllegalStateException("Cannot create a durable subscriber on a QueueSession");
+      }
+      if (topic == null)
+      {
+         throw new InvalidDestinationException("Cannot create a durable subscriber on a null topic");
+      }
+      if (!(topic instanceof JBossTopic))
+      {
+         throw new InvalidDestinationException("Not a JBossTopic:" + topic);
+      }
       if ("".equals(messageSelector))
       {
          messageSelector = null;
@@ -441,8 +460,9 @@
    }
 
    private JBossMessageConsumer createConsumer(final JBossDestination dest,
-            final String subscriptionName, String selectorString,
-            final boolean noLocal) throws JMSException
+                                               final String subscriptionName,
+                                               String selectorString,
+                                               final boolean noLocal) throws JMSException
    {
       try
       {
@@ -452,9 +472,7 @@
          {
             connection.setHasNoLocal();
 
-            String filter = JBossConnection.CONNECTION_ID_PROPERTY_NAME
-                     .toString()
-                     + "<>'" + connection.getUID() + "'";
+            String filter = JBossConnection.CONNECTION_ID_PROPERTY_NAME.toString() + "<>'" + connection.getUID() + "'";
 
             if (selectorString != null)
             {
@@ -470,8 +488,7 @@
 
          if (selectorString != null)
          {
-            coreFilterString = new SimpleString(SelectorTranslator
-                     .convertToJBMFilterString(selectorString));
+            coreFilterString = new SimpleString(SelectorTranslator.convertToJBMFilterString(selectorString));
          }
 
          ClientConsumer consumer;
@@ -480,22 +497,23 @@
 
          if (dest instanceof Queue)
          {
-            SessionQueueQueryResponseMessage response = session.queueQuery(dest
-                     .getSimpleAddress());
+            SessionQueueQueryResponseMessage response = session.queueQuery(dest.getSimpleAddress());
 
-            if (!response.isExists()) { throw new InvalidDestinationException(
-                     "Queue " + dest.getName() + " does not exist"); }
+            if (!response.isExists())
+            {
+               throw new InvalidDestinationException("Queue " + dest.getName() + " does not exist");
+            }
 
-            consumer = session.createConsumer(dest.getSimpleAddress(),
-                     coreFilterString, false);
+            consumer = session.createConsumer(dest.getSimpleAddress(), coreFilterString, false);
          }
          else
          {
-            SessionBindingQueryResponseMessage response = session
-                     .bindingQuery(dest.getSimpleAddress());
+            SessionBindingQueryResponseMessage response = session.bindingQuery(dest.getSimpleAddress());
 
-            if (!response.isExists()) { throw new InvalidDestinationException(
-                     "Topic " + dest.getName() + " does not exist"); }
+            if (!response.isExists())
+            {
+               throw new InvalidDestinationException("Topic " + dest.getName() + " does not exist");
+            }
 
             SimpleString queueName;
 
@@ -505,8 +523,7 @@
 
                queueName = new SimpleString(UUID.randomUUID().toString());
 
-               session.createQueue(dest.getSimpleAddress(), queueName,
-                        coreFilterString, false, true);
+               session.createQueue(dest.getSimpleAddress(), queueName, coreFilterString, false, true);
 
                consumer = session.createConsumer(queueName, null, false);
 
@@ -516,29 +533,32 @@
             {
                // Durable sub
 
-               if (connection.getClientID() == null) { throw new InvalidClientIDException(
-                        "Cannot create durable subscription - client ID has not been set"); }
+               if (connection.getClientID() == null)
+               {
+                  throw new InvalidClientIDException("Cannot create durable subscription - client ID has not been set");
+               }
 
-               if (dest.isTemporary()) { throw new InvalidDestinationException(
-                        "Cannot create a durable subscription on a temporary topic"); }
+               if (dest.isTemporary())
+               {
+                  throw new InvalidDestinationException("Cannot create a durable subscription on a temporary topic");
+               }
 
-               queueName = new SimpleString(JBossTopic
-                        .createQueueNameForDurableSubscription(connection
-                                 .getClientID(), subscriptionName));
+               queueName = new SimpleString(JBossTopic.createQueueNameForDurableSubscription(connection.getClientID(),
+                                                                                             subscriptionName));
 
-               SessionQueueQueryResponseMessage subResponse = session
-                        .queueQuery(queueName);
+               SessionQueueQueryResponseMessage subResponse = session.queueQuery(queueName);
 
                if (!subResponse.isExists())
                {
-                  session.createQueue(dest.getSimpleAddress(), queueName,
-                           coreFilterString, true, false);
+                  session.createQueue(dest.getSimpleAddress(), queueName, coreFilterString, true, false);
                }
                else
                {
                   // Already exists
-                  if (subResponse.getConsumerCount() > 0) { throw new IllegalStateException(
-                           "Cannot create a subscriber on the durable subscription since it already has subscriber(s)"); }
+                  if (subResponse.getConsumerCount() > 0)
+                  {
+                     throw new IllegalStateException("Cannot create a subscriber on the durable subscription since it already has subscriber(s)");
+                  }
 
                   // From javax.jms.Session Javadoc (and also JMS 1.1 6.11.1):
                   // A client can change an existing durable subscription by
@@ -551,16 +571,12 @@
 
                   SimpleString oldFilterString = subResponse.getFilterString();
 
-                  boolean selectorChanged = (coreFilterString == null && oldFilterString != null)
-                           || (oldFilterString == null && coreFilterString != null)
-                           || (oldFilterString != null
-                                    && coreFilterString != null && !oldFilterString
-                                    .equals(coreFilterString));
+                  boolean selectorChanged = (coreFilterString == null && oldFilterString != null) || (oldFilterString == null && coreFilterString != null) ||
+                                            (oldFilterString != null && coreFilterString != null && !oldFilterString.equals(coreFilterString));
 
                   SimpleString oldTopicName = subResponse.getAddress();
 
-                  boolean topicChanged = !oldTopicName.equals(dest
-                           .getSimpleAddress());
+                  boolean topicChanged = !oldTopicName.equals(dest.getSimpleAddress());
 
                   if (selectorChanged || topicChanged)
                   {
@@ -568,8 +584,7 @@
                      session.deleteQueue(queueName);
 
                      // Create the new one
-                     session.createQueue(dest.getSimpleAddress(), queueName,
-                              coreFilterString, true, false);
+                     session.createQueue(dest.getSimpleAddress(), queueName, coreFilterString, true, false);
                   }
                }
 
@@ -577,11 +592,15 @@
             }
          }
 
-         JBossMessageConsumer jbc = new JBossMessageConsumer(this, consumer, noLocal, dest,
-                  selectorString, autoDeleteQueueName);
-         
+         JBossMessageConsumer jbc = new JBossMessageConsumer(this,
+                                                             consumer,
+                                                             noLocal,
+                                                             dest,
+                                                             selectorString,
+                                                             autoDeleteQueueName);
+
          consumers.add(jbc);
-         
+
          return jbc;
       }
       catch (MessagingException e)
@@ -595,16 +614,21 @@
       return createBrowser(queue, null);
    }
 
-   public QueueBrowser createBrowser(final Queue queue, String filterString)
-            throws JMSException
+   public QueueBrowser createBrowser(final Queue queue, String filterString) throws JMSException
    {
       // As per spec. section 4.11
-      if (sessionType == TYPE_TOPIC_SESSION) { throw new IllegalStateException(
-               "Cannot create a browser on a TopicSession"); }
-      if (queue == null) { throw new InvalidDestinationException(
-               "Cannot create a browser with a null queue"); }
-      if (!(queue instanceof JBossQueue)) { throw new InvalidDestinationException(
-               "Not a JBossQueue:" + queue); }
+      if (sessionType == TYPE_TOPIC_SESSION)
+      {
+         throw new IllegalStateException("Cannot create a browser on a TopicSession");
+      }
+      if (queue == null)
+      {
+         throw new InvalidDestinationException("Cannot create a browser with a null queue");
+      }
+      if (!(queue instanceof JBossQueue))
+      {
+         throw new InvalidDestinationException("Not a JBossQueue:" + queue);
+      }
       if ("".equals(filterString))
       {
          filterString = null;
@@ -614,11 +638,10 @@
 
       try
       {
-         String coreSelector = SelectorTranslator
-                  .convertToJBMFilterString(filterString);
+         String coreSelector = SelectorTranslator.convertToJBMFilterString(filterString);
 
          ClientBrowser browser = session.createBrowser(jbq.getSimpleAddress(),
-                  coreSelector == null ? null : new SimpleString(coreSelector));
+                                                       coreSelector == null ? null : new SimpleString(coreSelector));
 
          return new JBossQueueBrowser(queue, filterString, browser);
       }
@@ -631,8 +654,10 @@
    public TemporaryQueue createTemporaryQueue() throws JMSException
    {
       // As per spec. section 4.11
-      if (sessionType == TYPE_TOPIC_SESSION) { throw new IllegalStateException(
-               "Cannot create a temporary queue using a TopicSession"); }
+      if (sessionType == TYPE_TOPIC_SESSION)
+      {
+         throw new IllegalStateException("Cannot create a temporary queue using a TopicSession");
+      }
 
       String queueName = UUID.randomUUID().toString();
 
@@ -642,8 +667,7 @@
 
          SimpleString simpleAddress = queue.getSimpleAddress();
 
-         session.createQueue(queue.getSimpleAddress(),
-                  queue.getSimpleAddress(), null, false, true);
+         session.createQueue(queue.getSimpleAddress(), queue.getSimpleAddress(), null, false, true);
 
          session.addDestination(queue.getSimpleAddress(), false, true);
 
@@ -662,8 +686,10 @@
    public TemporaryTopic createTemporaryTopic() throws JMSException
    {
       // As per spec. section 4.11
-      if (sessionType == TYPE_QUEUE_SESSION) { throw new IllegalStateException(
-               "Cannot create a temporary topic on a QueueSession"); }
+      if (sessionType == TYPE_QUEUE_SESSION)
+      {
+         throw new IllegalStateException("Cannot create a temporary topic on a QueueSession");
+      }
 
       String topicName = UUID.randomUUID().toString();
 
@@ -688,25 +714,29 @@
    public void unsubscribe(final String name) throws JMSException
    {
       // As per spec. section 4.11
-      if (sessionType == TYPE_QUEUE_SESSION) { throw new IllegalStateException(
-               "Cannot unsubscribe using a QueueSession"); }
+      if (sessionType == TYPE_QUEUE_SESSION)
+      {
+         throw new IllegalStateException("Cannot unsubscribe using a QueueSession");
+      }
 
-      SimpleString queueName = new SimpleString(JBossTopic
-               .createQueueNameForDurableSubscription(connection.getClientID(),
-                        name));
+      SimpleString queueName = new SimpleString(JBossTopic.createQueueNameForDurableSubscription(connection.getClientID(),
+                                                                                                 name));
 
       try
       {
-         SessionQueueQueryResponseMessage response = session
-                  .queueQuery(queueName);
+         SessionQueueQueryResponseMessage response = session.queueQuery(queueName);
 
-         if (!response.isExists()) { throw new InvalidDestinationException(
-                  "Cannot unsubscribe, subscription with name " + name
-                           + " does not exist"); }
+         if (!response.isExists())
+         {
+            throw new InvalidDestinationException("Cannot unsubscribe, subscription with name " + name +
+                                                  " does not exist");
+         }
 
-         if (response.getConsumerCount() != 0) { throw new IllegalStateException(
-                  "Cannot unsubscribe durable subscription " + name
-                           + " since it has active subscribers"); }
+         if (response.getConsumerCount() != 0)
+         {
+            throw new IllegalStateException("Cannot unsubscribe durable subscription " + name +
+                                            " since it has active subscribers");
+         }
 
          session.deleteQueue(queueName);
       }
@@ -720,7 +750,10 @@
 
    public Session getSession() throws JMSException
    {
-      if (!xa) { throw new IllegalStateException("Isn't an XASession"); }
+      if (!xa)
+      {
+         throw new IllegalStateException("Isn't an XASession");
+      }
 
       return this;
    }
@@ -732,8 +765,7 @@
 
    // QueueSession implementation
 
-   public QueueReceiver createReceiver(final Queue queue,
-            final String messageSelector) throws JMSException
+   public QueueReceiver createReceiver(final Queue queue, final String messageSelector) throws JMSException
    {
       return (QueueReceiver) createConsumer(queue, messageSelector);
    }
@@ -762,15 +794,12 @@
       return (TopicPublisher) createProducer(topic);
    }
 
-   public TopicSubscriber createSubscriber(final Topic topic,
-            final String messageSelector, final boolean noLocal)
-            throws JMSException
+   public TopicSubscriber createSubscriber(final Topic topic, final String messageSelector, final boolean noLocal) throws JMSException
    {
       return (TopicSubscriber) createConsumer(topic, messageSelector, noLocal);
    }
 
-   public TopicSubscriber createSubscriber(final Topic topic)
-            throws JMSException
+   public TopicSubscriber createSubscriber(final Topic topic) throws JMSException
    {
       return (TopicSubscriber) createConsumer(topic);
    }
@@ -804,21 +833,23 @@
       this.recoverCalled = recoverCalled;
    }
 
-   public void deleteTemporaryTopic(final JBossTemporaryTopic tempTopic)
-            throws JMSException
+   public void deleteTemporaryTopic(final JBossTemporaryTopic tempTopic) throws JMSException
    {
       try
       {
-         SessionBindingQueryResponseMessage response = session
-                  .bindingQuery(tempTopic.getSimpleAddress());
+         SessionBindingQueryResponseMessage response = session.bindingQuery(tempTopic.getSimpleAddress());
 
-         if (!response.isExists()) { throw new InvalidDestinationException(
-                  "Cannot delete temporary topic " + tempTopic.getName()
-                           + " does not exist"); }
+         if (!response.isExists())
+         {
+            throw new InvalidDestinationException("Cannot delete temporary topic " + tempTopic.getName() +
+                                                  " does not exist");
+         }
 
-         if (!response.getQueueNames().isEmpty()) { throw new IllegalStateException(
-                  "Cannot delete temporary topic " + tempTopic.getName()
-                           + " since it has subscribers"); }
+         if (!response.getQueueNames().isEmpty())
+         {
+            throw new IllegalStateException("Cannot delete temporary topic " + tempTopic.getName() +
+                                            " since it has subscribers");
+         }
 
          SimpleString address = tempTopic.getSimpleAddress();
 
@@ -832,21 +863,23 @@
       }
    }
 
-   public void deleteTemporaryQueue(final JBossTemporaryQueue tempQueue)
-            throws JMSException
+   public void deleteTemporaryQueue(final JBossTemporaryQueue tempQueue) throws JMSException
    {
       try
       {
-         SessionQueueQueryResponseMessage response = session
-                  .queueQuery(tempQueue.getSimpleAddress());
+         SessionQueueQueryResponseMessage response = session.queueQuery(tempQueue.getSimpleAddress());
 
-         if (!response.isExists()) { throw new InvalidDestinationException(
-                  "Cannot delete temporary queue " + tempQueue.getName()
-                           + " does not exist"); }
+         if (!response.isExists())
+         {
+            throw new InvalidDestinationException("Cannot delete temporary queue " + tempQueue.getName() +
+                                                  " does not exist");
+         }
 
-         if (response.getConsumerCount() > 0) { throw new IllegalStateException(
-                  "Cannot delete temporary queue " + tempQueue.getName()
-                           + " since it has subscribers"); }
+         if (response.getConsumerCount() > 0)
+         {
+            throw new IllegalStateException("Cannot delete temporary queue " + tempQueue.getName() +
+                                            " since it has subscribers");
+         }
 
          SimpleString address = tempQueue.getSimpleAddress();
 
@@ -874,19 +907,19 @@
          throw JMSExceptionHelper.convertFromMessagingException(e);
       }
    }
-   
+
    public void start() throws JMSException
    {
       try
       {
-         session.start();         
+         session.start();
       }
       catch (MessagingException e)
       {
          throw JMSExceptionHelper.convertFromMessagingException(e);
       }
    }
-   
+
    public void stop() throws JMSException
    {
       try
@@ -898,7 +931,7 @@
          throw JMSExceptionHelper.convertFromMessagingException(e);
       }
    }
-   
+
    public void removeConsumer(final JBossMessageConsumer consumer)
    {
       consumers.remove(consumer);
@@ -907,13 +940,15 @@
    // Package protected ---------------------------------------------
 
    // Protected -----------------------------------------------------
-   
+
    // Private -------------------------------------------------------
 
    private void checkClosed() throws JMSException
    {
-      if (session.isClosed()) { throw new IllegalStateException(
-               "Session is closed"); }
+      if (session.isClosed())
+      {
+         throw new IllegalStateException("Session is closed");
+      }
    }
 
    // Inner classes -------------------------------------------------

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/DummyInterceptor.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/DummyInterceptor.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/DummyInterceptor.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -29,7 +29,7 @@
 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.wireformat.ReceiveMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionReceiveMessage;
 import org.jboss.messaging.util.SimpleString;
 
 /**
@@ -63,9 +63,9 @@
       }
       if (changeMessage)
       {
-         if (packet instanceof ReceiveMessage)
+         if (packet instanceof SessionReceiveMessage)
          {
-            ReceiveMessage deliver = (ReceiveMessage)packet;
+            SessionReceiveMessage deliver = (SessionReceiveMessage)packet;
             log.debug("msg = " + deliver.getServerMessage().getClass().getName());
             deliver.getServerMessage().putStringProperty(new SimpleString("DummyInterceptor"), new SimpleString("was here"));
          }

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/ReplicationTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/ReplicationTest.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/ReplicationTest.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -22,7 +22,9 @@
 
 package org.jboss.messaging.tests.integration.cluster;
 
+import java.util.ArrayList;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 
 import junit.framework.TestCase;
@@ -40,6 +42,8 @@
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
 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;
 import org.jboss.messaging.core.server.impl.MessagingServiceImpl;
@@ -54,6 +58,14 @@
   
    // Attributes ----------------------------------------------------
    
+   private static final SimpleString ADDRESS = new SimpleString("FailoverTestAddress");
+   
+   private MessagingService liveService;
+   
+   private MessagingService backupService;
+   
+   private Map<String, Object> backupParams = new HashMap<String, Object>();
+      
    // Static --------------------------------------------------------
 
    // Constructors --------------------------------------------------
@@ -61,98 +73,144 @@
    // Public --------------------------------------------------------
 
    public void testReplication() throws Exception
-   {             
-      final SimpleString QUEUE = new SimpleString("CoreClientTestQueue");
-      
-      Configuration backupConf = new ConfigurationImpl();      
-      backupConf.setSecurityEnabled(false);        
-      backupConf.setPacketConfirmationBatchSize(1);
-      Map<String, Object> backupParams = new HashMap<String, Object>();
-      backupParams.put(TransportConstants.SERVER_ID_PROP_NAME, 1);
-      backupConf.getAcceptorConfigurations().add(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMAcceptorFactory", backupParams));
-      backupConf.setBackup(true);                  
-      MessagingService backupService = MessagingServiceImpl.newNullStorageMessagingServer(backupConf);              
-      backupService.start();
-            
-      Configuration liveConf = new ConfigurationImpl();      
-      liveConf.setSecurityEnabled(false);    
-      liveConf.setPacketConfirmationBatchSize(1);
-      liveConf.getAcceptorConfigurations().add(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMAcceptorFactory"));
-      liveConf.setBackupConnectorConfiguration(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory", backupParams));
-      MessagingService liveService = MessagingServiceImpl.newNullStorageMessagingServer(liveConf);              
-      liveService.start();
-            
+   {                                     
       ClientSessionFactory sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"));
 
       ClientSession session = sf.createSession(false, true, true, -1, false);
         
-      session.createQueue(QUEUE, QUEUE, null, false, false);
+      session.createQueue(ADDRESS, ADDRESS, null, false, false);
+            
+      ClientProducer producer = session.createProducer(ADDRESS);     
       
-      
-      ClientProducer producer = session.createProducer(QUEUE);     
-      
       final int numMessages = 1000;
       
+      log.info("starting");
+      
       for (int i = 0; i < numMessages; i++)
       {
          ClientMessage message = session.createClientMessage(JBossTextMessage.TYPE, false, 0,
-               System.currentTimeMillis(), (byte) 1);         
-         message.getBody().putString("testINVMCoreClient");
+               System.currentTimeMillis(), (byte) 1);  
+         message.putIntProperty(new SimpleString("count"), i);
+         message.getBody().putString("aardvarks");
          message.getBody().flip();  
          producer.send(message);
       }
+      
+      log.info("Sent messages");
                                 
-      ClientConsumer consumer = session.createConsumer(QUEUE);
+      ClientConsumer consumer = session.createConsumer(ADDRESS);
       
       session.start();
        
       for (int i = 0; i < numMessages; i++)
       {
          ClientMessage message2 = consumer.receive();
+         
+        // log.info("Got message " + message2);
 
-         assertEquals("testINVMCoreClient", message2.getBody().getString());
+         assertEquals("aardvarks", message2.getBody().getString());
+         assertEquals(i, message2.getProperty(new SimpleString("count")));
          
          session.acknowledge();
       }
       
-      session.close();
+      log.info("done");
       
-      liveService.stop();
-      backupService.stop();
+      ClientMessage message3 = consumer.receive(500);
+      
+      assertNull(message3);
+      
+      log.info("Got all messages");
+      
+      session.close();
    }
    
       
    public void testFailoverSameConnectionFactory() throws Exception
-   {             
-      final SimpleString QUEUE = new SimpleString("CoreClientTestQueue");
+   {                              
+      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));
+
+      ClientSession session = sf.createSession(false, true, true, -1, false);
+                  
+      session.createQueue(ADDRESS, ADDRESS, null, false, false);
+       
+      ClientProducer producer = session.createProducer(ADDRESS);     
       
-      Configuration backupConf = new ConfigurationImpl();      
-      backupConf.setSecurityEnabled(false);        
-      backupConf.setPacketConfirmationBatchSize(1);
-      Map<String, Object> backupParams = new HashMap<String, Object>();
-      backupParams.put(TransportConstants.SERVER_ID_PROP_NAME, 1);
-      backupConf.getAcceptorConfigurations().add(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMAcceptorFactory", backupParams));
-      backupConf.setBackup(true);                  
-      MessagingService backupService = MessagingServiceImpl.newNullStorageMessagingServer(backupConf);              
-      backupService.start();
-            
-      Configuration liveConf = new ConfigurationImpl();      
-      liveConf.setSecurityEnabled(false);    
-      liveConf.setPacketConfirmationBatchSize(1);
-      liveConf.getAcceptorConfigurations().add(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMAcceptorFactory"));
-      liveConf.setBackupConnectorConfiguration(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory", backupParams));
-      MessagingService liveService = MessagingServiceImpl.newNullStorageMessagingServer(liveConf);              
-      liveService.start();
-            
+      final int numMessages = 1000;
+      
+      for (int i = 0; i < numMessages; i++)
+      {
+         ClientMessage message = session.createClientMessage(JBossTextMessage.TYPE, false, 0,
+               System.currentTimeMillis(), (byte) 1);         
+         message.putIntProperty(new SimpleString("count"), i);
+         message.getBody().putString("aardvarks");
+         message.getBody().flip();  
+         producer.send(message);
+      }
+      
+      RemotingConnection conn = ((ClientSessionImpl)session).getConnection();
+      
+      //Simulate failure on connection
+      conn.fail(new MessagingException(MessagingException.NOT_CONNECTED));
+                      
+      ClientConsumer consumer = session.createConsumer(ADDRESS);
+      
+      session.start();
+      
+      for (int i = 0; i < numMessages / 2; i++)
+      {
+         ClientMessage message2 = consumer.receive();
+
+         assertEquals("aardvarks", message2.getBody().getString());
+         
+         assertEquals(i, message2.getProperty(new SimpleString("count")));
+         
+         session.acknowledge();
+         
+         //log.info("got message " + message2.getProperty(new SimpleString("blah")));
+      }
+
+      session.close();
+                  
+      session = sf.createSession(false, true, true, -1, false);
+      
+      consumer = session.createConsumer(ADDRESS);
+      
+      session.start();
+      
+      for (int i = numMessages / 2 ; i < numMessages; i++)
+      {
+         ClientMessage message2 = consumer.receive();
+
+         assertEquals("aardvarks", message2.getBody().getString());
+         
+         assertEquals(i, message2.getProperty(new SimpleString("count")));
+         
+         session.acknowledge();
+         
+        //log.info("got message " + message2.getProperty(new SimpleString("blah")));
+      }
+      
+      ClientMessage message3 = consumer.receive(500);
+      
+      session.close();
+      
+      assertNull(message3);
+   }
+   
+   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));
 
       ClientSession session = sf.createSession(false, true, true, -1, false);
                   
-      session.createQueue(QUEUE, QUEUE, null, false, false);
+      session.createQueue(ADDRESS, ADDRESS, null, false, false);
        
-      ClientProducer producer = session.createProducer(QUEUE);     
+      ClientProducer producer = session.createProducer(ADDRESS);     
       
       final int numMessages = 1000;
       
@@ -160,8 +218,8 @@
       {
          ClientMessage message = session.createClientMessage(JBossTextMessage.TYPE, false, 0,
                System.currentTimeMillis(), (byte) 1);         
-         message.putIntProperty(new SimpleString("blah"), i);
-         message.getBody().putString("testINVMCoreClient");
+         message.putIntProperty(new SimpleString("count"), i);
+         message.getBody().putString("aardvarks");
          message.getBody().flip();  
          producer.send(message);
      //    log.info("sent " + i);
@@ -172,16 +230,18 @@
       //Simulate failure on connection
       conn.fail(new MessagingException(MessagingException.NOT_CONNECTED));
                       
-      ClientConsumer consumer = session.createConsumer(QUEUE);
+      ClientConsumer consumer = session.createConsumer(ADDRESS);
       
       session.start();
-      
+            
       for (int i = 0; i < numMessages / 2; i++)
       {
          ClientMessage message2 = consumer.receive();
 
-         assertEquals("testINVMCoreClient", message2.getBody().getString());
+         assertEquals("aardvarks", message2.getBody().getString());
          
+         assertEquals(i, message2.getProperty(new SimpleString("count")));
+         
          session.acknowledge();
          
          //log.info("got message " + message2.getProperty(new SimpleString("blah")));
@@ -189,240 +249,158 @@
 
       session.close();
                   
+      sf =
+         new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory", backupParams));                  
+      
       log.info("** creating new one");
       
-//      sf =
-//         new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory", backupParams));
-            
       session = sf.createSession(false, true, true, -1, false);
       
-      consumer = session.createConsumer(QUEUE);
+      consumer = session.createConsumer(ADDRESS);
       
       session.start();
       
-      for (int i = 0; i < numMessages / 2; i++)
+      for (int i = numMessages / 2 ; i < numMessages; i++)      
       {
          ClientMessage message2 = consumer.receive();
 
-         assertEquals("testINVMCoreClient", message2.getBody().getString());
+         assertEquals("aardvarks", message2.getBody().getString());
          
+         assertEquals(i, message2.getProperty(new SimpleString("count")));
+         
          session.acknowledge();
          
         //log.info("got message " + message2.getProperty(new SimpleString("blah")));
       }
       
-      ClientMessage message3 = consumer.receive(1000);
+      ClientMessage message3 = consumer.receive(500);
       
       assertNull(message3);
       
-      liveService.stop();
-      backupService.stop();
-         
+      session.close();      
    }
    
-//   public void testFailoverChangeConnectionFactory() throws Exception
-//   {             
-//      final SimpleString QUEUE = new SimpleString("CoreClientTestQueue");
-//      
-//      Configuration backupConf = new ConfigurationImpl();      
-//      backupConf.setSecurityEnabled(false);        
-//      backupConf.setPacketConfirmationBatchSize(1);
-//      Map<String, Object> backupParams = new HashMap<String, Object>();
-//      backupParams.put(TransportConstants.SERVER_ID_PROP_NAME, 1);
-//      backupConf.getAcceptorConfigurations().add(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMAcceptorFactory", backupParams));
-//      backupConf.setBackup(true);                  
-//      MessagingService backupService = MessagingServiceImpl.newNullStorageMessagingServer(backupConf);              
-//      backupService.start();
-//            
-//      Configuration liveConf = new ConfigurationImpl();      
-//      liveConf.setSecurityEnabled(false);    
-//      liveConf.setPacketConfirmationBatchSize(1);
-//      liveConf.getAcceptorConfigurations().add(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMAcceptorFactory"));
-//      liveConf.setBackupConnectorConfiguration(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory", backupParams));
-//      MessagingService liveService = MessagingServiceImpl.newNullStorageMessagingServer(liveConf);              
-//      liveService.start();
-//            
-//      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));
-//
-//      ClientSession session = sf.createSession(false, true, true, -1, false);
-//                  
-//      session.createQueue(QUEUE, QUEUE, null, false, false);
-//       
-//      ClientProducer producer = session.createProducer(QUEUE);     
-//      
-//      final int numMessages = 10;
-//      
-//      for (int i = 0; i < numMessages; i++)
-//      {
-//         ClientMessage message = session.createClientMessage(JBossTextMessage.TYPE, false, 0,
-//               System.currentTimeMillis(), (byte) 1);         
-//         message.putIntProperty(new SimpleString("blah"), i);
-//         message.getBody().putString("testINVMCoreClient");
-//         message.getBody().flip();  
-//         producer.send(message);
-//      }
-//      
-//      RemotingConnection conn = ((ClientSessionImpl)session).getConnection();
-//      
-//      //Simulate failure on connection
-//      conn.fail(new MessagingException(MessagingException.NOT_CONNECTED));
-//                      
-//      ClientConsumer consumer = session.createConsumer(QUEUE);
-//      
-//      session.start();
-//      
-//      for (int i = 0; i < numMessages / 2; i++)
-//      {
-//         ClientMessage message2 = consumer.receive();
-//
-//         assertEquals("testINVMCoreClient", message2.getBody().getString());
-//         
-//         session.acknowledge();
-//         
-//         log.info("got message " + message2.getProperty(new SimpleString("blah")));
-//      }
-//
-//      session.close();
-//                  
-//      log.info("** creating new one");
-//      
-//      sf =
-//         new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory", backupParams));
-//            
-//      session = sf.createSession(false, true, true, -1, false);
-//      
-//      consumer = session.createConsumer(QUEUE);
-//      
-//      session.start();
-//      
-//      for (int i = 0; i < numMessages / 2; i++)
-//      {
-//         ClientMessage message2 = consumer.receive();
-//
-//         assertEquals("testINVMCoreClient", message2.getBody().getString());
-//         
-//         session.acknowledge();
-//         
-//         log.info("got message " + message2.getProperty(new SimpleString("blah")));
-//      }
-//      
-//      ClientMessage message3 = consumer.receive(1000);
-//      
-//      assertNull(message3);
-//      
-//      liveService.stop();
-//      backupService.stop();
-//      
-//  //    todo - do we need to failover connection factories too?????
-//               
-//               
-//   }
-//   
-//   public void testFailoverNetty() throws Exception
-//   {             
-//      final SimpleString QUEUE = new SimpleString("CoreClientTestQueue");
-//      
-//      Configuration backupConf = new ConfigurationImpl();      
-//      backupConf.setSecurityEnabled(false);        
-//      backupConf.setPacketConfirmationBatchSize(1);
-//      Map<String, Object> backupParams = new HashMap<String, Object>();
-//      backupParams.put(org.jboss.messaging.core.remoting.impl.netty.TransportConstants.PORT_PROP_NAME, 7654);
-//      backupConf.getAcceptorConfigurations().add(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.netty.NettyAcceptorFactory", backupParams));
-//      backupConf.setBackup(true);                  
-//      MessagingService backupService = MessagingServiceImpl.newNullStorageMessagingServer(backupConf);              
-//      backupService.start();
-//            
-//      Configuration liveConf = new ConfigurationImpl();      
-//      liveConf.setSecurityEnabled(false);    
-//      liveConf.setPacketConfirmationBatchSize(1);
-//      liveConf.getAcceptorConfigurations().add(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.netty.NettyAcceptorFactory"));
-//      liveConf.setBackupConnectorConfiguration(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory", backupParams));
-//      MessagingService liveService = MessagingServiceImpl.newNullStorageMessagingServer(liveConf);              
-//      liveService.start();
-//            
-//      ClientSessionFactory sf =
-//         new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory"),
-//                  new TransportConfiguration("org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory", backupParams));
-//
-//      ClientSession session = sf.createSession(false, true, true, -1, false);
-//                  
-//      session.createQueue(QUEUE, QUEUE, null, false, false);
-//       
-//      ClientProducer producer = session.createProducer(QUEUE);     
-//      
-//      final int numMessages = 10;
-//      
-//      for (int i = 0; i < numMessages; i++)
-//      {
-//         ClientMessage message = session.createClientMessage(JBossTextMessage.TYPE, false, 0,
-//               System.currentTimeMillis(), (byte) 1);         
-//         message.putIntProperty(new SimpleString("blah"), i);
-//         message.getBody().putString("testINVMCoreClient");
-//         message.getBody().flip();  
-//         producer.send(message);
-//      }
-//      
-//      RemotingConnection conn = ((ClientSessionImpl)session).getConnection();
-//      
-//      //Simulate failure on connection
-//      conn.fail(new MessagingException(MessagingException.NOT_CONNECTED));
-//                      
-//      ClientConsumer consumer = session.createConsumer(QUEUE);
-//      
-//      session.start();
-//      
-//      for (int i = 0; i < numMessages / 2; i++)
-//      {
-//         ClientMessage message2 = consumer.receive();
-//
-//         assertEquals("testINVMCoreClient", message2.getBody().getString());
-//         
-//         session.acknowledge();
-//         
-//         log.info("got message " + message2.getProperty(new SimpleString("blah")));
-//      }
-//
-//      session.close();
-//                  
-//      log.info("** creating new one");
-//      
-//      sf =
-//         new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory", backupParams));
-//            
-//      session = sf.createSession(false, true, true, -1, false);
-//      
-//      consumer = session.createConsumer(QUEUE);
-//      
-//      session.start();
-//      
-//      for (int i = 0; i < numMessages / 2; i++)
-//      {
-//         ClientMessage message2 = consumer.receive();
-//
-//         assertEquals("testINVMCoreClient", message2.getBody().getString());
-//         
-//         session.acknowledge();
-//         
-//         log.info("got message " + message2.getProperty(new SimpleString("blah")));
-//      }
-//      
-//      ClientMessage message3 = consumer.receive(1000);
-//      
-//      assertNull(message3);
-//      
-//      liveService.stop();
-//      backupService.stop();
-//      
-//  //    todo - do we need to failover connection factories too?????
-//               
-//               
-//   }
+   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));
 
+      final int numSessions = 10;
+      
+      List<ClientSession> sessions = new ArrayList<ClientSession>();
+      
+      List<ClientConsumer> consumers = new ArrayList<ClientConsumer>();
+      
+      for (int i = 0; i < numSessions; i++)
+      {
+         ClientSession sess = sf.createSession(false, true, true, -1, false);
+         
+         SimpleString queueName = new SimpleString("subscription" + i);
+         
+         sess.createQueue(ADDRESS, queueName, null, false, false);
+         
+         ClientConsumer consumer = sess.createConsumer(queueName);
+                          
+         sess.start();
+         
+         sessions.add(sess);
+         
+         consumers.add(consumer);
+      }
+      
+      log.info("Created consumers");
+            
+      ClientSession session = sf.createSession(false, true, true, -1, false);
+                  
+      ClientProducer producer = session.createProducer(ADDRESS);     
+      
+      final int numMessages = 100;
+      
+      for (int i = 0; i < numMessages; i++)
+      {
+         ClientMessage message = session.createClientMessage(JBossTextMessage.TYPE, false, 0,
+               System.currentTimeMillis(), (byte) 1);         
+         message.putIntProperty(new SimpleString("count"), i);
+         message.getBody().putString("aardvarks");
+         message.getBody().flip();  
+         producer.send(message);
+     //    log.info("sent " + i);
+      }
+                  
+      RemotingConnection conn = ((ClientSessionImpl)session).getConnection();
+      
+      //Simulate failure on connection
+      conn.fail(new MessagingException(MessagingException.NOT_CONNECTED));
+      
+      for (int i = 0; i < numSessions; i++)
+      {      
+         ClientConsumer cons = consumers.get(i);
+         
+         ClientSession sess = sessions.get(i);
+         
+         for (int j = 0; j < numMessages; j++)
+         {
+            ClientMessage message2 = cons.receive();
+   
+            assertEquals("aardvarks", message2.getBody().getString());
+            
+            //log.info("got message " + i + ":" + message2.getProperty(new SimpleString("count")));
+            
+            assertEquals(j, message2.getProperty(new SimpleString("count")));
+            
+            sess.acknowledge();
+         }
+      }
+      
+      session.close();
+      
+      for (int i = 0; i < numSessions; i++)
+      {      
+         ClientSession sess = sessions.get(i);
+         
+         sess.close();
+      }
+   }
+   
    // Package protected ---------------------------------------------
 
    // Protected -----------------------------------------------------
+   
+   protected void setUp() throws Exception
+   {
+      Configuration backupConf = new ConfigurationImpl();      
+      backupConf.setSecurityEnabled(false);        
+      backupConf.setPacketConfirmationBatchSize(1);
+      backupParams.put(TransportConstants.SERVER_ID_PROP_NAME, 1);
+      backupConf.getAcceptorConfigurations().add(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMAcceptorFactory", backupParams));
+      backupConf.setBackup(true);                  
+      backupService = MessagingServiceImpl.newNullStorageMessagingServer(backupConf);              
+      backupService.start();
+            
+      Configuration liveConf = new ConfigurationImpl();      
+      liveConf.setSecurityEnabled(false);    
+      liveConf.setPacketConfirmationBatchSize(1);
+      liveConf.getAcceptorConfigurations().add(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMAcceptorFactory"));
+      liveConf.setBackupConnectorConfiguration(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory", backupParams));
+      liveService = MessagingServiceImpl.newNullStorageMessagingServer(liveConf);              
+      liveService.start();
+   }
+   
+   protected void tearDown() throws Exception
+   {                
+      assertEquals(0, ConnectionRegistryImpl.instance.size());
+      
+      assertEquals(0, backupService.getServer().getRemotingService().getConnections().size());
+      
+      backupService.stop();
+      
+      assertEquals(0, liveService.getServer().getRemotingService().getConnections().size());
+      
+      liveService.stop();
+      
+      assertEquals(0, InVMRegistry.instance.size());
+   }
 
    // Private -------------------------------------------------------
 

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/client/impl/ClientBrowserImplTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/client/impl/ClientBrowserImplTest.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/client/impl/ClientBrowserImplTest.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -64,7 +64,7 @@
 //            
 //      final long serverTargetID = 1209102;
 //   
-//      ReceiveMessage resp = new ReceiveMessage();
+//      SessionReceiveMessage resp = new SessionReceiveMessage();
 //      
 //      EasyMock.expect(cm.sendCommandBlocking(serverTargetID, new PacketImpl(PacketImpl.SESS_BROWSER_NEXTMESSAGE))).andReturn(resp);
 //      

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/client/impl/ClientConsumerImplTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/client/impl/ClientConsumerImplTest.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/client/impl/ClientConsumerImplTest.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -682,7 +682,7 @@
 //      
 //      final long targetID = 120912;
 //
-//      cm.sendCommandOneway(targetID, new SessionFlowCreditMessage(clientWindowSize));
+//      cm.sendCommandOneway(targetID, new SessionConsumerFlowCreditMessage(clientWindowSize));
 //      EasyMock.expectLastCall().times(2);
 //      
 //      EasyMock.replay(session, cm, executor, pd);
@@ -741,7 +741,7 @@
 //      
 //      final long targetID = 120912;
 //
-//      cm.sendCommandOneway(targetID, new SessionFlowCreditMessage(505));
+//      cm.sendCommandOneway(targetID, new SessionConsumerFlowCreditMessage(505));
 //      EasyMock.expectLastCall().times(2);
 //      
 //      EasyMock.replay(session, cm, executor, pd);

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/client/impl/ClientProducerImplTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/client/impl/ClientProducerImplTest.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/client/impl/ClientProducerImplTest.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -281,11 +281,11 @@
 // 
 //      if (sendBlocking)
 //      {
-//         EasyMock.expect(cm.sendCommandBlocking(targetID, new SendMessage(message))).andReturn(null);
+//         EasyMock.expect(cm.sendCommandBlocking(targetID, new SessionSendMessage(message))).andReturn(null);
 //      }
 //      else
 //      {
-//         cm.sendCommandOneway(targetID, new SendMessage(message));
+//         cm.sendCommandOneway(targetID, new SessionSendMessage(message));
 //      }
 //      
 //      final int messageSize = 123;

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/client/impl/ClientSessionImplTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/client/impl/ClientSessionImplTest.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/client/impl/ClientSessionImplTest.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -2344,7 +2344,7 @@
 //      pd.register(new ClientConsumerPacketHandler(null, clientTargetID, null));
 //      
 //      cm.sendCommandOneway(resp.getConsumerTargetID(), 
-//                    new SessionFlowCreditMessage(resp.getWindowSize()));
+//                    new SessionConsumerFlowCreditMessage(resp.getWindowSize()));
 //      
 //      EasyMock.replay(cf, rc, pd, cm);
 //      ClientSession session = new ClientSessionImpl("blah", sessionTargetID, false, -1, false, false, false, false,rc, cf, pd, 100, cm);
@@ -2398,7 +2398,7 @@
 //      pd.register(new ClientConsumerPacketHandler(null, clientTargetID, null));
 //      
 //      cm.sendCommandOneway(resp.getConsumerTargetID(), 
-//                    new SessionFlowCreditMessage(resp.getWindowSize()));
+//                    new SessionConsumerFlowCreditMessage(resp.getWindowSize()));
 //      
 //      EasyMock.replay(cf, rc, pd, cm);
 //      
@@ -2455,7 +2455,7 @@
 //      pd.register(new ClientConsumerPacketHandler(null, clientTargetID, null));
 //      
 //      cm.sendCommandOneway(resp.getConsumerTargetID(), 
-//                    new SessionFlowCreditMessage(resp.getWindowSize()));
+//                    new SessionConsumerFlowCreditMessage(resp.getWindowSize()));
 //      
 //      EasyMock.replay(cf, rc, pd, cm);
 //      

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/DeliveryImplTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/DeliveryImplTest.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/DeliveryImplTest.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -48,7 +48,7 @@
 //         {
 //            long targetID = (Long)EasyMock.getCurrentArguments()[0];
 //            assertEquals(consumerID, targetID);
-//            ReceiveMessage receiveMessage = (ReceiveMessage) EasyMock.getCurrentArguments()[1];            
+//            SessionReceiveMessage receiveMessage = (SessionReceiveMessage) EasyMock.getCurrentArguments()[1];            
 //            assertEquals(receiveMessage.getDeliveryCount(), deliveryCount + 1);
 //            return null;
 //         }

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerBrowserImplTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerBrowserImplTest.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerBrowserImplTest.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -278,7 +278,7 @@
 //         {
 //            long targetID = (Long)EasyMock.getCurrentArguments()[0];
 //            assertEquals(1, targetID);
-//            ReceiveMessage resp = (ReceiveMessage) EasyMock.getCurrentArguments()[1];
+//            SessionReceiveMessage resp = (SessionReceiveMessage) EasyMock.getCurrentArguments()[1];
 //            assertEquals(resp.getServerMessage(), refs.get(0).getMessage());
 //            return null;
 //         }
@@ -314,7 +314,7 @@
 //         {
 //            long targetID = (Long)EasyMock.getCurrentArguments()[0];
 //            assertEquals(1, targetID);
-//            ReceiveMessage resp = (ReceiveMessage) EasyMock.getCurrentArguments()[1];
+//            SessionReceiveMessage resp = (SessionReceiveMessage) EasyMock.getCurrentArguments()[1];
 //            assertEquals(resp.getServerMessage(), refs.get(0).getMessage());
 //            return null;
 //         }
@@ -329,7 +329,7 @@
 //         {
 //            long targetID = (Long)EasyMock.getCurrentArguments()[0];
 //            assertEquals(1, targetID);
-//            ReceiveMessage resp = (ReceiveMessage) EasyMock.getCurrentArguments()[1];
+//            SessionReceiveMessage resp = (SessionReceiveMessage) EasyMock.getCurrentArguments()[1];
 //            assertEquals(resp.getServerMessage(), refs.get(0).getMessage());
 //            return null;
 //         }

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerConsumerPacketHandlerTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerConsumerPacketHandlerTest.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerConsumerPacketHandlerTest.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -48,7 +48,7 @@
 //      ServerConsumer consumer = createStrictMock(ServerConsumer.class);
 //      CommandManager cm = createStrictMock(CommandManager.class);     
 //      ServerConsumerPacketHandler handler = new ServerConsumerPacketHandler(consumer, cm);
-//      SessionFlowCreditMessage message = new SessionFlowCreditMessage(100);
+//      SessionConsumerFlowCreditMessage message = new SessionConsumerFlowCreditMessage(100);
 //      consumer.receiveCredits(100);
 //      cm.packetProcessed(message);
 //      replay(consumer, cm);

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerProducerImplTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerProducerImplTest.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerProducerImplTest.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -87,8 +87,8 @@
 //      {
 //         public Object answer() throws Throwable
 //         {
-//            assertEquals(ProducerFlowCreditMessage.class, getCurrentArguments()[1].getClass());
-//            ProducerFlowCreditMessage m = (ProducerFlowCreditMessage) getCurrentArguments()[1];
+//            assertEquals(SessionProducerFlowCreditMessage.class, getCurrentArguments()[1].getClass());
+//            SessionProducerFlowCreditMessage m = (SessionProducerFlowCreditMessage) getCurrentArguments()[1];
 //            assertEquals(m.getTokens(), 12345);
 //            return null;
 //         }

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerProducerPacketHandlerTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerProducerPacketHandlerTest.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerProducerPacketHandlerTest.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -49,7 +49,7 @@
 //      ServerProducer producer = createStrictMock(ServerProducer.class);
 //      ServerProducerPacketHandler handler = new ServerProducerPacketHandler(producer, cm);
 //      producer.send(serverMessage);
-//      SendMessage message = new SendMessage(serverMessage);
+//      SessionSendMessage message = new SessionSendMessage(serverMessage);
 //      cm.packetProcessed(message);      
 //      replay(producer, cm, serverMessage);
 //      handler.handle(1212, message);

Modified: trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerSessionImplTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerSessionImplTest.java	2008-09-16 17:16:42 UTC (rev 4956)
+++ trunk/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerSessionImplTest.java	2008-09-16 18:36:19 UTC (rev 4957)
@@ -1673,7 +1673,7 @@
 //         expect(consumer.getClientTargetID()).andReturn(76767L);
 //         expect(ref.getMessage()).andReturn(createMock(ServerMessage.class));
 //         expect(ref.getDeliveryCount()).andReturn(0);
-//         cm.sendCommandOneway(eq(76767L), isA(ReceiveMessage.class));
+//         cm.sendCommandOneway(eq(76767L), isA(SessionReceiveMessage.class));
 //         refs.add(ref);
 //      }
 //
@@ -1824,7 +1824,7 @@
 //         expect(consumer.getClientTargetID()).andReturn(76767L);
 //         expect(ref.getMessage()).andReturn(createMock(ServerMessage.class));
 //         expect(ref.getDeliveryCount()).andReturn(0);
-//         cm.sendCommandOneway(eq(76767L), isA(ReceiveMessage.class));
+//         cm.sendCommandOneway(eq(76767L), isA(SessionReceiveMessage.class));
 //         refs.add(ref);
 //      }
 //
@@ -1981,7 +1981,7 @@
 //         expect(consumer.getClientTargetID()).andReturn(76767L);
 //         expect(ref.getMessage()).andReturn(createMock(ServerMessage.class));
 //         expect(ref.getDeliveryCount()).andReturn(0);
-//         cm.sendCommandOneway(eq(76767L), isA(ReceiveMessage.class));
+//         cm.sendCommandOneway(eq(76767L), isA(SessionReceiveMessage.class));
 //         refs.add(ref);
 //      }
 //
@@ -2127,7 +2127,7 @@
 //         expect(consumer.getClientTargetID()).andReturn(76767L);
 //         expect(ref.getMessage()).andReturn(createMock(ServerMessage.class));
 //         expect(ref.getDeliveryCount()).andReturn(0);
-//         cm.sendCommandOneway(eq(76767L), isA(ReceiveMessage.class));
+//         cm.sendCommandOneway(eq(76767L), isA(SessionReceiveMessage.class));
 //         refs.add(ref);
 //      }
 //




More information about the jboss-cvs-commits mailing list