[jboss-cvs] JBoss Messaging SVN: r5183 - in branches/Branch_Chunk_CRS2: src/main/org/jboss/messaging/core/client/impl and 44 other directories.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Mon Oct 27 12:51:47 EDT 2008


Author: clebert.suconic at jboss.com
Date: 2008-10-27 12:51:46 -0400 (Mon, 27 Oct 2008)
New Revision: 5183

Added:
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/FileClientMessage.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/FileClientMessageImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/impl/journal/JournalServerLargeMessageImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/impl/nullpm/NullStorageServerLargeMessageImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionSendChunkMessage.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/ServerLargeMessage.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/chunkmessage/
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/chunkmessage/MessageChunkTest.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/chunkmessage/mock/
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/chunkmessage/mock/MockConnector.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/chunkmessage/mock/MockConnectorFactory.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/util/ServiceTestBase.java
Modified:
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/ClientConsumer.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/ClientSession.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/ClientSessionFactory.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientConsumerImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientConsumerInternal.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientMessageImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientProducerImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientSessionInternal.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientSessionPacketHandler.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/config/Configuration.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/config/impl/ConfigurationImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/config/impl/FileConfiguration.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/exception/MessagingException.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/SequentialFile.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/SequentialFileFactory.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/AIOSequentialFile.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/AIOSequentialFileFactory.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/JournalFile.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/JournalFileImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/NIOSequentialFile.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/message/Message.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/message/impl/MessageImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/PageMessage.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/PagingManager.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/impl/PageMessageImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/impl/PagingManagerImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/impl/PagingStoreImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/StorageManager.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/impl/journal/JournalStorageManager.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/impl/nullpm/NullStorageManager.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/Packet.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/RemotingConnectionImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/invm/InVMConnector.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/CreateSessionMessage.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/PacketImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionReceiveMessage.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionScheduledSendMessage.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionSendMessage.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/MessagingServer.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/ServerMessage.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/ServerProducer.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/ServerSession.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/MessagingServerImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/MessagingServerPacketHandler.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/MessagingServiceImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerConsumerImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerMessageImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerProducerImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerSessionPacketHandler.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/settings/impl/QueueSettings.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/transaction/impl/TransactionImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/client/JBossConnectionFactory.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/JMSServerManager.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/impl/JMSServerDeployer.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/impl/JMSServerManagerImpl.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/management/JMSServerControlMBean.java
   branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/management/impl/JMSServerControl.java
   branches/Branch_Chunk_CRS2/tests/jms-tests/src/org/jboss/test/messaging/jms/CTSMiscellaneousTest.java
   branches/Branch_Chunk_CRS2/tests/jms-tests/src/org/jboss/test/messaging/jms/JMSTest.java
   branches/Branch_Chunk_CRS2/tests/jms-tests/src/org/jboss/test/messaging/jms/JMSTestCase.java
   branches/Branch_Chunk_CRS2/tests/jms-tests/src/org/jboss/test/messaging/tools/container/LocalTestServer.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/base/IntegrationTestBase.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/paging/PagingManagerIntegrationTest.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/remoting/DestroyConsumerTest.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/scheduling/ScheduledMessageTest.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/xa/BasicXaRecoveryTest.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/stress/paging/MultipleDestinationPagingTest.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/ReclaimerTest.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/fakes/FakeSequentialFileFactory.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PageImplTestBase.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PageManagerImplTest.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PagingStoreImplTest.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PagingStoreTestBase.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/persistence/impl/journal/JournalStorageManagerTest.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/server/impl/MessageReferenceImplTest.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/server/impl/QueueImplTest.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerMessageImplTest.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/settings/impl/QueueSettingsTest.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/transaction/impl/TransactionImplTest.java
   branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/util/UnitTestCase.java
Log:
update on Branch

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/ClientConsumer.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/ClientConsumer.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/ClientConsumer.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -18,10 +18,12 @@
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */ 
+ */
 
 package org.jboss.messaging.core.client;
 
+import java.io.File;
+
 import org.jboss.messaging.core.exception.MessagingException;
 
 /**
@@ -30,20 +32,23 @@
  * @author <a href="mailto:ataylor at redhat.com">Andy Taylor</a>
  */
 public interface ClientConsumer
-{      
-	ClientMessage receive() throws MessagingException;
-	
+{
+   ClientMessage receive() throws MessagingException;
+
    ClientMessage receive(long timeout) throws MessagingException;
-   
+
    ClientMessage receiveImmediate() throws MessagingException;
-   
+
    MessageHandler getMessageHandler() throws MessagingException;
 
    void setMessageHandler(MessageHandler handler) throws MessagingException;
-   
+
    void close() throws MessagingException;
-   
-   boolean isClosed();   
-   
-   boolean isDirect();   
+
+   boolean isClosed();
+
+   boolean isDirect();
+
+   boolean isFileConsumer();
+
 }

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/ClientSession.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/ClientSession.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/ClientSession.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -22,6 +22,8 @@
 
 package org.jboss.messaging.core.client;
 
+import java.io.File;
+
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.remoting.FailureListener;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionBindingQueryResponseMessage;
@@ -69,6 +71,20 @@
                                  int maxRate,
                                  boolean browseOnly) throws MessagingException;
 
+   ClientConsumer createFileConsumer(File directory, SimpleString queueName) throws MessagingException;
+
+   ClientConsumer createFileConsumer(File directory, SimpleString queueName, SimpleString filterString, boolean direct) throws MessagingException;
+
+   ClientConsumer createFileConsumer(File directory, SimpleString queueName, SimpleString filterString, boolean direct, boolean browseOnly) throws MessagingException;
+
+   ClientConsumer createFileConsumer(File directory,
+                                 SimpleString queueName,
+                                 SimpleString filterString,
+                                 boolean direct,
+                                 int windowSize,
+                                 int maxRate,
+                                 boolean browseOnly) throws MessagingException;
+
    ClientProducer createProducer(SimpleString address) throws MessagingException;
 
    ClientProducer createProducer(SimpleString address,
@@ -110,6 +126,8 @@
    ClientMessage createClientMessage(final byte type, final boolean durable);
 
    ClientMessage createClientMessage(final boolean durable);
+   
+   FileClientMessage createFileMessage(final boolean durable);
 
    void start() throws MessagingException;
 

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/ClientSessionFactory.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/ClientSessionFactory.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/ClientSessionFactory.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -61,6 +61,10 @@
    
    int getProducerMaxRate();
    
+   int getBigMessageSize();
+   
+   void setBigMessageSize(final int bigMessageSize);
+   
    boolean isBlockOnPersistentSend();
    
    void setBlockOnPersistentSend(final boolean blocking);

Added: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/FileClientMessage.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/FileClientMessage.java	                        (rev 0)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/FileClientMessage.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -0,0 +1,50 @@
+/*
+ * 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.client;
+
+import java.io.File;
+import java.nio.channels.FileChannel;
+
+import org.jboss.messaging.core.exception.MessagingException;
+
+/**
+ * A FileClientMessage
+ *
+ * @author <a href="mailto:clebert.suconic at jboss.org">Clebert Suconic</a>
+ * 
+ * Created Oct 14, 2008 3:21:15 PM
+ *
+ *
+ */
+public interface FileClientMessage extends ClientMessage
+{
+   File getFile();
+
+   void setFile(File file);
+   
+   FileChannel getChannel() throws MessagingException;
+   
+   void closeChannel() throws MessagingException;  
+   
+
+}

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientConsumerImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientConsumerImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientConsumerImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -12,6 +12,7 @@
 
 package org.jboss.messaging.core.client.impl;
 
+import java.io.File;
 import java.util.LinkedList;
 import java.util.Queue;
 import java.util.concurrent.Executor;
@@ -23,6 +24,7 @@
 import org.jboss.messaging.core.remoting.Channel;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionConsumerCloseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionConsumerFlowCreditMessage;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
 import org.jboss.messaging.util.Future;
 
 /**
@@ -62,7 +64,10 @@
    private final boolean direct;
 
    private final Runner runner = new Runner();
+   
+   private File largeMessagesDir;
 
+   
    private volatile Thread receiverThread;
 
    private volatile Thread onMessageThread;
@@ -81,7 +86,8 @@
                              final int clientWindowSize,
                              final boolean direct,
                              final Executor executor,
-                             final Channel channel)
+                             final Channel channel,
+                             final File directory)
    {
       this.id = id;
 
@@ -94,6 +100,8 @@
       this.clientWindowSize = clientWindowSize;
 
       this.direct = direct;
+      
+      this.largeMessagesDir = directory;
    }
 
    // ClientConsumer implementation
@@ -179,6 +187,29 @@
       }
    }
 
+   
+   public ClientMessage createFileMessage(MessagingBuffer propertiesBuffer) throws Exception
+   {
+      if (isFileConsumer())
+      {
+         if (!this.largeMessagesDir.exists())
+         {
+            largeMessagesDir.mkdirs();
+         }
+         
+         FileClientMessageImpl message = new FileClientMessageImpl();
+         message.decodeProperties(propertiesBuffer);
+         message.setFile(new File(this.largeMessagesDir, message.getMessageID() + "-" + this.session.getName() + "-" + this.getID() + ".jbm"));
+         return message;
+      }
+      else
+      {
+         ClientMessageImpl message = new ClientMessageImpl();
+         message.decodeProperties(propertiesBuffer);
+         return message;
+      }
+   }
+   
    public ClientMessage receive() throws MessagingException
    {
       return receive(0);
@@ -247,6 +278,14 @@
       return direct;
    }
 
+   /* (non-Javadoc)
+    * @see org.jboss.messaging.core.client.ClientConsumer#isLargeMessagesAsFiles()
+    */
+   public boolean isFileConsumer()
+   {
+      return largeMessagesDir != null;
+   }
+   
    // ClientConsumerInternal implementation
    // --------------------------------------------------------------
 
@@ -488,4 +527,5 @@
          callOnMessage();
       }
    }
+
 }

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientConsumerInternal.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientConsumerInternal.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientConsumerInternal.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -24,6 +24,7 @@
 
 import org.jboss.messaging.core.client.ClientConsumer;
 import org.jboss.messaging.core.client.ClientMessage;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
 
 /**
  * 
@@ -47,4 +48,6 @@
    int getCreditsToSend();
 
    void cleanUp() throws Exception;
+   
+   ClientMessage createFileMessage(MessagingBuffer propertiesBuffer) throws Exception;
 }

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientMessageImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientMessageImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientMessageImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -72,7 +72,6 @@
       super((byte) 0, durable, 0, System.currentTimeMillis(), (byte)4, body);
    }
    
-   /* Only used in testing */
    public ClientMessageImpl()
    {      
    }

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientProducerImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientProducerImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientProducerImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -1,32 +1,47 @@
 /*
- * 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.client.impl;
 
+import java.nio.ByteBuffer;
+import java.util.concurrent.Semaphore;
+
 import org.jboss.messaging.core.client.AcknowledgementHandler;
 import org.jboss.messaging.core.client.ClientMessage;
+import org.jboss.messaging.core.client.FileClientMessage;
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.message.impl.MessageImpl;
 import org.jboss.messaging.core.remoting.Channel;
+import org.jboss.messaging.core.remoting.impl.ByteBufferWrapper;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionProducerCloseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionScheduledSendMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendChunkMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendManagementMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendMessage;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
 import org.jboss.messaging.util.SimpleString;
 import org.jboss.messaging.util.TokenBucketLimiter;
 
-import java.util.concurrent.Semaphore;
-
 /**
  * The client-side Producer connectionFactory class.
  * 
@@ -43,8 +58,6 @@
 
    // Attributes -----------------------------------------------------------------------------------
 
-   private final boolean trace = log.isTraceEnabled();
-
    private final SimpleString address;
 
    private final long id;
@@ -72,6 +85,8 @@
    private final int initialWindowSize;
 
    private final SimpleString autoGroupId;
+   
+   private final int bigMessageSize;
 
    // Static ---------------------------------------------------------------------------------------
 
@@ -85,6 +100,7 @@
                              final boolean blockOnPersistentSend,
                              final SimpleString autoGroupId,
                              final int initialCredits,
+                             final int bigMessageSize,
                              final Channel channel)
    {
       this.channel = channel;
@@ -102,6 +118,8 @@
       this.blockOnPersistentSend = blockOnPersistentSend;
 
       this.autoGroupId = autoGroupId;
+      
+      this.bigMessageSize = bigMessageSize;
 
       availableCredits = new Semaphore(initialCredits);
 
@@ -131,14 +149,14 @@
       doSend(address, msg, 0);
    }
 
-    public void send(final ClientMessage msg, long scheduleDeliveryTime) throws MessagingException
+   public void send(final ClientMessage msg, final long scheduleDeliveryTime) throws MessagingException
    {
       checkClosed();
 
       doSend(null, msg, scheduleDeliveryTime);
    }
 
-   public void send(final SimpleString address, final ClientMessage msg, long scheduleDeliveryTime) throws MessagingException
+   public void send(final SimpleString address, final ClientMessage msg, final long scheduleDeliveryTime) throws MessagingException
    {
       checkClosed();
 
@@ -150,29 +168,29 @@
    public void sendManagement(final ClientMessage msg) throws MessagingException
    {
       checkClosed();
-      
+
       if (address != null)
       {
          msg.setDestination(address);
       }
       else
       {
-         msg.setDestination(this.address);
+         msg.setDestination(address);
       }
-      
+
       if (rateLimiter != null)
       {
          // Rate flow control
-                  
+
          rateLimiter.limit();
       }
-      
+
       boolean sendBlocking = msg.isDurable() ? blockOnPersistentSend : blockOnNonPersistentSend;
-      
+
       SessionSendManagementMessage message = new SessionSendManagementMessage(id, msg, false);
-      
+
       if (sendBlocking)
-      {        
+      {
          channel.sendBlocking(message);
       }
       else
@@ -287,7 +305,7 @@
       closed = true;
    }
 
-   private void doSend(final SimpleString address, final ClientMessage msg, long scheduledDeliveryTime) throws MessagingException
+   private void doSend(final SimpleString address, final ClientMessage msg, final long scheduledDeliveryTime) throws MessagingException
    {
       if (address != null)
       {
@@ -305,33 +323,40 @@
          rateLimiter.limit();
       }
 
-      if(autoGroupId != null)
+      if (autoGroupId != null)
       {
          msg.putStringProperty(MessageImpl.GROUP_ID, autoGroupId);
       }
 
       boolean sendBlocking = msg.isDurable() ? blockOnPersistentSend : blockOnNonPersistentSend;
 
-      SessionSendMessage message;
-      //check to see if this message need to be scheduled.
-      if(scheduledDeliveryTime <= 0)
+      if (msg.getEncodeSize() > bigMessageSize)
       {
-         message = new SessionSendMessage(id, msg, sendBlocking);
+         sendMessageInChunks(sendBlocking, msg, scheduledDeliveryTime);
       }
       else
       {
-         message = new SessionScheduledSendMessage(id, msg, sendBlocking, scheduledDeliveryTime);
-      }
+         SessionSendMessage message;
 
+         // check to see if this message need to be scheduled.
+         if (scheduledDeliveryTime <= 0)
+         {
+            message = new SessionSendMessage(id, msg, sendBlocking);
+         }
+         else
+         {
+            message = new SessionScheduledSendMessage(id, msg, sendBlocking, scheduledDeliveryTime);
+         }
 
-      if (sendBlocking)
-      {
-         channel.sendBlocking(message);
+         if (sendBlocking)
+         {
+            channel.sendBlocking(message);
+         }
+         else
+         {
+            channel.send(message);
+         }
       }
-      else
-      {
-         channel.send(message);
-      }
 
 //      // We only flow control with non-anonymous producers
 //      if (address == null && creditFlowControl)
@@ -346,6 +371,80 @@
 //      }
    }
 
+   /**
+    * @param msg
+    * @throws MessagingException
+    */
+   private void sendMessageInChunks(final boolean sendBlocking, final ClientMessage msg, final long scheduledDelivery) throws MessagingException
+   {
+      int headerSize = msg.getPropertiesEncodeSize();
+
+      if (headerSize > bigMessageSize)
+      {
+         throw new MessagingException(MessagingException.ILLEGAL_STATE,
+                                      "Header size is too big, use the messageBody for large data");
+      }
+
+      MessagingBuffer headerBuffer = new ByteBufferWrapper(ByteBuffer.allocate(headerSize));
+      msg.encodeProperties(headerBuffer);
+
+      final int bodySize = msg.getBodySize();
+
+      int bodyLength = bigMessageSize - headerSize;
+
+      MessagingBuffer bodyBuffer = new ByteBufferWrapper(ByteBuffer.allocate(bodyLength));
+
+      msg.encodeBody(bodyBuffer, 0, bodyLength);
+
+      SessionSendChunkMessage chunk = new SessionSendChunkMessage(id,
+                                                                  headerBuffer.array(),
+                                                                  bodyBuffer.array(),
+                                                                  bodyLength < bodySize,
+                                                                  sendBlocking,
+                                                                  scheduledDelivery);
+
+      if (sendBlocking)
+      {
+         channel.sendBlocking(chunk);
+      }
+      else
+      {
+         channel.send(chunk);
+      }
+
+      for (int pos = bodyLength; pos < bodySize;)
+      {
+         bodyLength = Math.min(bodySize - pos, bigMessageSize);
+         bodyBuffer = new ByteBufferWrapper(ByteBuffer.allocate(bodyLength));
+
+         msg.encodeBody(bodyBuffer, pos, bodyLength);
+
+         chunk = new SessionSendChunkMessage(id, null, bodyBuffer.array(), pos + bodyLength < bodySize, sendBlocking, scheduledDelivery);
+
+         if (sendBlocking)
+         {
+            channel.sendBlocking(chunk);
+         }
+         else
+         {
+            channel.send(chunk);
+         }
+
+         pos += bodyLength;
+      }
+      
+      if (msg instanceof FileClientMessage)
+      {
+         try
+         {
+            ((FileClientMessage)msg).closeChannel();
+         }
+         catch (Exception e)
+         {
+         }
+      }
+   }
+
    private void checkClosed() throws MessagingException
    {
       if (closed)

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -51,6 +51,9 @@
 
    public static final long DEFAULT_PING_PERIOD = 5000;
 
+   // Any message beyond this size is considered a big message (to be chunked)
+   public static final int DEFAULT_BIG_MESSAGE_SIZE = 100 * 1024;
+   
    public static final int DEFAULT_CONSUMER_WINDOW_SIZE = 1024 * 1024;
 
    public static final int DEFAULT_CONSUMER_MAX_RATE = -1;
@@ -86,6 +89,8 @@
    private volatile long pingPeriod;
 
    private volatile long callTimeout;
+   
+   private volatile int bigMessageSize;
 
    private volatile int consumerWindowSize;
 
@@ -124,6 +129,7 @@
                                    final int consumerMaxRate,
                                    final int producerWindowSize,
                                    final int producerMaxRate,
+                                   final int bigMessageSize,
                                    final boolean blockOnAcknowledge,
                                    final boolean blockOnNonPersistentSend,
                                    final boolean blockOnPersistentSend,
@@ -145,6 +151,7 @@
       this.blockOnAcknowledge = blockOnAcknowledge;
       this.blockOnNonPersistentSend = blockOnNonPersistentSend;
       this.blockOnPersistentSend = blockOnPersistentSend;
+      this.bigMessageSize = bigMessageSize;
       this.autoGroupId = autoGroupId;
       connectionRegistry = ConnectionRegistryImpl.instance;
    }
@@ -168,6 +175,7 @@
       blockOnAcknowledge = DEFAULT_BLOCK_ON_ACKNOWLEDGE;
       blockOnPersistentSend = DEFAULT_BLOCK_ON_PERSISTENT_SEND;
       blockOnNonPersistentSend = DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND;
+      bigMessageSize = DEFAULT_BIG_MESSAGE_SIZE;
       autoGroupId = DEFAULT_AUTO_GROUP_ID;
       connectionRegistry = ConnectionRegistryImpl.instance;
    }
@@ -188,6 +196,7 @@
       blockOnAcknowledge = DEFAULT_BLOCK_ON_ACKNOWLEDGE;
       blockOnPersistentSend = DEFAULT_BLOCK_ON_PERSISTENT_SEND;
       blockOnNonPersistentSend = DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND;
+      bigMessageSize = DEFAULT_BIG_MESSAGE_SIZE;
       autoGroupId = DEFAULT_AUTO_GROUP_ID;
       connectionRegistry = ConnectionRegistryImpl.instance;
    }
@@ -388,6 +397,22 @@
       return sessions.size();
    }
 
+   /**
+    * @return the bigMessageSize
+    */
+   public int getBigMessageSize()
+   {
+      return bigMessageSize;
+   }
+
+   /**
+    * @param bigMessageSize the bigMessageSize to set
+    */
+   public void setBigMessageSize(int bigMessageSize)
+   {
+      this.bigMessageSize = bigMessageSize;
+   }
+
    // ClientSessionFactoryInternal implementation
    // ------------------------------------------
 
@@ -494,6 +519,7 @@
                                                    clientVersion.getIncrementingVersion(),
                                                    username,
                                                    password,
+                                                   bigMessageSize,
                                                    xa,
                                                    autoCommitSends,
                                                    autoCommitAcks);

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -21,6 +21,9 @@
  */
 package org.jboss.messaging.core.client.impl;
 
+import java.io.File;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
@@ -38,6 +41,7 @@
 import org.jboss.messaging.core.client.ClientMessage;
 import org.jboss.messaging.core.client.ClientProducer;
 import org.jboss.messaging.core.client.ClientSessionFactory;
+import org.jboss.messaging.core.client.FileClientMessage;
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.Channel;
@@ -45,6 +49,7 @@
 import org.jboss.messaging.core.remoting.FailureListener;
 import org.jboss.messaging.core.remoting.Packet;
 import org.jboss.messaging.core.remoting.RemotingConnection;
+import org.jboss.messaging.core.remoting.impl.ByteBufferWrapper;
 import org.jboss.messaging.core.remoting.impl.ConnectionRegistryImpl;
 import org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl;
 import org.jboss.messaging.core.remoting.impl.wireformat.ReattachSessionMessage;
@@ -65,6 +70,7 @@
 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;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendChunkMessage;
 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;
@@ -162,6 +168,8 @@
 
    private volatile boolean started;
 
+   private Map<Long, ClientMessage> currentChunk = new ConcurrentHashMap<Long, ClientMessage>();
+
    // Constructors ----------------------------------------------------------------------------
 
    public ClientSessionImpl(final ClientSessionFactoryInternal sessionFactory,
@@ -297,7 +305,8 @@
                             filterString,
                             direct,
                             connectionFactory.getConsumerWindowSize(),
-                            connectionFactory.getConsumerMaxRate(), false);
+                            connectionFactory.getConsumerMaxRate(),
+                            false);
    }
 
    public ClientConsumer createConsumer(final SimpleString queueName,
@@ -305,11 +314,12 @@
                                         final boolean direct,
                                         final boolean browseOnly) throws MessagingException
    {
-       return createConsumer(queueName,
+      return createConsumer(queueName,
                             filterString,
                             direct,
                             connectionFactory.getConsumerWindowSize(),
-                            connectionFactory.getConsumerMaxRate(), browseOnly);
+                            connectionFactory.getConsumerMaxRate(),
+                            browseOnly);
    }
 
    public ClientConsumer createConsumer(final SimpleString queueName,
@@ -319,64 +329,58 @@
                                         final int maxRate,
                                         final boolean browseOnly) throws MessagingException
    {
+      return internalCreateConsumer(queueName, filterString, direct, windowSize, maxRate, browseOnly, null);
+   }
+
+   public ClientConsumer createFileConsumer(final File directory, final SimpleString queueName) throws MessagingException
+   {
       checkClosed();
 
-      SessionCreateConsumerMessage request = new SessionCreateConsumerMessage(queueName,
-                                                                              filterString,
-                                                                              windowSize,
-                                                                              maxRate,
-                                                                              browseOnly);
+      return createFileConsumer(directory, queueName, null, false);
+   }
 
-      SessionCreateConsumerResponseMessage response = (SessionCreateConsumerResponseMessage)channel.sendBlocking(request);
+   public ClientConsumer createFileConsumer(final File directory,
+                                            final SimpleString queueName,
+                                            final SimpleString filterString,
+                                            final boolean direct) throws MessagingException
+   {
+      checkClosed();
 
-      // The actual windows size that gets used is determined by the user since
-      // could be overridden on the queue settings
-      // The value we send is just a hint
-      int actualWindowSize = response.getWindowSize();
+      return createFileConsumer(directory,
+                                queueName,
+                                filterString,
+                                direct,
+                                connectionFactory.getConsumerWindowSize(),
+                                connectionFactory.getConsumerMaxRate(),
+                                false);
+   }
 
-      int clientWindowSize;
-      if (actualWindowSize == -1)
-      {
-         // No flow control - buffer can increase without bound! Only use with
-         // caution for very fast consumers
-         clientWindowSize = 0;
-      }
-      else if (actualWindowSize == 1)
-      {
-         // Slow consumer - no buffering
-         clientWindowSize = 1;
-      }
-      else if (actualWindowSize > 1)
-      {
-         // Client window size is half server window size
-         clientWindowSize = actualWindowSize >> 1;
-      }
-      else
-      {
-         throw new IllegalArgumentException("Invalid window size " + actualWindowSize);
-      }
+   public ClientConsumer createFileConsumer(final File directory,
+                                            final SimpleString queueName,
+                                            final SimpleString filterString,
+                                            final boolean direct,
+                                            final boolean browseOnly) throws MessagingException
+   {
+      return createFileConsumer(directory,
+                                queueName,
+                                filterString,
+                                direct,
+                                connectionFactory.getConsumerWindowSize(),
+                                connectionFactory.getConsumerMaxRate(),
+                                browseOnly);
+   }
 
-      long consumerID = idGenerator.generateID();
-
-      ClientConsumerInternal consumer = new ClientConsumerImpl(this,
-                                                               consumerID,
-                                                               clientWindowSize,
-                                                               direct,
-                                                               executor,
-                                                               channel);
-
-      addConsumer(consumer);
-
-      // Now we send window size credits to start the consumption
-      // We even send it if windowSize == -1, since we need to start the
-      // consumer
-
-      channel.send(new SessionConsumerFlowCreditMessage(consumerID, response.getWindowSize()));
-
-      return consumer;
+   public ClientConsumer createFileConsumer(File directory,
+                                            SimpleString queueName,
+                                            SimpleString filterString,
+                                            boolean direct,
+                                            int windowSize,
+                                            int maxRate,
+                                            boolean browseOnly) throws MessagingException
+   {
+      return internalCreateConsumer(queueName, filterString, direct, windowSize, maxRate, browseOnly, directory);
    }
 
-
    public ClientProducer createProducer(final SimpleString address) throws MessagingException
    {
       checkClosed();
@@ -447,6 +451,7 @@
                                            autoCommitSends && blockOnPersistentSend,
                                            response.getAutoGroupId(),
                                            response.getInitialCredits(),
+                                           sessionFactory.getBigMessageSize(),
                                            channel);
       }
 
@@ -471,10 +476,10 @@
    {
       checkClosed();
 
-      //We do a "JMS style" rollback where the session is stopped, and the buffer is cancelled back
-      //first before rolling back
-      //This ensures messages are received in the same order after rollback w.r.t. to messages in the buffer
-      //For core we could just do a straight rollback, it really depends if we want JMS style semantics or not...
+      // We do a "JMS style" rollback where the session is stopped, and the buffer is cancelled back
+      // first before rolling back
+      // This ensures messages are received in the same order after rollback w.r.t. to messages in the buffer
+      // For core we could just do a straight rollback, it really depends if we want JMS style semantics or not...
 
       boolean wasStarted = started;
 
@@ -522,6 +527,11 @@
       return new ClientMessageImpl(durable, body);
    }
 
+   public FileClientMessage createFileMessage(final boolean durable)
+   {
+      return new FileClientMessageImpl(durable);
+   }
+
    public boolean isClosed()
    {
       return closed;
@@ -666,6 +676,73 @@
       }
    }
 
+   public void handleReceiveChunk(final long consumerID, final SessionSendChunkMessage chunk) throws Exception
+   {
+      ClientMessage currentChunkMessage;
+
+      if (chunk.getHeader() != null)
+      {
+
+         // The Header only comes on the first message, so a buffer has to be created on the client
+         // to hold either a file or a big message
+         MessagingBuffer header = new ByteBufferWrapper(ByteBuffer.wrap(chunk.getHeader()));
+
+         currentChunkMessage = createLargeMessage(consumerID, header);
+
+         if (currentChunkMessage instanceof FileClientMessage)
+         {
+            FileClientMessage fileMessage = (FileClientMessage)currentChunkMessage;
+            addBytesBody(fileMessage, chunk.getBody());
+         }
+         else
+         {
+            MessagingBuffer initialBody = new ByteBufferWrapper(ByteBuffer.wrap(chunk.getBody()));
+            currentChunkMessage.setBody(initialBody);
+         }
+
+         currentChunk.put(consumerID, currentChunkMessage);
+      }
+      else
+      {
+         // No header.. this is then a continuation of a previous message
+         ByteBuffer body = ByteBuffer.wrap(chunk.getBody());
+
+         currentChunkMessage = currentChunk.get(consumerID);
+
+         if (currentChunkMessage instanceof FileClientMessage)
+         {
+            FileClientMessage fileMessage = (FileClientMessage)currentChunkMessage;
+            addBytesBody(fileMessage, chunk.getBody());
+         }
+         else
+         {
+            MessagingBuffer currentBody = currentChunkMessage.getBody();
+
+            MessagingBuffer newBody = new ByteBufferWrapper(ByteBuffer.allocate(currentBody.limit() + body.limit()));
+
+            newBody.putBytes(currentBody.array());
+            newBody.putBytes(body.array());
+
+            currentChunkMessage.setBody(newBody);
+         }
+      }
+
+      if (!chunk.isContinues())
+      {
+         if (currentChunkMessage instanceof FileClientMessage)
+         {
+            ((FileClientMessage)currentChunkMessage).closeChannel();
+         }
+         handleReceiveMessage(consumerID, currentChunkMessage);
+      }
+   }
+
+   private void addBytesBody(FileClientMessage fileMessage, byte[] body) throws Exception
+   {
+      FileChannel channel = fileMessage.getChannel();
+      channel.write(ByteBuffer.wrap(body));
+   }
+
    public void receiveProducerCredits(final long producerID, final int credits) throws Exception
    {
       ClientProducerInternal producer = producers.get(producerID);
@@ -709,7 +786,19 @@
       doCleanup();
    }
 
-   //Needs to be synchronized to prevent issues with occurring concurrently with close()
+   public ClientMessage createLargeMessage(final long consumerID, final MessagingBuffer header) throws Exception
+   {
+      ClientConsumerInternal consumer = consumers.get(consumerID);
+
+      if (consumer == null)
+      {
+         throw new IllegalStateException("No Consumer with ID = " + consumerID);
+      }
+
+      return consumer.createFileMessage(header);
+   }
+
+   // Needs to be synchronized to prevent issues with occurring concurrently with close()
    public synchronized boolean handleFailover(final RemotingConnection backupConnection)
    {
       if (closed)
@@ -1075,7 +1164,82 @@
 
    // Private
    // ----------------------------------------------------------------------------
+   /**
+    * @param queueName
+    * @param filterString
+    * @param direct
+    * @param windowSize
+    * @param maxRate
+    * @param browseOnly
+    * @return
+    * @throws MessagingException
+    */
+   private ClientConsumer internalCreateConsumer(final SimpleString queueName,
+                                                 final SimpleString filterString,
+                                                 final boolean direct,
+                                                 final int windowSize,
+                                                 final int maxRate,
+                                                 final boolean browseOnly,
+                                                 final File directory) throws MessagingException
+   {
+      checkClosed();
 
+      SessionCreateConsumerMessage request = new SessionCreateConsumerMessage(queueName,
+                                                                              filterString,
+                                                                              windowSize,
+                                                                              maxRate,
+                                                                              browseOnly);
+
+      SessionCreateConsumerResponseMessage response = (SessionCreateConsumerResponseMessage)channel.sendBlocking(request);
+
+      // The actual windows size that gets used is determined by the user since
+      // could be overridden on the queue settings
+      // The value we send is just a hint
+      int actualWindowSize = response.getWindowSize();
+
+      int clientWindowSize;
+      if (actualWindowSize == -1)
+      {
+         // No flow control - buffer can increase without bound! Only use with
+         // caution for very fast consumers
+         clientWindowSize = 0;
+      }
+      else if (actualWindowSize == 1)
+      {
+         // Slow consumer - no buffering
+         clientWindowSize = 1;
+      }
+      else if (actualWindowSize > 1)
+      {
+         // Client window size is half server window size
+         clientWindowSize = actualWindowSize >> 1;
+      }
+      else
+      {
+         throw new IllegalArgumentException("Invalid window size " + actualWindowSize);
+      }
+
+      long consumerID = idGenerator.generateID();
+
+      ClientConsumerInternal consumer = new ClientConsumerImpl(this,
+                                                               consumerID,
+                                                               clientWindowSize,
+                                                               direct,
+                                                               executor,
+                                                               channel,
+                                                               directory);
+
+      addConsumer(consumer);
+
+      // Now we send window size credits to start the consumption
+      // We even send it if windowSize == -1, since we need to start the
+      // consumer
+
+      channel.send(new SessionConsumerFlowCreditMessage(consumerID, response.getWindowSize()));
+
+      return consumer;
+   }
+
    private void checkXA() throws XAException
    {
       if (!xa)
@@ -1099,13 +1263,13 @@
       {
          producerCache.clear();
       }
-     
+
       remotingConnection.removeFailureListener(this);
 
       synchronized (this)
       {
          closed = true;
-         
+
          channel.close();
 
          connectionRegistry.returnConnection(remotingConnection.getID());

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientSessionInternal.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientSessionInternal.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientSessionInternal.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -16,6 +16,8 @@
 import org.jboss.messaging.core.client.ClientSession;
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.remoting.RemotingConnection;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendChunkMessage;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
 import org.jboss.messaging.util.SimpleString;
 
 import java.util.Map;
@@ -49,6 +51,11 @@
    void receiveProducerCredits(long producerID, int credits) throws Exception;
 
    void handleReceiveMessage(long consumerID, ClientMessage message) throws Exception;
+   
+   void handleReceiveChunk(long consumerID, SessionSendChunkMessage chunk) throws Exception;
 
    boolean handleFailover(final RemotingConnection backupConnection);
+
+   ClientMessage createLargeMessage(long consumerID, MessagingBuffer header) throws Exception;
+
 }

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientSessionPacketHandler.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientSessionPacketHandler.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/ClientSessionPacketHandler.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -23,16 +23,31 @@
 package org.jboss.messaging.core.client.impl;
 
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.EXCEPTION;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_CHUNK_SEND;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_RECEIVETOKENS;
 import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_RECEIVE_MSG;
 
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+import org.jboss.messaging.core.client.ClientMessage;
+import org.jboss.messaging.core.client.FileClientMessage;
+import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.ChannelHandler;
 import org.jboss.messaging.core.remoting.Packet;
+import org.jboss.messaging.core.remoting.impl.ByteBufferWrapper;
 import org.jboss.messaging.core.remoting.impl.wireformat.MessagingExceptionMessage;
-import org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionProducerFlowCreditMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionReceiveMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendChunkMessage;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
 
 /**
  *
@@ -48,42 +63,49 @@
    private final ClientSessionInternal clientSession;
 
    public ClientSessionPacketHandler(final ClientSessionInternal clientSesssion)
-   {     
+   {
       this.clientSession = clientSesssion;
    }
-      
+
    public void handlePacket(final Packet packet)
    {
       byte type = packet.getType();
-       
+
       try
       {
          switch (type)
          {
             case SESS_RECEIVETOKENS:
             {
-               SessionProducerFlowCreditMessage message = (SessionProducerFlowCreditMessage) packet;
-   
+               SessionProducerFlowCreditMessage message = (SessionProducerFlowCreditMessage)packet;
+
                clientSession.receiveProducerCredits(message.getProducerID(), message.getTokens());
-               
+
                break;
             }
+            case SESS_CHUNK_SEND:
+            {
+               SessionSendChunkMessage chunk = (SessionSendChunkMessage)packet;
+               clientSession.handleReceiveChunk(chunk.getTargetID(), chunk);
+
+               break;
+            }
             case SESS_RECEIVE_MSG:
             {
-               SessionReceiveMessage message = (SessionReceiveMessage) packet;
-      
+               SessionReceiveMessage message = (SessionReceiveMessage)packet;
+
                clientSession.handleReceiveMessage(message.getConsumerID(), message.getClientMessage());
-               
+
                break;
             }
             case EXCEPTION:
             {
-               //TODO - we can provide a means for async exceptions to get back to to client
-               //For now we just log it
+               // TODO - we can provide a means for async exceptions to get back to to client
+               // For now we just log it
                MessagingExceptionMessage mem = (MessagingExceptionMessage)packet;
-               
+
                log.error("Received exception asynchronously from server", mem.getException());
-               
+
                break;
             }
             default:
@@ -97,4 +119,17 @@
          log.error("Failed to handle packet", e);
       }
    }
+
+   /**
+    * @param chunk
+    * @throws Exception
+    * @throws MessagingException
+    */
+
+   /**
+    * @param fileMessage
+    * @param body
+    * @throws FileNotFoundException
+    * @throws IOException
+    */
 }
\ No newline at end of file

Added: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/FileClientMessageImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/FileClientMessageImpl.java	                        (rev 0)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/client/impl/FileClientMessageImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -0,0 +1,261 @@
+/*
+ * 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.client.impl;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+
+import org.jboss.messaging.core.client.FileClientMessage;
+import org.jboss.messaging.core.exception.MessagingException;
+import org.jboss.messaging.core.remoting.impl.ByteBufferWrapper;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
+
+/**
+ * A FileClientMessageImpl
+ *
+ * @author <a href="mailto:clebert.suconic at jboss.org">Clebert Suconic</a>
+ * 
+ * Created Oct 13, 2008 4:33:56 PM
+ *
+ *
+ */
+public class FileClientMessageImpl extends ClientMessageImpl implements FileClientMessage
+{
+
+   File file;
+
+   FileChannel currentChannel;
+
+   /**
+    * 
+    */
+   public FileClientMessageImpl()
+   {
+      super();
+   }
+   
+
+   public FileClientMessageImpl(boolean durable)
+   {
+      super(durable, null);
+   }
+
+
+
+   /**
+    * @param type
+    * @param durable
+    * @param expiration
+    * @param timestamp
+    * @param priority
+    * @param body
+    */
+   public FileClientMessageImpl(byte type,
+                                boolean durable,
+                                long expiration,
+                                long timestamp,
+                                byte priority,
+                                MessagingBuffer body)
+   {
+      super(type, durable, expiration, timestamp, priority, body);
+      // TODO Auto-generated constructor stub
+   }
+
+
+
+   /**
+    * @param type
+    * @param durable
+    * @param body
+    */
+   public FileClientMessageImpl(byte type, boolean durable, MessagingBuffer body)
+   {
+      super(type, durable, body);
+      // TODO Auto-generated constructor stub
+   }
+
+
+
+   /**
+    * @param deliveryCount
+    */
+   public FileClientMessageImpl(final int deliveryCount)
+   {
+      super(deliveryCount);
+   }
+
+   // Constants -----------------------------------------------------
+
+   // Attributes ----------------------------------------------------
+
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   // Public --------------------------------------------------------
+
+   /**
+    * @return the file
+    */
+   public File getFile()
+   {
+      return file;
+   }
+
+   /**
+    * @param file the file to set
+    */
+   public void setFile(final File file)
+   {
+      this.file = file;
+   }
+
+   @Override
+   public MessagingBuffer getBody()
+   {
+      FileChannel channel = null;
+      try
+      {
+         // We open a new channel on getBody.
+         // for a better performance, users should be using the channels when using file
+         channel = newChannel();
+
+         ByteBuffer buffer = ByteBuffer.allocate((int)channel.size());
+
+         channel.position(0);
+         channel.read(buffer);
+
+         return new ByteBufferWrapper(buffer);
+      }
+      catch (Exception e)
+      {
+         throw new RuntimeException(e);
+      }
+      finally
+      {
+         try
+         {
+            channel.close();
+         }
+         catch (Throwable ignored)
+         {
+
+         }
+      }
+   }
+   
+   public synchronized void encodeBody(MessagingBuffer buffer, int start, int size)
+   {
+      try
+      {
+         FileChannel channel = getChannel();
+         
+         ByteBuffer bufferRead = ByteBuffer.allocate(size);
+         
+         channel.position(start);
+         channel.read(bufferRead);
+         
+         buffer.putBytes(bufferRead.array());
+      }
+      catch (Exception e)
+      {
+         throw new RuntimeException(e.getMessage(), e);
+      }
+      
+   }
+   
+
+   @Override
+   public void setBody(final MessagingBuffer body)
+   {
+
+      throw new RuntimeException("Not supported");
+   }
+
+   public synchronized FileChannel getChannel() throws MessagingException
+   {
+      if (currentChannel == null)
+      {
+         currentChannel = newChannel();
+      }
+
+      return currentChannel;
+   }
+
+   public synchronized void closeChannel() throws MessagingException
+   {
+      if (currentChannel != null)
+      {
+         try
+         {
+            currentChannel.close();
+         }
+         catch (IOException e)
+         {
+            throw new MessagingException(MessagingException.INTERNAL_ERROR, e.getMessage(), e);
+         }
+         currentChannel = null;
+      }
+
+   }
+
+   @Override
+   public synchronized int getBodySize()
+   {
+      return (int)file.length();
+   }
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   /**
+    * @return
+    * @throws FileNotFoundException
+    * @throws IOException
+    */
+   private FileChannel newChannel() throws MessagingException
+   {
+      try
+      {
+         RandomAccessFile randomFile = new RandomAccessFile(getFile(), "rw");
+         randomFile.seek(0);
+   
+         FileChannel channel = randomFile.getChannel();
+         return channel;
+      }
+      catch (IOException e)
+      {
+         throw new MessagingException(MessagingException.INTERNAL_ERROR, e.getMessage(), e);  
+      }
+   }
+
+   // Inner classes -------------------------------------------------
+
+}

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/config/Configuration.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/config/Configuration.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/config/Configuration.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -37,8 +37,7 @@
  */
 public interface Configuration extends Serializable
 {
-   // General attributes
-   // -------------------------------------------------------------------
+   // General attributes -------------------------------------------------------------------
 
    boolean isClustered();
 
@@ -92,9 +91,10 @@
 
    void setBackupConnectorConfiguration(TransportConfiguration config);
 
-   // Journal related attributes
-   // ------------------------------------------------------------
+   boolean isWildcardRoutingEnabled();
 
+   // Journal related attributes ------------------------------------------------------------
+
    String getBindingsDirectory();
 
    void setBindingsDirectory(String dir);
@@ -103,10 +103,6 @@
 
    void setJournalDirectory(String dir);
 
-   String getPagingDirectory();
-
-   void setPagingDirectory(String dir);
-
    JournalType getJournalType();
 
    void setJournalType(JournalType type);
@@ -143,9 +139,24 @@
 
    void setCreateJournalDir(boolean create);
 
+   
+   // Paging Properties --------------------------------------------------------------------
+   
+   String getPagingDirectory();
+
+   void setPagingDirectory(String dir);
+
    long getPagingMaxGlobalSizeBytes();
 
    void setPagingMaxGlobalSizeBytes(long maxGlobalSize);
-
-   boolean isWildcardRoutingEnabled();
+   
+   long getPagingDefaultSize();
+   
+   void setPagingDefaultSize(long pageSize);
+   
+   // Large Messages Properties ------------------------------------------------------------
+   
+   String getLargeMessagesDirectory();
+   
+   void setLargeMessagesDirectory(String directory);
 }

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/config/impl/ConfigurationImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/config/impl/ConfigurationImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/config/impl/ConfigurationImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -58,6 +58,10 @@
    public static final String DEFAULT_JOURNAL_DIR = "data/journal";
 
    public static final String DEFAULT_PAGING_DIR = "data/paging";
+   
+   public static final long DEFAULT_DEFAULT_PAGE_SIZE = 10 * 1024 * 1024;
+   
+   public static final String DEFAULT_LARGEMESSAGES_DIR = "data/largemessages";
 
    public static final boolean DEFAULT_CREATE_JOURNAL_DIR = true;
 
@@ -105,14 +109,21 @@
 
    protected TransportConfiguration backupConnectorConfig;
 
-   // Paging related attributes
+   protected boolean wildcardRoutingEnabled = DEFAULT_WILDCARD_ROUTING_ENABLED;
 
+   // Paging related attributes ------------------------------------------------------------
+
    protected long pagingMaxGlobalSize = -1;
+   
+   protected long pagingDefaultSize = DEFAULT_DEFAULT_PAGE_SIZE;
 
    protected String pagingDirectory = DEFAULT_PAGING_DIR;
+   
 
-   // Journal related attributes
+   // File related attributes -----------------------------------------------------------
 
+   protected String largeMessagesDirectory = DEFAULT_LARGEMESSAGES_DIR;
+   
    protected String bindingsDirectory = DEFAULT_BINDINGS_DIRECTORY;
 
    protected boolean createBindingsDir = DEFAULT_CREATE_BINDINGS_DIR;
@@ -135,8 +146,6 @@
 
    protected int journalBufferReuseSize = DEFAULT_JOURNAL_REUSE_BUFFER_SIZE;
 
-   protected boolean wildcardRoutingEnabled = DEFAULT_WILDCARD_ROUTING_ENABLED;
-
    public boolean isClustered()
    {
       return clustered;
@@ -401,7 +410,35 @@
    {
       pagingMaxGlobalSize = maxGlobalSize;
    }
+   
+   /* (non-Javadoc)
+    * @see org.jboss.messaging.core.config.Configuration#getPagingDefaultSize()
+    */
+   public long getPagingDefaultSize()
+   {
+      return pagingDefaultSize;
+   }
 
+   /* (non-Javadoc)
+    * @see org.jboss.messaging.core.config.Configuration#setPagingDefaultSize(long)
+    */
+   public void setPagingDefaultSize(long pageSize)
+   {
+      this.pagingDefaultSize = pageSize;
+   }
+   
+   
+   public String getLargeMessagesDirectory()
+   {
+      return largeMessagesDirectory;
+   }
+   
+   public void setLargeMessagesDirectory(final String directory)
+   {
+      this.largeMessagesDirectory = directory;
+   }
+   
+
    @Override
    public boolean equals(final Object other)
    {
@@ -424,6 +461,7 @@
              cother.isRequireDestinations() == isRequireDestinations() &&
              cother.isSecurityEnabled() == isSecurityEnabled() &&
              cother.isWildcardRoutingEnabled() == isWildcardRoutingEnabled() &&
+             cother.getLargeMessagesDirectory().equals(getLargeMessagesDirectory()) &&
              cother.getBindingsDirectory().equals(getBindingsDirectory()) &&
              cother.getJournalDirectory().equals(getJournalDirectory()) &&
              cother.getJournalFileSize() == getJournalFileSize() &&
@@ -431,7 +469,11 @@
              cother.getJournalMinFiles() == getJournalMinFiles() &&
              cother.getJournalType() == getJournalType() &&
              cother.getScheduledThreadPoolMaxSize() == getScheduledThreadPoolMaxSize() &&
-             cother.getSecurityInvalidationInterval() == getSecurityInvalidationInterval();
+             cother.getSecurityInvalidationInterval() == getSecurityInvalidationInterval() &&
+             cother.getPagingDefaultSize() == getPagingDefaultSize();
    }
 
+   
+   
+
 }

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/config/impl/FileConfiguration.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/config/impl/FileConfiguration.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/config/impl/FileConfiguration.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -306,6 +306,8 @@
 
       // Persistence config
 
+      largeMessagesDirectory = getString(e, "large-messages-directory", largeMessagesDirectory);
+      
       bindingsDirectory = getString(e, "bindings-directory", bindingsDirectory);
 
       createBindingsDir = getBoolean(e, "create-bindings-dir", createBindingsDir);
@@ -315,6 +317,8 @@
       pagingDirectory = getString(e, "paging-directory", pagingDirectory);
       
       pagingMaxGlobalSize = getLong(e, "paging-max-global-size-bytes", pagingMaxGlobalSize);
+      
+      pagingDefaultSize = getLong(e, "paging-default-size", pagingDefaultSize);
 
       createJournalDir = getBoolean(e, "create-journal-dir", createJournalDir);
 

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/exception/MessagingException.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/exception/MessagingException.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/exception/MessagingException.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -82,6 +82,13 @@
       this.code = code;
    }
    
+   public MessagingException(int code, String msg, Throwable cause)
+   {
+      super(msg, cause);
+      
+      this.code = code;
+   }
+   
    public int getCode()
    {
       return code;

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/SequentialFile.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/SequentialFile.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/SequentialFile.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -38,6 +38,8 @@
     * Creates the file if it doesn't already exist, then opens it
     */
    void open() throws Exception;
+   
+   boolean isOpen();
 
    /**
     * For certain operations (like loading) we don't need open the file with full maxIO
@@ -66,14 +68,16 @@
 
    int read(ByteBuffer bytes) throws Exception;
 
-   void position(int pos) throws Exception;
+   void position(long pos) throws Exception;
 
-   int position() throws Exception;
+   long position() throws Exception;
 
    void close() throws Exception;
 
    void sync() throws Exception;
 
    long size() throws Exception;
+   
+   void renameTo(SequentialFile file) throws Exception;
 
 }

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/SequentialFileFactory.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/SequentialFileFactory.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/SequentialFileFactory.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -35,7 +35,7 @@
  */
 public interface SequentialFileFactory
 {
-   SequentialFile createSequentialFile(String fileName, int maxIO) throws Exception;
+   SequentialFile createSequentialFile(String fileName, int maxIO);
 
    List<String> listFiles(String extension) throws Exception;
 

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/AIOSequentialFile.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/AIOSequentialFile.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/AIOSequentialFile.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -67,13 +67,18 @@
    // AIO using a single thread.
    private ExecutorService executor;
 
-   public AIOSequentialFile(final String journalDir, final String fileName, final int maxIO) throws Exception
+   public AIOSequentialFile(final String journalDir, final String fileName, final int maxIO)
    {
       this.journalDir = journalDir;
       this.fileName = fileName;
       this.maxIO = maxIO;
    }
 
+   public boolean isOpen() 
+   {
+      return opened;
+   }
+   
    public int getAlignment() throws Exception
    {
       checkOpened();
@@ -174,6 +179,14 @@
       open(maxIO);
    }
 
+   /* (non-Javadoc)
+    * @see org.jboss.messaging.core.journal.SequentialFile#renameTo(org.jboss.messaging.core.journal.SequentialFile)
+    */
+   public void renameTo(SequentialFile file) throws Exception
+   {
+      throw new IllegalStateException ("method rename not supported on AIO");
+      
+   }
    public synchronized void open(final int currentMaxIO) throws Exception
    {
       opened = true;
@@ -189,14 +202,14 @@
       aioFile.setBufferCallback(callback);
    }
 
-   public void position(final int pos) throws Exception
+   public void position(final long pos) throws Exception
    {
       position.set(pos);
    }
 
-   public int position() throws Exception
+   public long position() throws Exception
    {
-      return (int)position.get();
+      return position.get();
    }
 
    public int read(final ByteBuffer bytes, final IOCallback callback) throws Exception
@@ -363,4 +376,5 @@
          return;
       }
    }
+
 }

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/AIOSequentialFileFactory.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/AIOSequentialFileFactory.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/AIOSequentialFileFactory.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -41,7 +41,7 @@
       super(journalDir);
    }
 
-   public SequentialFile createSequentialFile(final String fileName, final int maxIO) throws Exception
+   public SequentialFile createSequentialFile(final String fileName, final int maxIO)
    {
       return new AIOSequentialFile(journalDir, fileName, maxIO);
    }

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/JournalFile.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/JournalFile.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/JournalFile.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -51,11 +51,11 @@
 
    void extendOffset(final int delta);
 
-   int getOffset();
+   long getOffset();
 
    int getOrderingID();
 
-   void setOffset(final int offset);
+   void setOffset(final long offset);
 
    SequentialFile getFile();
 }

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/JournalFileImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/JournalFileImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/JournalFileImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -46,7 +46,7 @@
 
    private final int orderingID;
 
-   private int offset;
+   private long offset;
 
    private final AtomicInteger posCount = new AtomicInteger(0);
 
@@ -110,7 +110,7 @@
       offset += delta;
    }
 
-   public int getOffset()
+   public long getOffset()
    {
       return offset;
    }
@@ -120,7 +120,7 @@
       return orderingID;
    }
 
-   public void setOffset(final int offset)
+   public void setOffset(final long offset)
    {
       this.offset = offset;
    }

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/NIOSequentialFile.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/NIOSequentialFile.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/journal/impl/NIOSequentialFile.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -43,11 +43,6 @@
 public class NIOSequentialFile implements SequentialFile
 {
    private static final Logger log = Logger.getLogger(NIOSequentialFile.class);
-
-   private final String journalDir;
-
-   private final String fileName;
-
    private File file;
 
    private FileChannel channel;
@@ -58,9 +53,7 @@
 
    public NIOSequentialFile(final String journalDir, final String fileName)
    {
-      this.journalDir = journalDir;
-
-      this.fileName = fileName;
+       this.file = new File(journalDir + "/" + fileName);
    }
 
    public int getAlignment()
@@ -75,13 +68,16 @@
 
    public String getFileName()
    {
-      return fileName;
+      return file.getName();
    }
+   
+   public synchronized boolean isOpen()
+   {
+      return channel != null;
+   }
 
    public synchronized void open() throws Exception
    {
-      file = new File(journalDir + "/" + fileName);
-
       rfile = new RandomAccessFile(file, "rw");
 
       channel = rfile.getChannel();
@@ -119,22 +115,29 @@
 
    public void close() throws Exception
    {
-      channel.close();
+      if (channel != null)
+      {
+         channel.close();
+      }
 
-      rfile.close();
+      if (rfile != null)
+      {
+         rfile.close();
+      }
 
       channel = null;
 
       rfile = null;
-
-      file = null;
    }
 
    public void delete() throws Exception
    {
+      if (isOpen())
+      {
+         close();
+      }
+
       file.delete();
-
-      close();
    }
 
    public int read(final ByteBuffer bytes) throws Exception
@@ -207,7 +210,8 @@
          throw e;
       }
    }
-
+   
+   
    public void sync() throws Exception
    {
       channel.force(false);
@@ -218,14 +222,30 @@
       return channel.size();
    }
 
-   public void position(final int pos) throws Exception
+   public void position(final long pos) throws Exception
    {
       channel.position(pos);
    }
 
-   public int position() throws Exception
+   public long position() throws Exception
    {
-      return (int)channel.position();
+      return channel.position();
    }
 
+   public void renameTo(SequentialFile newFile) throws Exception
+   {
+      close();
+      this.file.renameTo(((NIOSequentialFile)newFile).file);
+      file = ((NIOSequentialFile)newFile).file;
+   }
+   
+   
+   
+   public String toString()
+   {
+      return "NIOSequentialFile " + this.file;
+   }
+
+   
+   
 }

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/message/Message.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/message/Message.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/message/Message.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -24,6 +24,7 @@
 
 import java.util.Set;
 
+import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.journal.EncodingSupport;
 import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
 import org.jboss.messaging.util.SimpleString;
@@ -74,6 +75,26 @@
    
    void decode(MessagingBuffer buffer);
    
+   
+   int getPropertiesEncodeSize();
+   
+   void encodeProperties(MessagingBuffer buffer);
+   
+   void decodeProperties(MessagingBuffer buffer);
+   
+   
+   int getBodySize();
+   
+   
+   // Used on Message chunk
+   void encodeBody(MessagingBuffer buffer, int start, int size);
+   
+   void encodeBody(MessagingBuffer buffer);
+   
+   void decodeBody(MessagingBuffer buffer);
+   
+   
+   
    // Properties
    // ------------------------------------------------------------------
    

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/message/impl/MessageImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/message/impl/MessageImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/message/impl/MessageImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -18,19 +18,27 @@
  * 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.message.impl;
 
+import static org.jboss.messaging.util.DataConstants.SIZE_BOOLEAN;
+import static org.jboss.messaging.util.DataConstants.SIZE_BYTE;
+import static org.jboss.messaging.util.DataConstants.SIZE_INT;
+import static org.jboss.messaging.util.DataConstants.SIZE_LONG;
+
+import java.nio.ByteBuffer;
+import java.util.Set;
+
+import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.message.Message;
+import org.jboss.messaging.core.remoting.impl.ByteBufferWrapper;
 import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
-import static org.jboss.messaging.util.DataConstants.*;
+import org.jboss.messaging.core.server.ServerLargeMessage;
 import org.jboss.messaging.util.SimpleString;
 import org.jboss.messaging.util.TypedProperties;
 
-import java.util.Set;
-
 /**
  * A concrete implementation of a message
  *
@@ -61,7 +69,7 @@
    // Attributes ----------------------------------------------------
 
    protected long messageID;
-   
+
    private SimpleString destination;
 
    private byte type;
@@ -83,7 +91,7 @@
 
    protected MessageImpl()
    {
-      this.properties = new TypedProperties();
+      properties = new TypedProperties();
    }
 
    /**
@@ -95,8 +103,12 @@
     * @param priority
     * @param body
     */
-   protected MessageImpl(final byte type, final boolean durable, final long expiration,
-                         final long timestamp, final byte priority, MessagingBuffer body)
+   protected MessageImpl(final byte type,
+                         final boolean durable,
+                         final long expiration,
+                         final long timestamp,
+                         final byte priority,
+                         final MessagingBuffer body)
    {
       this();
       this.type = type;
@@ -113,17 +125,17 @@
    protected MessageImpl(final MessageImpl other)
    {
       this();
-      this.messageID = other.messageID;
-      this.destination = other.destination;
-      this.type = other.type;
-      this.durable = other.durable;
-      this.expiration = other.expiration;
-      this.timestamp = other.timestamp;
-      this.priority = other.priority;
-      this.properties = new TypedProperties(other.properties);
-      this.body = other.body;
+      messageID = other.messageID;
+      destination = other.destination;
+      type = other.type;
+      durable = other.durable;
+      expiration = other.expiration;
+      timestamp = other.timestamp;
+      priority = other.priority;
+      properties = new TypedProperties(other.properties);
+      body = other.body;
    }
-   
+
    protected MessageImpl(final long messageID)
    {
       this();
@@ -132,34 +144,70 @@
 
    // Message implementation ----------------------------------------
 
-   public void encode(MessagingBuffer buff)
+   public void encode(final MessagingBuffer buffer)
    {
-      buff.putLong(messageID);
-      buff.putSimpleString(destination);
-      buff.putByte(type);
-      buff.putBoolean(durable);
-      buff.putLong(expiration);
-      buff.putLong(timestamp);
-      buff.putByte(priority);
-      properties.encode(buff);
-      buff.putInt(body.limit());    
-      buff.putBytes(body.array(), 0, body.limit());
+      encodeProperties(buffer);
+      buffer.putInt(getBodySize());
+      encodeBody(buffer);
    }
 
    public int getEncodeSize()
    {
-      return SIZE_LONG + /* Destination */ SimpleString.sizeofString(destination) +
-      /* Type */ SIZE_BYTE +
-      /* Durable */ SIZE_BOOLEAN +
-      /* Expiration */ SIZE_LONG +
-      /* Timestamp */ SIZE_LONG +
-      /* Priority */ SIZE_BYTE +
-      /* PropertySize and Properties */ properties.getEncodeSize() +
-      /* BodySize and Body */ SIZE_INT + body.limit();
+      return getPropertiesEncodeSize() + SIZE_INT + getBodySize();
    }
 
+   public int getPropertiesEncodeSize()
+   {
+      return SIZE_LONG + /* Destination */SimpleString.sizeofString(destination) +
+      /* Type */SIZE_BYTE +
+      /* Durable */SIZE_BOOLEAN +
+      /* Expiration */SIZE_LONG +
+      /* Timestamp */SIZE_LONG +
+      /* Priority */SIZE_BYTE +
+      /* PropertySize and Properties */properties.getEncodeSize();
+   }
+
+   public int getBodySize()
+   {
+      return /* BodySize and Body */ body.limit();
+   }
+
+   
+   public void encodeProperties(MessagingBuffer buffer)
+   {
+      buffer.putLong(messageID);
+      buffer.putSimpleString(destination);
+      buffer.putByte(type);
+      buffer.putBoolean(durable);
+      buffer.putLong(expiration);
+      buffer.putLong(timestamp);
+      buffer.putByte(priority);
+      properties.encode(buffer);
+   }
+
+
+   public void encodeBody(MessagingBuffer buffer)
+   {
+      MessagingBuffer localBody = getBody(); 
+      buffer.putBytes(localBody.array(), 0, localBody.limit());
+   }
+   
+   // Used on Message chunk
+   public void encodeBody(MessagingBuffer buffer, int start, int size)
+   {
+      buffer.putBytes(body.array(), start, size);
+   }
+   
+
    public void decode(final MessagingBuffer buffer)
    {
+      decodeProperties(buffer);
+
+      decodeBody(buffer);
+   }
+
+   public void decodeProperties(final MessagingBuffer buffer)
+   {
       messageID = buffer.getLong();
       destination = buffer.getSimpleString();
       type = buffer.getByte();
@@ -167,32 +215,37 @@
       expiration = buffer.getLong();
       timestamp = buffer.getLong();
       priority = buffer.getByte();
+      properties.decode(buffer);
+   }
 
-      properties.decode(buffer);
+   public void decodeBody(final MessagingBuffer buffer)
+   {
       int len = buffer.getInt();
-
-      //TODO - this can be optimised
+       // TODO - this can be optimised
       byte[] bytes = new byte[len];
       buffer.getBytes(bytes);
+//      body = new ByteBufferWrapper(ByteBuffer.wrap(bytes));
+//      body.position(body.limit());
       body = buffer.createNewBuffer(len);
       body.putBytes(bytes);      
+
    }
-   
+
    public long getMessageID()
    {
       return messageID;
    }
-   
+
    public SimpleString getDestination()
    {
       return destination;
    }
-   
-   public void setDestination(SimpleString destination)
+
+   public void setDestination(final SimpleString destination)
    {
       this.destination = destination;
    }
-   
+
    public byte getType()
    {
       return type;
@@ -202,7 +255,7 @@
    {
       return durable;
    }
-   
+
    public void setDurable(final boolean durable)
    {
       this.durable = durable;
@@ -222,12 +275,12 @@
    {
       return timestamp;
    }
-   
+
    public void setTimestamp(final long timestamp)
    {
       this.timestamp = timestamp;
    }
- 
+
    public byte getPriority()
    {
       return priority;
@@ -237,105 +290,105 @@
    {
       this.priority = priority;
    }
-     
+
    public boolean isExpired()
    {
       if (expiration == 0)
       {
          return false;
       }
-      
+
       return System.currentTimeMillis() - expiration >= 0;
    }
-   
-   // Properties 
+
+   // Properties
    // ---------------------------------------------------------------------------------------
-   
+
    public void putBooleanProperty(final SimpleString key, final boolean value)
    {
       properties.putBooleanProperty(key, value);
    }
-            
+
    public void putByteProperty(final SimpleString key, final byte value)
    {
       properties.putByteProperty(key, value);
    }
-   
+
    public void putBytesProperty(final SimpleString key, final byte[] value)
    {
       properties.putBytesProperty(key, value);
    }
-   
+
    public void putShortProperty(final SimpleString key, final short value)
    {
       properties.putShortProperty(key, value);
    }
-   
+
    public void putIntProperty(final SimpleString key, final int value)
    {
       properties.putIntProperty(key, value);
    }
-   
+
    public void putLongProperty(final SimpleString key, final long value)
    {
       properties.putLongProperty(key, value);
    }
-   
+
    public void putFloatProperty(final SimpleString key, final float value)
    {
       properties.putFloatProperty(key, value);
    }
-   
+
    public void putDoubleProperty(final SimpleString key, final double value)
    {
       properties.putDoubleProperty(key, value);
    }
-   
+
    public void putStringProperty(final SimpleString key, final SimpleString value)
    {
       properties.putStringProperty(key, value);
    }
-   
+
    public Object getProperty(final SimpleString key)
    {
       return properties.getProperty(key);
-   }  
-   
+   }
+
    public Object removeProperty(final SimpleString key)
    {
       return properties.removeProperty(key);
    }
-   
+
    public boolean containsProperty(final SimpleString key)
    {
       return properties.containsProperty(key);
    }
-   
+
    public Set<SimpleString> getPropertyNames()
    {
       return properties.getPropertyNames();
    }
-   
+
    // Body
    // -------------------------------------------------------------------------------------
-   
+
    public MessagingBuffer getBody()
    {
       return body;
    }
-   
+
    public void setBody(final MessagingBuffer body)
    {
       this.body = body;
    }
-      
+
    // Public --------------------------------------------------------
-   
+
    // Package protected ---------------------------------------------
 
    // Protected -----------------------------------------------------
 
    // Private -------------------------------------------------------
 
-   // Inner classes -------------------------------------------------  
+   // Inner classes -------------------------------------------------
 }

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/PageMessage.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/PageMessage.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/PageMessage.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -23,6 +23,7 @@
 package org.jboss.messaging.core.paging;
 
 import org.jboss.messaging.core.journal.EncodingSupport;
+import org.jboss.messaging.core.persistence.StorageManager;
 import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.util.TypedProperties;
 
@@ -36,7 +37,7 @@
  */
 public interface PageMessage extends EncodingSupport
 {
-   ServerMessage getMessage();
+   ServerMessage getMessage(StorageManager storageManager);
 
    long getTransactionID();
 

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/PagingManager.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/PagingManager.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/PagingManager.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -140,4 +140,9 @@
     * */
    void clearLastPageRecord(LastPageRecord lastRecord) throws Exception;
 
+   /**
+    * @return
+    */
+   long getDefaultPageSize();
+
 }

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/impl/PageMessageImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/impl/PageMessageImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/impl/PageMessageImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -22,8 +22,13 @@
 
 package org.jboss.messaging.core.paging.impl;
 
+import java.nio.ByteBuffer;
+
 import org.jboss.messaging.core.paging.PageMessage;
+import org.jboss.messaging.core.persistence.StorageManager;
+import org.jboss.messaging.core.remoting.impl.ByteBufferWrapper;
 import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
+import org.jboss.messaging.core.server.ServerLargeMessage;
 import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.core.server.impl.ServerMessageImpl;
 import org.jboss.messaging.util.DataConstants;
@@ -50,7 +55,10 @@
 
    // Public --------------------------------------------------------
 
-   private final ServerMessage message;
+   /** Large messages will need to be instatiated lazily during getMessage when the StorageManager is available */
+   private byte[] largeMessageLazyData;
+   
+   private ServerMessage message;
 
    private long transactionID = -1;
 
@@ -87,8 +95,15 @@
       this.properties = properties;
    }
 
-   public ServerMessage getMessage()
+   public ServerMessage getMessage(StorageManager storage)
    {
+      if (this.largeMessageLazyData != null)
+      {
+         this.message = storage.createLargeMessageStorage();
+         MessagingBuffer buffer = new ByteBufferWrapper(ByteBuffer.wrap(largeMessageLazyData));
+         message.decode(buffer);
+         largeMessageLazyData = null;
+      }
       return message;
    }
 
@@ -107,20 +122,49 @@
    public void decode(final MessagingBuffer buffer)
    {
       transactionID = buffer.getLong();
-      message.decode(buffer);
+      
+      boolean isLargeMessage = buffer.getBoolean();
+      
+      if (isLargeMessage)
+      {
+         int largeMessageHeaderSize = buffer.getInt();
+         
+         this.largeMessageLazyData = new byte[largeMessageHeaderSize];
+         
+         buffer.getBytes(largeMessageLazyData);
+         
+      }
+      else
+      {
+         message = new ServerMessageImpl();
+         message.decode(buffer);
+      }
+      
       properties.decode(buffer);
    }
 
    public void encode(final MessagingBuffer buffer)
    {
       buffer.putLong(transactionID);
-      message.encode(buffer);
+      buffer.putBoolean(message instanceof ServerLargeMessage);
+      if (message instanceof ServerLargeMessage)
+      {
+         buffer.putInt(message.getEncodeSize());
+         message.encode(buffer);
+      }
+      else
+      {
+         message.encode(buffer);
+      }
       properties.encode(buffer);
    }
 
    public int getEncodeSize()
    {
-      return DataConstants.SIZE_LONG  + message.getEncodeSize() + properties.getEncodeSize();
+      return DataConstants.SIZE_LONG + DataConstants.SIZE_BYTE +
+             (message instanceof ServerLargeMessage ? DataConstants.SIZE_INT : 0) +
+             message.getEncodeSize() +
+             properties.getEncodeSize();
    }
 
    // Package protected ---------------------------------------------

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/impl/PagingManagerImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/impl/PagingManagerImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/impl/PagingManagerImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -22,6 +22,15 @@
 
 package org.jboss.messaging.core.paging.impl;
 
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.List;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.paging.LastPageRecord;
 import org.jboss.messaging.core.paging.PageMessage;
@@ -38,15 +47,6 @@
 import org.jboss.messaging.util.SimpleString;
 import org.jboss.messaging.util.TypedProperties;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicLong;
-
 /**
  *  <p>Look at the <a href="http://wiki.jboss.org/wiki/JBossMessaging2Paging">WIKI</a> for more information.</p>
  * 
@@ -59,7 +59,6 @@
 {
 
    // Constants -----------------------------------------------------
-   private static final long WATERMARK_GLOBAL_PAGE = QueueSettings.DEFAULT_PAGE_SIZE_BYTES;
 
    // Attributes ----------------------------------------------------
 
@@ -81,6 +80,8 @@
 
    private final StorageManager storageManager;
 
+   private final long defaultPageSize;
+
    private PostOffice postOffice;
 
    private final ConcurrentMap</*TransactionID*/Long, PageTransactionInfo> transactions = new ConcurrentHashMap<Long, PageTransactionInfo>();
@@ -110,11 +111,13 @@
    public PagingManagerImpl(final PagingStoreFactory pagingSPI,
                             final StorageManager storageManager,
                             final HierarchicalRepository<QueueSettings> queueSettingsRepository,
-                            final long maxGlobalSize)
+                            final long maxGlobalSize,
+                            final long defaultPageSize)
    {
       this.pagingSPI = pagingSPI;
       this.queueSettingsRepository = queueSettingsRepository;
       this.storageManager = storageManager;
+      this.defaultPageSize = defaultPageSize;
       this.maxGlobalSize = maxGlobalSize;
    }
 
@@ -210,6 +213,10 @@
 
       for (PageMessage msg : data)
       {
+         ServerMessage pagedMessage = null;
+
+         pagedMessage = (ServerMessage)msg.getMessage(storageManager);
+
          final long transactionIdDuringPaging = msg.getTransactionID();
          if (transactionIdDuringPaging >= 0)
          {
@@ -222,7 +229,7 @@
             {
                if (isTrace)
                {
-                  trace("Transaction " + msg.getTransactionID() + " not found, ignoring message " + msg.getMessage());
+                  trace("Transaction " + msg.getTransactionID() + " not found, ignoring message " + pagedMessage);
                }
                continue;
             }
@@ -231,40 +238,40 @@
             // before the commit arrived
             if (!pageTransactionInfo.waitCompletion())
             {
-               trace("Rollback was called after prepare, ignoring message " + msg.getMessage());
+               trace("Rollback was called after prepare, ignoring message " + pagedMessage);
                continue;
             }
 
             // / Update information about transactions
-            if (msg.getMessage().isDurable())
+            if (pagedMessage.isDurable())
             {
                pageTransactionInfo.decrement();
                pageTransactionsToUpdate.add(pageTransactionInfo);
             }
          }
-         Long scheduledDeliveryTime = (Long) msg.getProperties().getProperty(SCHEDULED_DELIVERY_PROP);
-         //if this is a scheduled message we add it to the queue as just that
-         if(scheduledDeliveryTime == null)
+         Long scheduledDeliveryTime = (Long)msg.getProperties().getProperty(SCHEDULED_DELIVERY_PROP);
+         // if this is a scheduled message we add it to the queue as just that
+         if (scheduledDeliveryTime == null)
          {
-            refsToAdd.addAll(postOffice.route(msg.getMessage()));
+            refsToAdd.addAll(postOffice.route(pagedMessage));
          }
          else
          {
-            List<MessageReference> refs = postOffice.route(msg.getMessage());
+            List<MessageReference> refs = postOffice.route(pagedMessage);
             for (MessageReference ref : refs)
             {
                ref.setScheduledDeliveryTime(scheduledDeliveryTime);
                if(ref.getQueue().isDurable())
                {
-                  storageManager.storeMessageReferenceScheduledTransactional(depageTransactionID, ref.getQueue().getPersistenceID(), msg.getMessage().getMessageID(), scheduledDeliveryTime);
+                  storageManager.storeMessageReferenceScheduledTransactional(depageTransactionID, ref.getQueue().getPersistenceID(), pagedMessage.getMessageID(), scheduledDeliveryTime);
                }
             }
             scheduledRefsToAdd.addAll(refs);
          }
 
-         if (msg.getMessage().getDurableRefCount() != 0)
+         if (pagedMessage.getDurableRefCount() != 0)
          {
-            storageManager.storeMessageTransactional(depageTransactionID, msg.getMessage());
+            storageManager.storeMessageTransactional(depageTransactionID, pagedMessage);
          }
       }
 
@@ -296,7 +303,8 @@
       }
       if (globalMode.get())
       {
-         return globalSize.get() < maxGlobalSize - WATERMARK_GLOBAL_PAGE && pagingStore.getMaxSizeBytes() <= 0 ||
+         // We use the Default Page Size when in global mode for the calculation of the Watermark
+         return globalSize.get() < maxGlobalSize - defaultPageSize && pagingStore.getMaxSizeBytes() <= 0 ||
                 pagingStore.getAddressSize() < pagingStore.getMaxSizeBytes();
       }
       else
@@ -308,6 +316,11 @@
 
    }
 
+   public long getDefaultPageSize()
+   {
+      return defaultPageSize;
+   }
+
    public void setLastPage(final LastPageRecord lastPage) throws Exception
    {
       trace("LastPage loaded was " + lastPage.getLastId() + " recordID = " + lastPage.getRecordId());
@@ -470,8 +483,22 @@
          {
             // When in Global mode, we use the default page size as the minimal
             // watermark to start depage
-            if (globalMode.get() && currentGlobalSize < maxGlobalSize - QueueSettings.DEFAULT_PAGE_SIZE_BYTES)
+
+            if (isTrace)
             {
+               log.trace("globalMode.get = " + globalMode.get() +
+                         " currentGlobalSize = " +
+                         currentGlobalSize +
+                         " defaultPageSize = " +
+                         defaultPageSize +
+                         " maxGlobalSize = " +
+                         maxGlobalSize +
+                         "maxGlobalSize - defaultPageSize = " +
+                         (maxGlobalSize - defaultPageSize));
+            }
+
+            if (globalMode.get() && currentGlobalSize < maxGlobalSize - defaultPageSize)
+            {
                startGlobalDepage();
             }
             else if (maxSize > 0 && addressSize < maxSize - pageSize)

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/impl/PagingStoreImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/impl/PagingStoreImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/paging/impl/PagingStoreImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -31,6 +31,7 @@
 import java.util.concurrent.locks.ReadWriteLock;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
 
+import org.jboss.messaging.core.config.impl.ConfigurationImpl;
 import org.jboss.messaging.core.journal.SequentialFile;
 import org.jboss.messaging.core.journal.SequentialFileFactory;
 import org.jboss.messaging.core.logging.Logger;
@@ -72,7 +73,7 @@
    private final boolean dropMessagesOnSize;
 
    private boolean droppedMessages;
-
+   
    private final PagingManager pagingManager;
 
    private final Executor executor;
@@ -113,7 +114,18 @@
       this.fileFactory = fileFactory;
       this.storeName = storeName;
       maxSize = queueSettings.getMaxSizeBytes();
-      pageSize = queueSettings.getPageSizeBytes();
+      if (queueSettings.getPageSizeBytes() != null)
+      {
+         this.pageSize = queueSettings.getPageSizeBytes();
+      }
+      else if (pagingManager != null)
+      {
+         this.pageSize = pagingManager.getDefaultPageSize();
+      }
+      else
+      {
+         this.pageSize = ConfigurationImpl.DEFAULT_DEFAULT_PAGE_SIZE;
+      }
       dropMessagesOnSize = queueSettings.isDropMessagesWhenFull();
       this.executor = executor;
       this.pagingManager = pagingManager;

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/StorageManager.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/StorageManager.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/StorageManager.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -30,6 +30,7 @@
 import org.jboss.messaging.core.server.MessagingComponent;
 import org.jboss.messaging.core.server.Queue;
 import org.jboss.messaging.core.server.QueueFactory;
+import org.jboss.messaging.core.server.ServerLargeMessage;
 import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.core.transaction.ResourceManager;
 import org.jboss.messaging.util.SimpleString;
@@ -67,6 +68,9 @@
    void storeMessageReferenceScheduledTransactional(final long txID, final long queueID, final long messageID, final long scheduledDeliveryTime) throws Exception;
 
    void storeDeleteMessageTransactional(long txID, long queueID, long messageID) throws Exception;
+   
+   /** Create an area that will get LargeMessage bytes on the server size*/
+   ServerLargeMessage createLargeMessageStorage();
 
    /** Used to delete non-messaging data (such as PageTransaction and LasPage) */
    void storeDeleteTransactional(long txID, long recordID) throws Exception;

Added: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/impl/journal/JournalServerLargeMessageImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/impl/journal/JournalServerLargeMessageImpl.java	                        (rev 0)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/impl/journal/JournalServerLargeMessageImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -0,0 +1,256 @@
+/*
+ * 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.persistence.impl.journal;
+
+import java.nio.ByteBuffer;
+
+import org.jboss.messaging.core.exception.MessagingException;
+import org.jboss.messaging.core.journal.SequentialFile;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
+import org.jboss.messaging.core.server.ServerLargeMessage;
+import org.jboss.messaging.core.server.impl.ServerMessageImpl;
+
+/**
+ * A ServerLargeMessageImpl
+ *
+ * @author <a href="mailto:clebert.suconic at jboss.org">Clebert Suconic</a>
+ * 
+ * Created 30-Sep-08 12:02:45 PM
+ *
+ *
+ */
+public class JournalServerLargeMessageImpl extends ServerMessageImpl implements ServerLargeMessage
+{
+
+   // Constants -----------------------------------------------------
+
+   private static final Logger log = Logger.getLogger(JournalServerLargeMessageImpl.class);
+   
+   private static boolean isTrace = log.isTraceEnabled();
+
+   // Attributes ----------------------------------------------------
+
+   private final JournalStorageManager storageManager;
+
+   // We should only use the NIO implementation on the Journal
+   private volatile SequentialFile file;
+   
+   private volatile boolean complete = false;
+
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   public JournalServerLargeMessageImpl(JournalStorageManager storageManager)
+   {
+      this.storageManager = storageManager;
+   }
+
+   // Public --------------------------------------------------------
+
+   /* (non-Javadoc)
+    * @see org.jboss.messaging.core.server.ServerLargeMessage#addBytes(byte[])
+    */
+   public synchronized void addBytes(final byte[] bytes) throws Exception
+   {
+      validateFile();
+
+      if (!file.isOpen())
+      {
+         file.open();
+      }
+
+      file.position(file.size());
+
+      file.write(ByteBuffer.wrap(bytes), false);
+
+   }
+
+   @Override
+   public synchronized void encodeBody(final MessagingBuffer bufferOut, final int start, final int size)
+   {
+      validateFile();
+
+      try
+      {
+         // This could maybe be optimized (maybe reading directly into bufferOut)
+         ByteBuffer bufferRead = ByteBuffer.allocate(size);
+         if (!file.isOpen())
+         {
+            file.open();
+         }
+
+         int bytesRead = 0;
+         file.position(start);
+
+         bytesRead = file.read(bufferRead);
+
+         bufferRead.flip();
+
+         if (bytesRead > 0)
+         {
+            bufferOut.putBytes(bufferRead.array(), 0, bytesRead);
+         }
+
+      }
+      catch (Exception e)
+      {
+         throw new RuntimeException(e.getMessage(), e);
+      }
+   }
+
+   @Override
+   public synchronized int getBodySize()
+   {
+      validateFile();
+
+      try
+      {
+         if (!file.isOpen())
+         {
+            file.open();
+         }
+
+         return (int)file.size();
+      }
+
+      catch (Exception e)
+      {
+         throw new RuntimeException("Can't get the file size on " + file.getFileName());
+      }
+   }
+
+   @Override
+   public synchronized int getEncodeSize()
+   {
+      return getPropertiesEncodeSize();
+   }
+
+   @Override
+   public void encode(final MessagingBuffer buffer)
+   {
+      encodeProperties(buffer);
+   }
+
+   @Override
+   public void decode(final MessagingBuffer buffer)
+   {
+      file = null;
+      complete = true;
+      decodeProperties(buffer);
+   }
+
+   @Override
+   public int decrementRefCount()
+   {
+      int currentRefCount = super.decrementRefCount();
+
+      if (currentRefCount == 0)
+      {
+         if (isTrace)
+         {
+            log.trace("Deleting file " + file + " as the usage was complete");
+         }
+
+         try
+         {
+            deleteFile();
+         }
+         catch (Exception e)
+         {
+            log.error(e.getMessage(), e);
+         }
+      }
+
+      return currentRefCount;
+   }
+
+   public void deleteFile() throws MessagingException
+   {
+
+      if (file == null)
+      {
+         new Exception ("ainda nulo?").printStackTrace();
+      }
+      
+      this.storageManager.deleteFile(file);
+   }
+
+   @Override
+   public synchronized int getMemoryEstimate()
+   {
+      // The body won't be on memory (aways on-file), so we don't consider this for paging
+      return super.getPropertiesEncodeSize();
+   }
+   
+   public synchronized void complete() throws Exception
+   {
+      releaseResources();
+      
+      if (!complete)
+      {
+         SequentialFile fileToRename = storageManager.createFileForLargeMessage(this.getMessageID(), true);
+         file.renameTo(fileToRename);         
+      }
+   }
+
+   public synchronized void releaseResources()
+   {
+      if (file.isOpen())
+      {
+         try
+         {
+            file.close();
+         }
+         catch (Exception e)
+         {
+            log.error(e.getMessage(), e);
+         }
+      }
+   }
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   private void validateFile()
+   {
+      if (file == null)
+      {
+         if (this.messageID <= 0)
+         {
+            throw new RuntimeException("MessageID not set on LargeMessage");
+         }
+         
+         file = storageManager.createFileForLargeMessage(this.getMessageID(), complete);
+         
+      }
+   }
+
+
+   // Inner classes -------------------------------------------------
+
+}

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/impl/journal/JournalStorageManager.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/impl/journal/JournalStorageManager.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/impl/journal/JournalStorageManager.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -22,13 +22,34 @@
 
 package org.jboss.messaging.core.persistence.impl.journal;
 
+import static org.jboss.messaging.util.DataConstants.SIZE_BYTE;
+import static org.jboss.messaging.util.DataConstants.SIZE_INT;
+import static org.jboss.messaging.util.DataConstants.SIZE_LONG;
+
+import java.io.File;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicLong;
+
+import javax.transaction.xa.Xid;
+
 import org.jboss.messaging.core.config.Configuration;
+import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.filter.Filter;
 import org.jboss.messaging.core.filter.impl.FilterImpl;
 import org.jboss.messaging.core.journal.EncodingSupport;
 import org.jboss.messaging.core.journal.Journal;
 import org.jboss.messaging.core.journal.PreparedTransactionInfo;
 import org.jboss.messaging.core.journal.RecordInfo;
+import org.jboss.messaging.core.journal.SequentialFile;
 import org.jboss.messaging.core.journal.SequentialFileFactory;
 import org.jboss.messaging.core.journal.impl.AIOSequentialFileFactory;
 import org.jboss.messaging.core.journal.impl.JournalImpl;
@@ -50,12 +71,14 @@
 import org.jboss.messaging.core.server.MessageReference;
 import org.jboss.messaging.core.server.Queue;
 import org.jboss.messaging.core.server.QueueFactory;
+import org.jboss.messaging.core.server.ServerLargeMessage;
 import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.core.server.impl.ServerMessageImpl;
 import org.jboss.messaging.core.transaction.ResourceManager;
 import org.jboss.messaging.core.transaction.Transaction;
 import org.jboss.messaging.core.transaction.impl.TransactionImpl;
 import org.jboss.messaging.util.IDGenerator;
+import org.jboss.messaging.util.JBMThreadFactory;
 import org.jboss.messaging.util.SimpleString;
 import org.jboss.messaging.util.TimeAndCounterIDGenerator;
 
@@ -82,12 +105,6 @@
 {
    private static final Logger log = Logger.getLogger(JournalStorageManager.class);
 
-   private static final int SIZE_LONG = 8;
-
-   private static final int SIZE_INT = 4;
-
-   private static final int SIZE_BYTE = 1;
-
    // Bindings journal record type
 
    public static final byte BINDING_RECORD = 21;
@@ -99,6 +116,8 @@
 
    // Message journal record types
 
+   public static final byte ADD_LARGE_MESSAGE = 30;
+
    public static final byte ADD_MESSAGE = 31;
 
    public static final byte ACKNOWLEDGE_REF = 32;
@@ -111,7 +130,7 @@
 
    public static final byte SET_SCHEDULED_DELIVERY_TIME = 44;
 
-   //This will produce a unique id **for this node only**
+   // This will produce a unique id **for this node only**
    private final IDGenerator idGenerator = new TimeAndCounterIDGenerator();
 
    private final AtomicLong bindingIDSequence = new AtomicLong(0);
@@ -120,12 +139,19 @@
 
    private final Journal bindingsJournal;
 
+   private final SequentialFileFactory largeMessagesFactory;
+
    private final ConcurrentMap<SimpleString, Long> destinationIDMap = new ConcurrentHashMap<SimpleString, Long>();
 
    private volatile boolean started;
-
+   
+   private final ExecutorService executor;
+   
+   
    public JournalStorageManager(final Configuration config)
    {
+      this.executor = Executors.newCachedThreadPool(new JBMThreadFactory("JBM-journal-storage-manager"));
+      
       if (config.getJournalType() != JournalType.NIO && config.getJournalType() != JournalType.ASYNCIO)
       {
          throw new IllegalArgumentException("Only NIO and AsyncIO are supported journals");
@@ -190,13 +216,19 @@
                                        "jbm",
                                        config.getJournalMaxAIO(),
                                        config.getJournalBufferReuseSize());
+
+      largeMessagesFactory = new NIOSequentialFileFactory(config.getLargeMessagesDirectory());
    }
 
    /* This constructor is only used for testing */
-   public JournalStorageManager(final Journal messageJournal, final Journal bindingsJournal)
+   public JournalStorageManager(final Journal messageJournal,
+                                final Journal bindingsJournal,
+                                final SequentialFileFactory largeMessagesFactory)
    {
+      this.executor = Executors.newCachedThreadPool(new JBMThreadFactory("JBM-journal-storage-manager"));
       this.messageJournal = messageJournal;
       this.bindingsJournal = bindingsJournal;
+      this.largeMessagesFactory = largeMessagesFactory;
    }
 
    public long generateUniqueID()
@@ -204,11 +236,31 @@
       return idGenerator.generateID();
    }
 
+   /** Create an area that will get LargeMessage bytes on the server size*/
+   public ServerLargeMessage createLargeMessageStorage()
+   {
+      return new JournalServerLargeMessageImpl(this);
+   }
+
    // Non transactional operations
 
    public void storeMessage(final ServerMessage message) throws Exception
    {
-      messageJournal.appendAddRecord(message.getMessageID(), ADD_MESSAGE, message);
+      if (message.getMessageID() <= 0)
+      {
+         throw new MessagingException(MessagingException.ILLEGAL_STATE, "MessageId was not assigned to Message");
+      }
+
+      if (message instanceof ServerLargeMessage)
+      {
+         messageJournal.appendAddRecord(message.getMessageID(),
+                                        ADD_LARGE_MESSAGE,
+                                        new LargeMessageEncoding((ServerLargeMessage)message));
+      }
+      else
+      {
+         messageJournal.appendAddRecord(message.getMessageID(), ADD_MESSAGE, message);
+      }
    }
 
    public void storeAcknowledge(final long queueID, final long messageID) throws Exception
@@ -231,7 +283,23 @@
 
    public void storeMessageTransactional(final long txID, final ServerMessage message) throws Exception
    {
-      messageJournal.appendAddRecordTransactional(txID, message.getMessageID(), ADD_MESSAGE, message);
+      if (message.getMessageID() <= 0)
+      {
+         throw new MessagingException(MessagingException.ILLEGAL_STATE, "MessageId was not assigned to Message");
+      }
+
+      if (message instanceof ServerLargeMessage)
+      {
+         messageJournal.appendAddRecordTransactional(txID,
+                                                     message.getMessageID(),
+                                                     ADD_LARGE_MESSAGE,
+                                                     new LargeMessageEncoding(((ServerLargeMessage)message)));
+      }
+      else
+      {
+         messageJournal.appendAddRecordTransactional(txID, message.getMessageID(), ADD_MESSAGE, message);
+      }
+
    }
 
    public void storePageTransaction(final long txID, final PageTransactionInfo pageTransaction) throws Exception
@@ -332,6 +400,23 @@
 
          switch (recordType)
          {
+            case ADD_LARGE_MESSAGE:
+            {
+               ServerLargeMessage largeMessage = this.createLargeMessageStorage();
+
+               LargeMessageEncoding messageEncoding = new LargeMessageEncoding(largeMessage);
+
+               messageEncoding.decode(buff);
+
+               List<MessageReference> refs = postOffice.route(largeMessage);
+
+               for (MessageReference ref : refs)
+               {
+                  ref.getQueue().addLast(ref);
+               }
+
+               break;
+            }
             case ADD_MESSAGE:
             {
                ServerMessage message = new ServerMessageImpl(record.id);
@@ -617,11 +702,15 @@
       {
          return;
       }
+      
+      executor.shutdown();
 
       bindingsJournal.stop();
 
       messageJournal.stop();
 
+      executor.awaitTermination(60, TimeUnit.SECONDS);
+
       started = false;
    }
 
@@ -630,8 +719,7 @@
       return started;
    }
 
-   // Public
-   // -----------------------------------------------------------------------------------
+   // Public -----------------------------------------------------------------------------------
 
    public Journal getMessageJournal()
    {
@@ -643,9 +731,46 @@
       return bindingsJournal;
    }
 
-   // Private
-   // ----------------------------------------------------------------------------------
+   // Package protected ---------------------------------------------
+   
+   // This should be accessed from this package only
+   void deleteFile(final SequentialFile file)
+   {
+      this.executor.execute(new Runnable() {
 
+         public void run()
+         {
+            try
+            {
+               file.delete();
+            }
+            catch (Exception e)
+            {
+               log.warn(e.getMessage(), e);
+            }
+         }
+         
+      });
+   }
+
+   /**
+    * @param messageID
+    * @return
+    */
+   SequentialFile createFileForLargeMessage(final long messageID, final boolean completeFile)
+   {
+      if (completeFile)
+      {
+         return largeMessagesFactory.createSequentialFile(messageID + ".msg", -1);
+      }
+      else
+      {
+         return largeMessagesFactory.createSequentialFile(messageID + ".tmp", -1);
+      }
+   }
+
+   // Private ----------------------------------------------------------------------------------
+
    private void loadPreparedTransactions(final PostOffice postOffice,
                                          final Map<Long, Queue> queues,
                                          final ResourceManager resourceManager,
@@ -901,7 +1026,7 @@
       public int getEncodeSize()
       {
          return SimpleString.sizeofString(queueName) + SimpleString.sizeofString(address) + 1 + // HasFilter?
-                ((filter != null) ? SimpleString.sizeofString(filter) : 0);
+                (filter != null ? SimpleString.sizeofString(filter) : 0);
       }
    }
 
@@ -935,6 +1060,42 @@
 
    }
 
+   private static class LargeMessageEncoding implements EncodingSupport
+   {
+
+      private final ServerLargeMessage message;
+
+      public LargeMessageEncoding(ServerLargeMessage message)
+      {
+         this.message = message;
+      }
+
+      /* (non-Javadoc)
+       * @see org.jboss.messaging.core.journal.EncodingSupport#decode(org.jboss.messaging.core.remoting.spi.MessagingBuffer)
+       */
+      public void decode(final MessagingBuffer buffer)
+      {
+         message.decode(buffer);
+      }
+
+      /* (non-Javadoc)
+       * @see org.jboss.messaging.core.journal.EncodingSupport#encode(org.jboss.messaging.core.remoting.spi.MessagingBuffer)
+       */
+      public void encode(final MessagingBuffer buffer)
+      {
+         message.encode(buffer);
+      }
+
+      /* (non-Javadoc)
+       * @see org.jboss.messaging.core.journal.EncodingSupport#getEncodeSize()
+       */
+      public int getEncodeSize()
+      {
+         return message.getEncodeSize();
+      }
+
+   }
+
    private static class DeliveryCountUpdateEncoding implements EncodingSupport
    {
       long queueID;
@@ -1027,8 +1188,10 @@
          super(queueID);
       }
    }
+   
    private static class ScheduledDeliveryEncoding extends QueueEncoding
    {
+
       long scheduledDeliveryTime;
 
       private ScheduledDeliveryEncoding(long scheduledDeliveryTime, long queueID)
@@ -1059,4 +1222,5 @@
          scheduledDeliveryTime = buffer.getLong();
       }
    }
+
 }

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/impl/nullpm/NullStorageManager.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/impl/nullpm/NullStorageManager.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/impl/nullpm/NullStorageManager.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -31,6 +31,7 @@
 import org.jboss.messaging.core.server.MessageReference;
 import org.jboss.messaging.core.server.Queue;
 import org.jboss.messaging.core.server.QueueFactory;
+import org.jboss.messaging.core.server.ServerLargeMessage;
 import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.core.transaction.ResourceManager;
 import org.jboss.messaging.util.IDGenerator;
@@ -146,7 +147,16 @@
    public void updateDeliveryCount(MessageReference ref) throws Exception
 	{
 	}
+   
+   /* (non-Javadoc)
+    * @see org.jboss.messaging.core.persistence.StorageManager#createLargeMessageStorage(long, int, int)
+    */
+   public ServerLargeMessage createLargeMessageStorage()
+   {
+      return new NullStorageServerLargeMessageImpl();
+   }
 
+
 	public long generateUniqueID()
 	{
 	   //FIXME - this needs to use Howard's ID generator from JBM 1.4

Added: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/impl/nullpm/NullStorageServerLargeMessageImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/impl/nullpm/NullStorageServerLargeMessageImpl.java	                        (rev 0)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/persistence/impl/nullpm/NullStorageServerLargeMessageImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -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.persistence.impl.nullpm;
+
+import java.nio.ByteBuffer;
+
+import org.jboss.messaging.core.remoting.impl.ByteBufferWrapper;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
+import org.jboss.messaging.core.server.ServerLargeMessage;
+import org.jboss.messaging.core.server.impl.ServerMessageImpl;
+
+/**
+ * A NullStorageServerLargeMessageImpl
+ *
+ * @author <a href="mailto:clebert.suconic at jboss.org">Clebert Suconic</a>
+ * 
+ * Created 30-Sep-08 1:51:42 PM
+ *
+ *
+ */
+public class NullStorageServerLargeMessageImpl extends ServerMessageImpl implements ServerLargeMessage
+{
+
+   // Constants -----------------------------------------------------
+
+   // Attributes ----------------------------------------------------
+
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   // Public --------------------------------------------------------
+
+   public NullStorageServerLargeMessageImpl()
+   {
+      super();
+   }
+
+   /* (non-Javadoc)
+    * @see org.jboss.messaging.core.server.ServerLargeMessage#release()
+    */
+   public void releaseResources()
+   {
+   }
+
+   /* (non-Javadoc)
+    * @see org.jboss.messaging.core.server.ServerLargeMessage#addBytes(byte[])
+    */
+   public synchronized void addBytes(final byte[] bytes)
+   {
+      MessagingBuffer buffer = this.getBody();
+      
+      if (buffer != null)
+      {
+         ByteBuffer newBuffer = ByteBuffer.allocate(buffer.limit() + bytes.length);
+         newBuffer.put(buffer.array());
+         buffer = new ByteBufferWrapper(newBuffer);
+         this.setBody(buffer);
+      }
+      else
+      {
+         buffer = new ByteBufferWrapper(ByteBuffer.allocate(bytes.length));
+         this.setBody(buffer);
+      }
+      
+      buffer.putBytes(bytes);
+   }
+
+   /* (non-Javadoc)
+    * @see org.jboss.messaging.core.server.ServerLargeMessage#deleteFile()
+    */
+   public void deleteFile() throws Exception
+   {
+      // nothing to be done here.. we don really have a file on this Storage
+   }
+
+   /* (non-Javadoc)
+    * @see org.jboss.messaging.core.server.ServerLargeMessage#complete()
+    */
+   public void complete() throws Exception
+   {
+      // nothing to be done here.. we don really have a file on this Storage
+      
+   }
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   // Inner classes -------------------------------------------------
+
+}

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/Packet.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/Packet.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/Packet.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -45,6 +45,8 @@
       
    void decode(MessagingBuffer buffer);
    
+   int getPacketSize();
+   
    boolean isRequiresConfirmations();
    
    boolean isWriteAlways();

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/RemotingConnectionImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/RemotingConnectionImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/RemotingConnectionImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -26,6 +26,7 @@
 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_BINDINGQUERY_RESP;
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.SESS_CHUNK_SEND;
 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;
@@ -127,6 +128,7 @@
 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.SessionScheduledSendMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendChunkMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendManagementMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXACommitMessage;
@@ -720,8 +722,7 @@
 
    private void doWrite(final Packet packet)
    {
-      final MessagingBuffer buffer = transportConnection.createBuffer(PacketImpl.INITIAL_BUFFER_SIZE);
-
+      final MessagingBuffer buffer = transportConnection.createBuffer(packet.getPacketSize());
       packet.encode(buffer);
 
       transportConnection.write(buffer);
@@ -1000,6 +1001,11 @@
             packet = new SessionSendManagementMessage();
             break;
          }
+         case SESS_CHUNK_SEND:
+         {
+            packet = new SessionSendChunkMessage();
+            break;
+         }
          case SESS_REPLICATE_DELIVERY:
          {
             packet = new SessionReplicateDeliveryMessage();

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/invm/InVMConnector.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/invm/InVMConnector.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/invm/InVMConnector.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -94,13 +94,12 @@
 
    public Connection createConnection()
    {
-      Connection conn = new InVMConnection(acceptor.getHandler(), new Listener());
+      Connection conn = internalCreateConnection(acceptor.getHandler(), new Listener());
       
       acceptor.connect((String)conn.getID(), handler, this);
            
       return conn;
    }
-
    public synchronized void start()
    {          
       started = true;
@@ -125,7 +124,16 @@
          conn.close();
       }
    }
+
+
+   // This may be an injection point for mocks on tests
+   protected Connection internalCreateConnection(final BufferHandler handler, final ConnectionLifeCycleListener listener)
+   {
+      return new InVMConnection(handler, listener);
+   }
+
    
+   
    private class Listener implements ConnectionLifeCycleListener
    {
       public void connectionCreated(final Connection connection)

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/CreateSessionMessage.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/CreateSessionMessage.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/CreateSessionMessage.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -46,6 +46,8 @@
    
    private String password;
    
+   private int bigMessageSize;
+   
    private boolean xa;
    
    private boolean autoCommitSends;
@@ -58,6 +60,7 @@
 
    public CreateSessionMessage(final String name, final long sessionChannelID,
                                final int version, final String username, final String password,
+                               final int bigMessageSize, 
                                final boolean xa, final boolean autoCommitSends,
                                final boolean autoCommitAcks)
    {
@@ -73,6 +76,8 @@
       
       this.password = password;
       
+      this.bigMessageSize = bigMessageSize;
+      
       this.xa = xa;
       
       this.autoCommitSends = autoCommitSends;
@@ -134,6 +139,7 @@
       buffer.putInt(version);
       buffer.putNullableString(username);
       buffer.putNullableString(password);
+      buffer.putInt(bigMessageSize);
       buffer.putBoolean(xa);
       buffer.putBoolean(autoCommitSends);
       buffer.putBoolean(autoCommitAcks);
@@ -146,6 +152,7 @@
       version = buffer.getInt();
       username = buffer.getNullableString();
       password = buffer.getNullableString();
+      bigMessageSize = buffer.getInt();
       xa = buffer.getBoolean();
       autoCommitSends = buffer.getBoolean();
       autoCommitAcks = buffer.getBoolean();
@@ -178,6 +185,14 @@
       return false;
    }
 
+   /**
+    * @return
+    */
+   public int getBigMessageSize()
+   {
+      return bigMessageSize;
+   }
+   
    // Package protected ---------------------------------------------
 
    // Protected -----------------------------------------------------

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/PacketImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/PacketImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/PacketImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -28,7 +28,9 @@
 
    private static final Logger log = Logger.getLogger(PacketImpl.class);
 
-   public static final int INITIAL_BUFFER_SIZE = 1024;
+   public static final int DEFAULT_PACKET_SIZE = 1024;
+   
+   protected static final int BASIC_PACKET_SIZE = DataConstants.SIZE_INT + DataConstants.SIZE_BYTE + DataConstants.SIZE_LONG;
 
    private long channelID;
 
@@ -151,6 +153,8 @@
 
    public static final byte SESS_REPLICATE_DELIVERY = 91;
 
+   public static final byte SESS_CHUNK_SEND = 95;
+
    // Static --------------------------------------------------------
 
    public PacketImpl(final byte type)
@@ -160,6 +164,12 @@
 
    // Public --------------------------------------------------------
 
+   
+   public int getPacketSize()
+   {
+      return DEFAULT_PACKET_SIZE;
+   }
+   
    public byte getType()
    {
       return type;

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionReceiveMessage.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionReceiveMessage.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionReceiveMessage.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -27,6 +27,7 @@
 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.util.DataConstants;
 
 /**
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
@@ -95,6 +96,12 @@
       return deliveryCount;
    }
 
+   
+   public int getPacketSize()
+   {
+      return BASIC_PACKET_SIZE + DataConstants.SIZE_LONG + DataConstants.SIZE_INT + serverMessage.getEncodeSize();
+   }
+   
    public void encodeBody(final MessagingBuffer buffer)
    {
       buffer.putLong(consumerID);

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionScheduledSendMessage.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionScheduledSendMessage.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionScheduledSendMessage.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -23,6 +23,7 @@
 
 import org.jboss.messaging.core.client.ClientMessage;
 import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
+import org.jboss.messaging.util.DataConstants;
 
 /**
  * @author <a href="mailto:andy.taylor at jboss.org">Andy Taylor</a>
@@ -48,6 +49,13 @@
       buffer.putLong(scheduledDeliveryTime);
    }
 
+   @Override
+   public int getPacketSize()
+   {
+      return super.getPacketSize() + DataConstants.LONG;
+   }
+
+
    public void decodeBody(final MessagingBuffer buffer)
    {
       super.decodeBody(buffer);
@@ -58,4 +66,6 @@
    {
       return scheduledDeliveryTime;
    }
+   
+   
 }

Added: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionSendChunkMessage.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionSendChunkMessage.java	                        (rev 0)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionSendChunkMessage.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -0,0 +1,239 @@
+/*
+ * 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;
+import org.jboss.messaging.util.DataConstants;
+
+/**
+ * @author <a href="mailto:clebert.suconic at jboss.com">Clebert Suconic</a>
+ * 
+ * @version <tt>$Revision$</tt>
+ */
+public class SessionSendChunkMessage extends PacketImpl
+{
+   // Constants -----------------------------------------------------
+
+   // Attributes ----------------------------------------------------
+
+   private long targetID;
+
+   private byte[] header;
+
+   private byte[] body;
+
+   private boolean continues;
+
+   private long messageID = 0;
+
+   private boolean requiresResponse;
+
+   private long scheduledDeliveryTime;
+
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   public SessionSendChunkMessage(final long targetID,
+                                  final byte[] header,
+                                  final byte[] body,
+                                  final boolean continues,
+                                  final boolean requiresResponse,
+                                  final long scheduledDelivery)
+   {
+      super(SESS_CHUNK_SEND);
+      this.targetID = targetID;
+      this.header = header;
+      this.body = body;
+      this.continues = continues;
+      this.requiresResponse = requiresResponse;
+      this.scheduledDeliveryTime = scheduledDelivery;
+   }
+
+   public SessionSendChunkMessage(final long targetID,
+                                  final byte[] header,
+                                  final byte[] body,
+                                  final boolean continues,
+                                  final boolean requiresResponse)
+   {
+      super(SESS_CHUNK_SEND);
+      this.targetID = targetID;
+      this.header = header;
+      this.body = body;
+      this.continues = continues;
+      this.requiresResponse = requiresResponse;
+      this.scheduledDeliveryTime = 0;
+   }
+
+   public SessionSendChunkMessage()
+   {
+      super(SESS_CHUNK_SEND);
+   }
+
+   // Public --------------------------------------------------------
+
+   public long getTargetID()
+   {
+      return targetID;
+   }
+
+   public boolean isRequiresResponse()
+   {
+      return requiresResponse;
+   }
+
+   public byte[] getHeader()
+   {
+      return header;
+   }
+
+   public byte[] getBody()
+   {
+      return body;
+   }
+
+   public long getMessageID()
+   {
+      return messageID;
+   }
+
+   public void setMessageID(final long messageId)
+   {
+      messageID = messageId;
+   }
+
+   /**
+    * @return the scheduledDeliveryTime
+    */
+   public long getScheduledDeliveryTime()
+   {
+      return scheduledDeliveryTime;
+   }
+
+   public boolean isContinues()
+   {
+      return continues;
+   }
+
+   @Override
+   public int getPacketSize()
+   {
+      return DEFAULT_PACKET_SIZE + DataConstants.SIZE_LONG /* TargetID */+
+             DataConstants.SIZE_INT /* HeaderLength */+
+             (header != null ? header.length : 0) /* Header bytes */+
+             DataConstants.SIZE_INT /* BodyLength */+
+             body.length /* Body bytes */+
+             DataConstants.SIZE_BOOLEAN /* hasContinuations */+
+             DataConstants.SIZE_BOOLEAN /* requiresResponse */+
+             DataConstants.SIZE_BOOLEAN /* has MessageId */+
+             (messageID > 0 ? DataConstants.SIZE_LONG : 0) +
+             DataConstants.SIZE_BOOLEAN /* has scheduled delivery time */+
+             (scheduledDeliveryTime > 0 ? DataConstants.SIZE_LONG : 0);
+   }
+
+   @Override
+   public void encodeBody(final MessagingBuffer buffer)
+   {
+      buffer.putLong(targetID);
+
+      if (header != null)
+      {
+         buffer.putInt(header.length);
+         buffer.putBytes(header);
+      }
+      else
+      {
+         buffer.putInt(0);
+      }
+
+      buffer.putInt(body.length);
+      buffer.putBytes(body);
+
+      buffer.putBoolean(continues);
+
+      buffer.putBoolean(requiresResponse);
+
+      buffer.putBoolean(messageID > 0);
+
+      if (messageID > 0)
+      {
+         buffer.putLong(messageID);
+      }
+      
+      buffer.putBoolean(scheduledDeliveryTime > 0);
+      
+      if (scheduledDeliveryTime > 0)
+      {
+         buffer.putLong(scheduledDeliveryTime);
+      }
+   }
+
+   @Override
+   public void decodeBody(final MessagingBuffer buffer)
+   {
+      targetID = buffer.getLong();
+
+      final int headerLength = buffer.getInt();
+
+      if (headerLength > 0)
+      {
+         header = new byte[headerLength];
+         buffer.getBytes(header);
+      }
+      else
+      {
+         header = null;
+      }
+
+      final int bodyLength = buffer.getInt();
+
+      body = new byte[bodyLength];
+      buffer.getBytes(body);
+
+      continues = buffer.getBoolean();
+
+      requiresResponse = buffer.getBoolean();
+
+      final boolean hasMessageID = buffer.getBoolean();
+
+      if (hasMessageID)
+      {
+         messageID = buffer.getLong();
+      }
+      
+      final boolean hasScheduledDelivery = buffer.getBoolean();
+      
+      if (hasScheduledDelivery)
+      {
+         scheduledDeliveryTime = buffer.getLong();
+      }
+   }
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   // Inner classes -------------------------------------------------
+}

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionSendMessage.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionSendMessage.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/remoting/impl/wireformat/SessionSendMessage.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -18,15 +18,17 @@
  * 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.message.Message;
 import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
 import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.core.server.impl.ServerMessageImpl;
+import org.jboss.messaging.util.DataConstants;
 
 /**
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
@@ -39,15 +41,13 @@
    // Constants -----------------------------------------------------
 
    private static final Logger log = Logger.getLogger(SessionSendMessage.class);
-   
+
    // Attributes ----------------------------------------------------
 
    private long producerID;
-   
-   private ClientMessage clientMessage;
-   
-   private ServerMessage serverMessage;
-   
+
+   private Message message;
+
    private boolean requiresResponse;
 
    // Static --------------------------------------------------------
@@ -59,29 +59,32 @@
       super(SESS_SEND);
 
       this.producerID = producerID;
-      
-      this.clientMessage = message;
-      
+
+      this.message = message;
+
       this.requiresResponse = requiresResponse;
    }
-      
+
    public SessionSendMessage()
    {
       super(SESS_SEND);
    }
 
-   protected SessionSendMessage(final byte type, final long producerID, final ClientMessage message, final boolean requiresResponse)
+   protected SessionSendMessage(final byte type,
+                                final long producerID,
+                                final ClientMessage message,
+                                final boolean requiresResponse)
    {
       super(type);
 
       this.producerID = producerID;
 
-      this.clientMessage = message;
+      this.message = message;
 
       this.requiresResponse = requiresResponse;
    }
 
-   protected SessionSendMessage(byte type)
+   protected SessionSendMessage(final byte type)
    {
       super(type);
    }
@@ -92,55 +95,54 @@
    {
       return producerID;
    }
-   
+
    public ClientMessage getClientMessage()
    {
-      return clientMessage;
+      return (ClientMessage)message;
    }
-   
+
    public ServerMessage getServerMessage()
    {
-      return serverMessage;
+      return (ServerMessage)message;
    }
-   
+
    public boolean isRequiresResponse()
    {
       return requiresResponse;
    }
-   
+
+   @Override
+   public int getPacketSize()
+   {
+      return BASIC_PACKET_SIZE + DataConstants.SIZE_LONG + message.getEncodeSize() + DataConstants.BOOLEAN;
+   }
+
+   @Override
    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.putLong(producerID);
+
+      message.encode(buffer);
+
       buffer.putBoolean(requiresResponse);
    }
-   
+
+   @Override
    public void decodeBody(final MessagingBuffer buffer)
    {
-      //TODO can be optimised
-      
+      // TODO can be optimised
+
       producerID = buffer.getLong();
-                  
-      serverMessage = new ServerMessageImpl();
-      
-      serverMessage.decode(buffer);
-      
-      serverMessage.getBody().flip();
-      
+
+      message = new ServerMessageImpl();
+
+      message.decode(buffer);
+
+      message.getBody().flip();
+
       requiresResponse = buffer.getBoolean();
    }
 
-
    // Package protected ---------------------------------------------
 
    // Protected -----------------------------------------------------

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/MessagingServer.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/MessagingServer.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/MessagingServer.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -69,6 +69,7 @@
                                               String password,
                                               int incrementingVersion,
                                               RemotingConnection remotingConnection,
+                                              int bigMessageSize,
                                               boolean autoCommitSends,
                                               boolean autoCommitAcks,
                                               boolean xa) throws Exception;

Added: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/ServerLargeMessage.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/ServerLargeMessage.java	                        (rev 0)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/ServerLargeMessage.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -0,0 +1,45 @@
+/*
+ * 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;
+
+/**
+ * A LargeMessage
+ *
+ * @author <a href="mailto:clebert.suconic at jboss.org">Clebert Suconic</a>
+ * 
+ * Created 30-Sep-08 10:58:04 AM
+ *
+ *
+ */
+public interface ServerLargeMessage extends ServerMessage
+{
+   void addBytes(byte[] bytes) throws Exception;
+
+   /** Close the files if opened */
+   void releaseResources();
+   
+   void complete() throws Exception;
+   
+   void deleteFile() throws Exception;
+
+}

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/ServerMessage.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/ServerMessage.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/ServerMessage.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -41,12 +41,12 @@
 
    int decrementDurableRefCount();
    
-   int incrementReference(boolean durable);
-   
    int getDurableRefCount();
    
    int decrementRefCount();
    
+   int incrementDurableRefCount();
+   
    int getRefCount();
    
    ServerMessage copy();

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/ServerProducer.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/ServerProducer.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/ServerProducer.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -18,11 +18,10 @@
  * 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;
 
-
 /**
  * 
  * A ServerProducer
@@ -39,6 +38,12 @@
 	
 	void send(ServerMessage msg) throws Exception;
 
+   /** Current LargeMessage being sent in chunks */
+   ServerLargeMessage getCurrentChunk();
+   
+   /** Current LargeMessage being sent in chunks */
+   void setCurrentChunk(ServerLargeMessage message);
+
    void sendScheduled(ServerMessage message, long scheduledDeliveryTime) throws Exception;
 	
 	void sendCredits(int credits) throws Exception;

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/ServerSession.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/ServerSession.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/ServerSession.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -39,6 +39,7 @@
 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.SessionScheduledSendMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendChunkMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendManagementMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXACommitMessage;
@@ -66,6 +67,8 @@
    String getUsername();
 
    String getPassword();
+   
+   int getBigMessageSize();
 
    void removeConsumer(ServerConsumer consumer) throws Exception;
 
@@ -135,6 +138,8 @@
 
    void handleReceiveConsumerCredits(SessionConsumerFlowCreditMessage packet);
 
+   public void handleSendChunkMessage(SessionSendChunkMessage packet);
+
    void handleSendProducerMessage(SessionSendMessage packet);
 
    void handleSendScheduledProducerMessage(SessionScheduledSendMessage packet);
@@ -151,5 +156,4 @@
 
    //Should this really be here??
    void sendResponse(final DelayedResult result, final Packet response);
-
 }

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/MessagingServerImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/MessagingServerImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/MessagingServerImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -211,7 +211,8 @@
       pagingManager = new PagingManagerImpl(storeFactory,
                                             storageManager,
                                             queueSettingsRepository,
-                                            configuration.getPagingMaxGlobalSizeBytes());
+                                            configuration.getPagingMaxGlobalSizeBytes(),
+                                            configuration.getPagingDefaultSize());
 
       storeFactory.setPagingManager(pagingManager);
 
@@ -431,6 +432,7 @@
                                                      final String password,
                                                      final int incrementingVersion,
                                                      final RemotingConnection connection,
+                                                     final int bigMessageSize,
                                                      final boolean autoCommitSends,
                                                      final boolean autoCommitAcks,
                                                      final boolean xa) throws Exception
@@ -462,6 +464,7 @@
                                                               channelID,
                                                               username,
                                                               password,
+                                                              bigMessageSize,
                                                               autoCommitSends,
                                                               autoCommitAcks,
                                                               xa,

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/MessagingServerPacketHandler.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/MessagingServerPacketHandler.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/MessagingServerPacketHandler.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -79,6 +79,7 @@
                                                request.getPassword(),
                                                request.getVersion(),
                                                connection,
+                                               request.getBigMessageSize(),
                                                request.isAutoCommitSends(),
                                                request.isAutoCommitAcks(),
                                                request.isXA());

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/MessagingServiceImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/MessagingServiceImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/MessagingServiceImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -24,6 +24,7 @@
 import org.jboss.messaging.core.config.Configuration;
 import org.jboss.messaging.core.config.impl.ConfigurationImpl;
 import org.jboss.messaging.core.journal.Journal;
+import org.jboss.messaging.core.journal.SequentialFileFactory;
 import org.jboss.messaging.core.journal.impl.JournalImpl;
 import org.jboss.messaging.core.journal.impl.NIOSequentialFileFactory;
 import org.jboss.messaging.core.management.ManagementService;
@@ -78,7 +79,7 @@
       return new MessagingServiceImpl(server, storageManager, remotingService);
    }
 
-   public static MessagingServiceImpl newNioStorageMessagingServer(final Configuration config, String journalDir, String bindingsDir)
+   public static MessagingServiceImpl newNioStorageMessagingServer(final Configuration config, String journalDir, String bindingsDir, String largeMessagesDir)
    {
       NIOSequentialFileFactory sequentialFileFactory = new NIOSequentialFileFactory(journalDir);
       NIOSequentialFileFactory sequentialFileFactory2 = new NIOSequentialFileFactory(bindingsDir);
@@ -92,8 +93,10 @@
 	   		config.getJournalMinFiles(), config.isJournalSyncTransactional(),
 	   		config.isJournalSyncNonTransactional(), sequentialFileFactory,
 	   		"jbm-bindings", "jbm", config.getJournalMaxAIO(), 0);
+      
+      SequentialFileFactory largeMessagesFactory = new NIOSequentialFileFactory(largeMessagesDir);
 
-      StorageManager storageManager = new JournalStorageManager(msgs, bindings);
+      StorageManager storageManager = new JournalStorageManager(msgs, bindings, largeMessagesFactory);
 
       RemotingService remotingService = new RemotingServiceImpl(config);
 

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -30,6 +30,7 @@
 import org.jboss.messaging.core.list.PriorityLinkedList;
 import org.jboss.messaging.core.list.impl.PriorityLinkedListImpl;
 import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.paging.PagingManager;
 import org.jboss.messaging.core.persistence.StorageManager;
 import org.jboss.messaging.core.postoffice.Binding;
 import org.jboss.messaging.core.postoffice.FlowController;
@@ -99,6 +100,8 @@
    private AtomicBoolean waitingToDeliver = new AtomicBoolean(false);
 
    private final Runnable deliverRunner = new DeliverRunner();
+   
+   private final PagingManager pagingManager;
 
    private volatile boolean backup;
 
@@ -128,6 +131,15 @@
       this.scheduledExecutor = scheduledExecutor;
 
       this.postOffice = postOffice;
+      
+      if (postOffice == null)
+      {
+         this.pagingManager = null;
+      }
+      else
+      {
+         this.pagingManager = postOffice.getPagingManager();
+      }
 
       direct = true;
    }
@@ -262,6 +274,15 @@
             iterator.remove();
 
             removed = ref;
+            
+            try
+            {
+               referenceRemoved(removed);
+            }
+            catch (Exception e)
+            {
+               log.warn(e.getMessage(), e);
+            }
 
             break;
          }
@@ -329,10 +350,8 @@
 
    public void referenceAcknowledged(MessageReference ref) throws Exception
    {
-      deliveringCount.decrementAndGet();
+      referenceRemoved(ref);
 
-      sizeBytes.addAndGet(-ref.getMessage().getEncodeSize());
-
       // if (flowController != null)
       // {
       // flowController.messageAcknowledged();
@@ -794,6 +813,24 @@
       return status;
    }
 
+   /**
+    * To be called when a reference is removed from the queue.
+    * @param ref
+    * @throws Exception
+    */
+   private void referenceRemoved(MessageReference ref) throws Exception
+   {
+      deliveringCount.decrementAndGet();
+
+      sizeBytes.addAndGet(-ref.getMessage().getEncodeSize());
+      
+      
+      if (ref.getMessage().decrementRefCount() == 0)
+      {
+         pagingManager.messageDone(ref.getMessage());
+      }
+   }
+
    // Inner classes
    // --------------------------------------------------------------------------
 

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerConsumerImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerConsumerImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerConsumerImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -22,6 +22,7 @@
 
 package org.jboss.messaging.core.server.impl;
 
+import java.nio.ByteBuffer;
 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.concurrent.ConcurrentLinkedQueue;
@@ -35,16 +36,20 @@
 import org.jboss.messaging.core.persistence.StorageManager;
 import org.jboss.messaging.core.postoffice.PostOffice;
 import org.jboss.messaging.core.remoting.Channel;
+import org.jboss.messaging.core.remoting.impl.ByteBufferWrapper;
 import org.jboss.messaging.core.remoting.DelayedResult;
 import org.jboss.messaging.core.remoting.Packet;
 import org.jboss.messaging.core.remoting.impl.wireformat.MessagingExceptionMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.NullResponseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionReceiveMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendChunkMessage;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionReplicateDeliveryMessage;
 import org.jboss.messaging.core.server.HandleStatus;
 import org.jboss.messaging.core.server.MessageReference;
 import org.jboss.messaging.core.server.Queue;
 import org.jboss.messaging.core.server.ServerConsumer;
+import org.jboss.messaging.core.server.ServerLargeMessage;
 import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.core.server.ServerSession;
 import org.jboss.messaging.core.settings.HierarchicalRepository;
@@ -55,7 +60,8 @@
  *
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
  * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
- *
+ * @author <a href="mailto:clebert.suconic at jboss.com">Clebert Suconic</a>
+ * 
  * @version <tt>$Revision: 3783 $</tt> $Id: ServerConsumerImpl.java 3783 2008-02-25 12:15:14Z timfox $
  */
 public class ServerConsumerImpl implements ServerConsumer
@@ -79,6 +85,8 @@
 
    private final Filter filter;
 
+   private final int bigMessageSize;
+   
    private final ServerSession session;
 
    private final Lock lock = new ReentrantLock();
@@ -148,6 +156,8 @@
       this.channel = channel;
 
       messageQueue.addConsumer(this);
+      
+      this.bigMessageSize = session.getBigMessageSize();
    }
 
    // ServerConsumer implementation
@@ -200,28 +210,53 @@
 
          final SessionReceiveMessage packet = new SessionReceiveMessage(id, message, ref.getDeliveryCount() + 1);
 
-         DelayedResult result = channel.replicatePacket(new SessionReplicateDeliveryMessage(id, message.getMessageID()));
-
          if (!browseOnly)
          {
             deliveringRefs.add(ref);
          }
 
-         if (result == null)
+         DelayedResult result = channel.replicatePacket(new SessionReplicateDeliveryMessage(id, message.getMessageID()));
+         
+
+         if (message instanceof ServerLargeMessage)
          {
-            // Not replicated - just send now
-            channel.send(packet);
+            if (result == null)
+            {
+               // Not replicated - just send now
+               sendChunks((ServerLargeMessage)message);
+            }
+            else
+            {
+               // Send when replicate delivery response comes back
+               result.setResultRunner(new Runnable()
+               {
+                  public void run()
+                  {
+                     sendChunks((ServerLargeMessage)message);
+                  }
+               });
+               
+            }
          }
          else
          {
-            // Send when replicate delivery response comes back
-            result.setResultRunner(new Runnable()
+   
+            if (result == null)
             {
-               public void run()
+               // Not replicated - just send now
+               channel.send(packet);
+            }
+            else
+            {
+               // Send when replicate delivery response comes back
+               result.setResultRunner(new Runnable()
                {
-                  channel.send(packet);
-               }
-            });
+                  public void run()
+                  {
+                     channel.send(packet);
+                  }
+               });
+            }
          }
 
          return HandleStatus.HANDLED;
@@ -231,7 +266,7 @@
          lock.unlock();
       }
    }
-   
+
    public void handleClose(final Packet packet)
    {
       DelayedResult result = null;
@@ -415,6 +450,48 @@
    // Private
    // --------------------------------------------------------------------------------------
 
+   /**
+    * @param message
+    * @throws MessagingException
+    */
+   private void sendChunks(ServerLargeMessage message)
+   {
+      int headerSize = message.getPropertiesEncodeSize();
+
+      final int bodySize = message.getBodySize();
+      
+      int bodyLength = bigMessageSize - headerSize;
+
+      MessagingBuffer headerBuffer = new ByteBufferWrapper(ByteBuffer.allocate(message.getPropertiesEncodeSize()));
+      message.encodeProperties(headerBuffer);
+      
+      MessagingBuffer bodyBuffer = new ByteBufferWrapper(ByteBuffer.allocate(bodyLength));
+      message.encodeBody(bodyBuffer, 0, bodyLength);
+
+      SessionSendChunkMessage chunk = new SessionSendChunkMessage(id,
+                                                                  headerBuffer.array(),
+                                                                  bodyBuffer.array(),
+                                                                  bodyLength < bodySize,
+                                                                  false);
+      channel.send(chunk);
+
+      for (int pos = bodyLength; pos < bodySize;)
+      {
+         bodyLength = Math.min(bodySize - pos, bigMessageSize);
+         bodyBuffer = new ByteBufferWrapper(ByteBuffer.allocate(bodyLength));
+
+         message.encodeBody(bodyBuffer, pos, bodyLength);
+
+         chunk = new SessionSendChunkMessage(id, null, bodyBuffer.array(), pos + bodyLength < bodySize, false);
+
+         channel.send(chunk);
+
+         pos += bodyLength;
+      }
+      
+      message.releaseResources();
+   }
+   
    private void doClose() throws Exception
    {
       messageQueue.removeConsumer(this);

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerMessageImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerMessageImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerMessageImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -108,16 +108,11 @@
       return durableRefCount.decrementAndGet();
    }
 
-   public int incrementReference(final boolean durable)
+   public int incrementDurableRefCount()
    {
-      if (durable)
-      {
-         durableRefCount.incrementAndGet();
-      }
-
-      return refCount.incrementAndGet();
+      return durableRefCount.incrementAndGet();
    }
-
+   
    public int decrementRefCount()
    {
       return refCount.decrementAndGet();

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerProducerImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerProducerImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerProducerImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -18,7 +18,7 @@
  * License along with this software; if not, write to the Free
  * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
  * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */ 
+ */
 
 package org.jboss.messaging.core.server.impl;
 
@@ -29,6 +29,7 @@
 import org.jboss.messaging.core.remoting.Channel;
 import org.jboss.messaging.core.remoting.Packet;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionProducerFlowCreditMessage;
+import org.jboss.messaging.core.server.ServerLargeMessage;
 import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.core.server.ServerProducer;
 import org.jboss.messaging.core.server.ServerSession;
@@ -39,110 +40,139 @@
  * A ServerProducerImpl
  * 
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * @author <a href="mailto:clebert.suconic at jboss.com">Clebert Suconic</a>
  * @author <a href="mailto:andy.taylor at jboss.org>Andy Taylor</a>
  *
  */
 public class ServerProducerImpl implements ServerProducer
 {
-	private static final Logger log = Logger.getLogger(ServerProducerImpl.class);
-	
-	private final long id;
-	
-	private final ServerSession session;
-	
-	private final SimpleString address;
-	
-	private final FlowController flowController;
-	
-	private final int windowSize;
-	
-	private volatile boolean waiting;
-	
-   private AtomicInteger creditsToSend = new AtomicInteger(0);
-   
+
+   // Static -----------------------------------------------------------------------
+   private static final Logger log = Logger.getLogger(ServerProducerImpl.class);
+
+   // Attributes--------------------------------------------------------------------
+
+   private final long id;
+
+   private final ServerSession session;
+
+   private final SimpleString address;
+
+   private final FlowController flowController;
+
+   private final int windowSize;
+
+   private volatile boolean waiting;
+
+   private final AtomicInteger creditsToSend = new AtomicInteger(0);
+
    private final Channel channel;
-     	
-	// Constructors ----------------------------------------------------------------
-	
-	public ServerProducerImpl(final long id, final ServerSession session,
-	                          final SimpleString address, 
-			                    final FlowController flowController,
-			                    final int windowSize,			                    
-			                    final Channel channel) throws Exception
-	{	
-	   this.id = id;
-	   
-		this.session = session;
-		
-		this.address = address;
-		
-		this.flowController = flowController;		
-		
-		this.windowSize = windowSize;
-		
-		this.channel = channel;
-	}
-	
-	// ServerProducer implementation --------------------------------------------
-	
-	public long getID()
-	{
-		return id;
-	}
-	
-	public void close() throws Exception
-	{	   
-		session.removeProducer(this);
-	}
-	
-	public void send(final ServerMessage message) throws Exception
-	{
+
+   private ServerLargeMessage currentLargeMessage;
+
+   // Constructors ----------------------------------------------------------------
+
+   public ServerProducerImpl(final long id,
+                             final ServerSession session,
+                             final SimpleString address,
+                             final FlowController flowController,
+                             final int windowSize,
+                             final Channel channel) throws Exception
+   {
+      this.id = id;
+
+      this.session = session;
+
+      this.address = address;
+
+      this.flowController = flowController;
+
+      this.windowSize = windowSize;
+
+      this.channel = channel;
+   }
+
+   // ServerProducer implementation --------------------------------------------
+
+   public long getID()
+   {
+      return id;
+   }
+
+   public void close() throws Exception
+   {
+      if (currentLargeMessage != null)
+      {
+         try
+         {
+            currentLargeMessage.deleteFile();
+         }
+         catch (Throwable error)
+         {
+            log.warn(error.toString(), error);
+
+         }
+      }
+
+      session.removeProducer(this);
+   }
+
+   public void send(final ServerMessage message) throws Exception
+   {
       doFlowControl(message);
 
-      session.send(message);  		
-	}
-	
-	public void sendScheduled(final ServerMessage message, final long scheduledDeliveryTime) throws Exception
+      session.send(message);
+   }
+
+   public void sendScheduled(final ServerMessage message, final long scheduledDeliveryTime) throws Exception
    {
       doFlowControl(message);
 
       session.sendScheduled(message, scheduledDeliveryTime);
    }
-	
+
+   public ServerLargeMessage getCurrentChunk()
+   {
+      return currentLargeMessage;
+   }
+
+   public void setCurrentChunk(final ServerLargeMessage message)
+   {
+      currentLargeMessage = message;
+   }
+
    public void requestAndSendCredits() throws Exception
-	{	 
-	   if (!waiting)
-	   {
-	      flowController.requestAndSendCredits(this, creditsToSend.get());
-	   }
-	}
+   {
+      if (!waiting)
+      {
+         flowController.requestAndSendCredits(this, creditsToSend.get());
+      }
+   }
 
-	public void sendCredits(final int credits) throws Exception
-	{
-	   creditsToSend.addAndGet(-credits);
-	   
-//		Packet packet = new SessionProducerFlowCreditMessage(id, credits);
-//		
-//		channel.send(packet);	
-	}
-	
-	public void setWaiting(final boolean waiting)
-	{
-		this.waiting = waiting;
-	}
-	
-	public boolean isWaiting()
-	{
-		return waiting;
-	}
+   public void sendCredits(final int credits) throws Exception
+   {
+      creditsToSend.addAndGet(-credits);
 
+      // Packet packet = new SessionProducerFlowCreditMessage(id, credits);
+      //		
+      // channel.send(packet);
+   }
 
+   public void setWaiting(final boolean waiting)
+   {
+      this.waiting = waiting;
+   }
 
+   public boolean isWaiting()
+   {
+      return waiting;
+   }
+
    private void doFlowControl(final ServerMessage message) throws Exception
    {
       if (this.address != null)
       {
-         //Only do flow control with non anonymous producers
+         // Only do flow control with non anonymous producers
 
          if (flowController != null)
          {

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -66,6 +66,7 @@
 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.SessionScheduledSendMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendChunkMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendManagementMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXACommitMessage;
@@ -81,12 +82,14 @@
 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.spi.MessagingBuffer;
 import org.jboss.messaging.core.security.CheckType;
 import org.jboss.messaging.core.security.SecurityStore;
 import org.jboss.messaging.core.server.MessageReference;
 import org.jboss.messaging.core.server.MessagingServer;
 import org.jboss.messaging.core.server.Queue;
 import org.jboss.messaging.core.server.ServerConsumer;
+import org.jboss.messaging.core.server.ServerLargeMessage;
 import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.core.server.ServerProducer;
 import org.jboss.messaging.core.server.ServerSession;
@@ -119,13 +122,13 @@
 
    // Attributes ----------------------------------------------------------------------------
 
-   private final boolean trace = log.isTraceEnabled();
-
    private final long id;
 
    private final String username;
 
    private final String password;
+   
+   private final int bigMessageSize;
 
    private final boolean autoCommitSends;
 
@@ -175,6 +178,7 @@
                             final long id,
                             final String username,
                             final String password,
+                            final int bigMessageSize,
                             final boolean autoCommitSends,
                             final boolean autoCommitAcks,
                             final boolean xa,
@@ -195,6 +199,8 @@
       this.username = username;
 
       this.password = password;
+      
+      this.bigMessageSize = bigMessageSize;
 
       this.autoCommitSends = autoCommitSends;
 
@@ -243,6 +249,11 @@
    {
       return password;
    }
+   
+   public int getBigMessageSize()
+   {
+      return bigMessageSize;
+   }
 
    public long getID()
    {
@@ -1725,7 +1736,79 @@
 
       sendResponse(result, response);
    }
+   
 
+   public void handleSendChunkMessage(final SessionSendChunkMessage packet)
+   {
+
+      if (packet.getMessageID() == 0)
+      {
+         packet.setMessageID(storageManager.generateUniqueID());
+      }
+
+      Packet response = null;
+
+      DelayedResult result = channel.replicatePacket(packet);
+      
+      try
+      {
+         ServerLargeMessage largeMessage = null;
+         
+         if (packet.getHeader() != null)
+         {
+            largeMessage = createLargeMessageStorage(packet.getTargetID(), packet.getMessageID(), packet.getHeader());
+         }
+         else
+         {
+            largeMessage = getCurrentLargeMessage(packet.getTargetID());
+         }
+         
+
+         largeMessage.addBytes(packet.getBody());
+         
+         
+         if (!packet.isContinues())
+         {
+            largeMessage.complete();
+            clearCurrentLargeMessage(packet.getTargetID());
+            if (packet.getScheduledDeliveryTime() > 0)
+            {
+               producers.get(packet.getTargetID()).sendScheduled(largeMessage, packet.getScheduledDeliveryTime());
+            }
+            else
+            {
+               producers.get(packet.getTargetID()).send(largeMessage);
+            }
+         }
+
+         if (packet.isRequiresResponse())
+         {
+            response = new NullResponseMessage();
+         }
+         
+      }
+      catch (Exception e)
+      {
+         log.error("Failed to send message", e);
+
+         if (packet.isRequiresResponse())
+         {
+            if (e instanceof MessagingException)
+            {
+               response = new MessagingExceptionMessage((MessagingException)e);
+            }
+            else
+            {
+               response = new MessagingExceptionMessage(new MessagingException(MessagingException.INTERNAL_ERROR));
+            }
+         }
+      }
+
+      sendResponse(result, response);
+
+   }
+   
+
    public void handleSendScheduledProducerMessage(final SessionScheduledSendMessage packet)
    {
       ServerMessage msg = packet.getServerMessage();
@@ -1939,6 +2022,39 @@
    // Private
    // ----------------------------------------------------------------------------
 
+   private ServerLargeMessage createLargeMessageStorage(long producerID, long messageID, byte[] header) throws Exception
+   {
+      ServerLargeMessage largeMessage = storageManager.createLargeMessageStorage();
+      
+      MessagingBuffer headerBuffer = new ByteBufferWrapper(ByteBuffer.wrap(header));
+      
+      largeMessage.decodeProperties(headerBuffer);
+
+      // client didn send the ID originally
+      largeMessage.setMessageID(messageID);
+      
+      ServerProducer producer = producers.get(producerID);
+       
+      producer.setCurrentChunk(largeMessage);
+      
+      return largeMessage;
+   }
+
+   private ServerLargeMessage getCurrentLargeMessage(long producerID)
+   {
+      ServerProducer producer = producers.get(producerID);
+      
+      return producer.getCurrentChunk();
+   }
+
+   private void clearCurrentLargeMessage(long producerID)
+   {
+      ServerProducer producer = producers.get(producerID);
+      
+      producer.setCurrentChunk(null);      
+   }
+
+
    private void doRollback(final Transaction theTx) throws Exception
    {
       boolean wasStarted = started;
@@ -2019,11 +2135,6 @@
 
       Queue queue = ref.getQueue();
 
-      if (message.decrementRefCount() == 0)
-      {
-         pager.messageDone(message);
-      }
-
       if (message.isDurable() && queue.isDurable())
       {
          int count = message.decrementDurableRefCount();

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerSessionPacketHandler.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerSessionPacketHandler.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/server/impl/ServerSessionPacketHandler.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -16,6 +16,7 @@
 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_CHUNK_SEND;
 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;
@@ -64,6 +65,7 @@
 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.SessionSendChunkMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionReplicateDeliveryMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionScheduledSendMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionSendManagementMessage;
@@ -77,6 +79,8 @@
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXARollbackMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXASetTimeoutMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAStartMessage;
+import org.jboss.messaging.core.server.ServerLargeMessage;
+import org.jboss.messaging.core.server.ServerMessage;
 import org.jboss.messaging.core.server.ServerSession;
 
 /**
@@ -293,6 +297,12 @@
                session.handleSendProducerMessage(message);
                break;
             }
+            case SESS_CHUNK_SEND:
+            {
+               SessionSendChunkMessage message = (SessionSendChunkMessage)packet;
+               session.handleSendChunkMessage(message);
+               break;
+            }
             case SESS_SCHEDULED_SEND:
             {
                SessionScheduledSendMessage message = (SessionScheduledSendMessage)packet;

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/settings/impl/QueueSettings.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/settings/impl/QueueSettings.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/settings/impl/QueueSettings.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -49,8 +49,6 @@
 
    public static final Boolean DEFAULT_DROP_MESSAGES_WHEN_FULL = Boolean.FALSE;
 
-   public static final Integer DEFAULT_PAGE_SIZE_BYTES = 10 * 1024 * 1024; // 10M Bytes
-
    public static final Integer DEFAULT_MAX_DELIVERY_ATTEMPTS = 10;
 
    public static final Integer DEFAULT_MESSAGE_COUNTER_HISTORY_DAY_LIMIT = 0;
@@ -97,7 +95,7 @@
 
    public Integer getPageSizeBytes()
    {
-      return pageSizeBytes != null ? pageSizeBytes : DEFAULT_PAGE_SIZE_BYTES;
+      return pageSizeBytes;
    }
 
    public Boolean isDropMessagesWhenFull()

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/transaction/impl/TransactionImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/transaction/impl/TransactionImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/core/transaction/impl/TransactionImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -196,11 +196,6 @@
 
       ServerMessage message = acknowledgement.getMessage();
 
-      if (message.decrementRefCount() == 0 && pagingManager != null)
-      {
-         pagingManager.messageDone(message);
-      }
-      
       if (message.isDurable())
       {
          Queue queue = acknowledgement.getQueue();
@@ -354,19 +349,15 @@
       
       for (MessageReference ref : acknowledgements)
       {
-//         Queue queue = ref.getQueue();
-//
-//         ServerMessage message = ref.getMessage();
+         Queue queue = ref.getQueue();
 
-         // Putting back the size on pagingManager, and reverting the counters
-         
-         //FIXME - why????
-         //Surely paging happens before routing, so cancellation shouldn't effect anything......
-//         if (message.incrementReference(message.isDurable() && queue.isDurable()) == 1)
-//         {
-//            pagingManager.addSize(message);
-//         }
+         ServerMessage message = ref.getMessage();
 
+         if (message.isDurable() && queue.isDurable())
+         {
+            message.incrementDurableRefCount();
+         }
+
          toCancel.add(ref);         
       }
       

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/client/JBossConnectionFactory.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/client/JBossConnectionFactory.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/client/JBossConnectionFactory.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -68,6 +68,8 @@
    private final int producerWindowSize;
 
    private final int producerMaxRate;
+   
+   private final int bigMessageSize;
 
    private final boolean blockOnAcknowledge;
 
@@ -89,6 +91,7 @@
                                  final int consumerMaxRate,
                                  final int producerWindowSize,
                                  final int producerMaxRate,
+                                 final int bigMessageSize,
                                  final boolean blockOnAcknowledge,
                                  final boolean blockOnNonPersistentSend,
                                  final boolean blockOnPersistentSend,
@@ -105,6 +108,7 @@
       this.producerMaxRate = producerMaxRate;
       this.producerWindowSize = producerWindowSize;
       this.blockOnAcknowledge = blockOnAcknowledge;
+      this.bigMessageSize = bigMessageSize;
       this.blockOnNonPersistentSend = blockOnNonPersistentSend;
       this.blockOnPersistentSend = blockOnPersistentSend;
       this.autoGroupId = autoGroupId;
@@ -279,6 +283,7 @@
                                                        consumerMaxRate,
                                                        producerWindowSize,
                                                        producerMaxRate,
+                                                       bigMessageSize,
                                                        blockOnAcknowledge,
                                                        blockOnNonPersistentSend,
                                                        blockOnPersistentSend,

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/JMSServerManager.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/JMSServerManager.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/JMSServerManager.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -110,6 +110,7 @@
             long pingPeriod, long callTimeout, String clientID,
          int dupsOKBatchSize, int consumerWindowSize, int consumerMaxRate,
          int producerWindowSize, int producerMaxRate,
+         int bigMessageSize, 
          boolean blockOnAcknowledge,
          boolean blockOnNonPersistentSend,
          boolean blockOnPersistentSend, boolean autoGroupId, String jndiBinding)
@@ -121,6 +122,7 @@
             long pingPeriod, long callTimeout, String clientID,
          int dupsOKBatchSize, int consumerWindowSize, int consumerMaxRate,
          int producerWindowSize, int producerMaxRate,
+         int bigMessageSize, 
          boolean blockOnAcknowledge,
          boolean blockOnNonPersistentSend,
          boolean blockOnPersistentSend, boolean autoGroupId,  List<String> jndiBinding)

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/impl/JMSServerDeployer.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/impl/JMSServerDeployer.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/impl/JMSServerDeployer.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -55,7 +55,9 @@
    private static final String PRODUCER_WINDOW_SIZE_ELEMENT = "producer-window-size";
 
    private static final String PRODUCER_MAX_RATE_ELEMENT = "producer-max-rate";
-
+   
+   private static final String BIG_MESSAGE_ELEMENT = "big-message-size";
+   
    private static final String BLOCK_ON_ACKNOWLEDGE_ELEMENT = "block-on-acknowledge";
 
    private static final String SEND_NP_MESSAGES_SYNCHRONOUSLY_ELEMENT = "send-np-messages-synchronously";
@@ -135,6 +137,7 @@
          int consumerMaxRate = ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE;
          int producerWindowSize = ClientSessionFactoryImpl.DEFAULT_PRODUCER_WINDOW_SIZE;
          int producerMaxRate = ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE;
+         int bigMessageSize = ClientSessionFactoryImpl.DEFAULT_BIG_MESSAGE_SIZE;
          boolean blockOnAcknowledge = ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE;
          boolean blockOnNonPersistentSend = ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND;
          boolean blockOnPersistentSend = ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_PERSISTENT_SEND;
@@ -171,6 +174,10 @@
             {
                producerMaxRate = Integer.parseInt(children.item(j).getTextContent().trim());
             }
+            else if (BIG_MESSAGE_ELEMENT.equalsIgnoreCase(children.item(j).getNodeName()))
+            {
+               bigMessageSize  = Integer.parseInt(children.item(j).getTextContent().trim());
+            }
             else if (CLIENTID_ELEMENT.equalsIgnoreCase(children.item(j).getNodeName()))
             {
                clientID = children.item(j).getTextContent().trim();
@@ -395,6 +402,7 @@
                                                   consumerMaxRate,
                                                   producerWindowSize,
                                                   producerMaxRate,
+                                                  bigMessageSize,
                                                   blockOnAcknowledge,
                                                   blockOnNonPersistentSend,
                                                   blockOnPersistentSend,

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/impl/JMSServerManagerImpl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/impl/JMSServerManagerImpl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/impl/JMSServerManagerImpl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -22,6 +22,7 @@
 
 package org.jboss.messaging.jms.server.impl;
 
+import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.management.MessagingServerControlMBean;
@@ -196,46 +197,33 @@
                                           int consumerMaxRate,
                                           int producerWindowSize,
                                           int producerMaxRate,
+                                          int bigMessageSize,
                                           boolean blockOnAcknowledge,
                                           boolean blockOnNonPersistentSend,
                                           boolean blockOnPersistentSend,
                                           boolean autoGroupId,
                                           String jndiBinding) throws Exception
    {
-      JBossConnectionFactory cf = connectionFactories.get(name);
-      if (cf == null)
-      {
-         cf = new JBossConnectionFactory(connectorConfig,
-                                         backupConnectorConfig,
-                                         pingPeriod,
-                                         callTimeout,
-                                         clientID,
-                                         dupsOKBatchSize,
-                                         consumerWindowSize,
-                                         consumerMaxRate,
-                                         producerWindowSize,
-                                         producerMaxRate,
-                                         blockOnAcknowledge,
-                                         blockOnNonPersistentSend,
-                                         blockOnPersistentSend,
-                                         autoGroupId);
-         connectionFactories.put(name, cf);
-      }
-      if (!bindToJndi(jndiBinding, cf))
-      {
-         return false;
-      }
-      if (connectionFactoryBindings.get(name) == null)
-      {
-         connectionFactoryBindings.put(name, new ArrayList<String>());
-      }
-      connectionFactoryBindings.get(name).add(jndiBinding);
-
-      List<String> bindings = new ArrayList<String>();
+      ArrayList<String> bindings = new ArrayList<String>(1);
       bindings.add(jndiBinding);
-
-      managementService.registerConnectionFactory(name, cf, bindings);
-      return true;
+      
+      return createConnectionFactory(name,
+                                     connectorConfig,
+                                     backupConnectorConfig,
+                                     pingPeriod,
+                                     callTimeout,
+                                     clientID,
+                                     dupsOKBatchSize,
+                                     consumerWindowSize,
+                                     consumerMaxRate,
+                                     producerWindowSize,
+                                     producerMaxRate,
+                                     bigMessageSize,
+                                     blockOnAcknowledge,
+                                     blockOnNonPersistentSend,
+                                     blockOnPersistentSend,
+                                     autoGroupId,
+                                     bindings);
    }
 
    public boolean createConnectionFactory(String name,
@@ -249,6 +237,7 @@
                                           int consumerMaxRate,
                                           int producerWindowSize,
                                           int producerMaxRate,
+                                          int bigMessageSize,
                                           boolean blockOnAcknowledge,
                                           boolean blockOnNonPersistentSend,
                                           boolean blockOnPersistentSend,
@@ -268,6 +257,7 @@
                                          consumerMaxRate,
                                          producerWindowSize,
                                          producerMaxRate,
+                                         bigMessageSize == -1 ? ClientSessionFactoryImpl.DEFAULT_BIG_MESSAGE_SIZE : bigMessageSize,
                                          blockOnAcknowledge,
                                          blockOnNonPersistentSend,
                                          blockOnPersistentSend,

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/management/JMSServerControlMBean.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/management/JMSServerControlMBean.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/management/JMSServerControlMBean.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -79,6 +79,7 @@
          @Parameter(name = "consumerMaxRate", desc = "Consumer's max rate") int consumerMaxRate,
          @Parameter(name = "producerWindowSize", desc = "Producer's window size") int producerWindowSize,
          @Parameter(name = "producerMaxRate", desc = "Producer's max rate") int producerMaxRate,
+         @Parameter(name = "bigMessageSize", desc = "Size of what is considered a big message requiring sending in chunks") int bigMessageSize, 
          @Parameter(name = "blockOnAcknowledge", desc = "Does acknowlegment block?") boolean blockOnAcknowledge,
          @Parameter(name = "blockOnNonPersistentSend", desc = "Does sending non persistent messages block?") boolean blockOnNonPersistentSend,
          @Parameter(name = "blockOnPersistentSend", desc = "Does sending persistent messages block") boolean blockOnPersistentSend,

Modified: branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/management/impl/JMSServerControl.java
===================================================================
--- branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/management/impl/JMSServerControl.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/src/main/org/jboss/messaging/jms/server/management/impl/JMSServerControl.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -71,6 +71,7 @@
             long pingPeriod, long callTimeout, String clientID,
          int dupsOKBatchSize, int consumerWindowSize, int consumerMaxRate,
          int producerWindowSize, int producerMaxRate,
+         int bigMessageSize, 
          boolean blockOnAcknowledge,
          boolean blockOnNonPersistentSend,
          boolean blockOnPersistentSend, boolean autoGroupId, String jndiBinding) throws Exception
@@ -81,7 +82,8 @@
       boolean created = server.createConnectionFactory(name, connectorConfig,
                backupConnectorConfig,
                   pingPeriod, callTimeout, clientID, dupsOKBatchSize, 
-               consumerWindowSize, consumerMaxRate, producerWindowSize, producerMaxRate, 
+               consumerWindowSize, consumerMaxRate, producerWindowSize, producerMaxRate,
+               bigMessageSize, 
                blockOnAcknowledge, blockOnNonPersistentSend, 
                blockOnPersistentSend, autoGroupId, jndiBinding);
       if (created)

Modified: branches/Branch_Chunk_CRS2/tests/jms-tests/src/org/jboss/test/messaging/jms/CTSMiscellaneousTest.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/jms-tests/src/org/jboss/test/messaging/jms/CTSMiscellaneousTest.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/jms-tests/src/org/jboss/test/messaging/jms/CTSMiscellaneousTest.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -72,7 +72,7 @@
          getJmsServerManager().createConnectionFactory("StrictTCKConnectionFactory",
                   new TransportConfiguration("org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory"), null, 5000, 5000,                  
                   null,
-               1000, 1024 * 1024, -1, 1000, -1, true, true, true, false, "/StrictTCKConnectionFactory");
+               1000, 1024 * 1024, -1, 1000, -1, -1, true, true, true, false, "/StrictTCKConnectionFactory");
                  
          cf = (JBossConnectionFactory) getInitialContext().lookup("/StrictTCKConnectionFactory");
 		}

Modified: branches/Branch_Chunk_CRS2/tests/jms-tests/src/org/jboss/test/messaging/jms/JMSTest.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/jms-tests/src/org/jboss/test/messaging/jms/JMSTest.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/jms-tests/src/org/jboss/test/messaging/jms/JMSTest.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -95,6 +95,8 @@
 	      conn.start();
 
 	      TextMessage rm = (TextMessage)cons.receive();
+	      
+	      assertNotNull(rm);
 
 	      assertEquals("message one", rm.getText());
       }

Modified: branches/Branch_Chunk_CRS2/tests/jms-tests/src/org/jboss/test/messaging/jms/JMSTestCase.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/jms-tests/src/org/jboss/test/messaging/jms/JMSTestCase.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/jms-tests/src/org/jboss/test/messaging/jms/JMSTestCase.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -39,7 +39,7 @@
       
       getJmsServerManager().createConnectionFactory("testsuitecf",
                new TransportConfiguration("org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory"), null, 5000, 5000,      
-               null, 1000, 1024 * 1024, -1, 1000, -1, true, true, true, false, "/testsuitecf");
+               null, 1000, 1024 * 1024, -1, 1000, -1, -1, true, true, true, false, "/testsuitecf");
       
       cf = (JBossConnectionFactory) getInitialContext().lookup("/testsuitecf");      
    }

Modified: branches/Branch_Chunk_CRS2/tests/jms-tests/src/org/jboss/test/messaging/tools/container/LocalTestServer.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/jms-tests/src/org/jboss/test/messaging/tools/container/LocalTestServer.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/jms-tests/src/org/jboss/test/messaging/tools/container/LocalTestServer.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -529,7 +529,7 @@
       getJMSServerManager().createConnectionFactory(objectName,
                new TransportConfiguration("org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory"), null, 5000, 5000,      
                clientId, dupsOkBatchSize,
-      		prefetchSize, -1, 1000, -1, blockOnAcknowledge, true, true, false, jndiBindings);
+      		prefetchSize, -1, 1000, -1, -1, blockOnAcknowledge, true, true, false, jndiBindings);
    }
 
 

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/base/IntegrationTestBase.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/base/IntegrationTestBase.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/base/IntegrationTestBase.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -1,183 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
- * by the @authors tag. See the copyright.txt in the distribution for a
- * full listing of individual contributors.
- *
- * This is free software; you can redistribute it and/or modify it
- * under the terms of the GNU Lesser General Public License as
- * published by the Free Software Foundation; either version 2.1 of
- * the License, or (at your option) any later version.
- *
- * This software is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public
- * License along with this software; if not, write to the Free
- * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
- * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
- */
-
-
-package org.jboss.messaging.tests.integration.base;
-
-import java.io.File;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.jboss.messaging.core.client.ClientMessage;
-import org.jboss.messaging.core.client.ClientSession;
-import org.jboss.messaging.core.client.ClientSessionFactory;
-import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
-import org.jboss.messaging.core.config.Configuration;
-import org.jboss.messaging.core.config.TransportConfiguration;
-import org.jboss.messaging.core.config.impl.ConfigurationImpl;
-import org.jboss.messaging.core.remoting.impl.invm.InVMAcceptorFactory;
-import org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory;
-import org.jboss.messaging.core.remoting.impl.netty.NettyAcceptorFactory;
-import org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory;
-import org.jboss.messaging.core.server.MessagingService;
-import org.jboss.messaging.core.server.impl.MessagingServiceImpl;
-import org.jboss.messaging.core.settings.impl.QueueSettings;
-import org.jboss.messaging.jms.client.JBossBytesMessage;
-import org.jboss.messaging.jms.client.JBossTextMessage;
-import org.jboss.messaging.tests.util.UnitTestCase;
-
-/**
- * 
- * Base class with basic utilities on starting up a basic server
- * 
- * @author <a href="mailto:clebert.suconic at jboss.com">Clebert Suconic</a>
- *
- */
-public class IntegrationTestBase extends UnitTestCase
-{
-   
-   // Constants -----------------------------------------------------
-   
-   // Attributes ----------------------------------------------------
-   
-   protected static final String INVM_ACCEPTOR_FACTORY = InVMAcceptorFactory.class.getCanonicalName();
-   protected static final String INVM_CONNECTOR_FACTORY = InVMConnectorFactory.class.getCanonicalName();
-   
-   protected static final String NETTY_ACCEPTOR_FACTORY = NettyAcceptorFactory.class.getCanonicalName();
-   protected static final String NETTY_CONNECTOR_FACTORY = NettyConnectorFactory.class.getCanonicalName();
-   
-   protected String journalDir = System.getProperty("java.io.tmpdir", "/tmp") + "/integration-test/journal";
-   protected String bindingsDir = System.getProperty("java.io.tmpdir", "/tmp") + "/integration-test/bindings";
-   protected String pageDir = System.getProperty("java.io.tmpdir", "/tmp") + "/integration-test/page";
-   protected MessagingService messagingService;
-
-   
-   // Static --------------------------------------------------------
-   
-   // Constructors --------------------------------------------------
-   
-   // Public --------------------------------------------------------
-   
-   // Package protected ---------------------------------------------
-   
-   // Protected -----------------------------------------------------
-   
-   protected void clearData()
-   {
-      File file = new File(journalDir);
-      File file2 = new File(bindingsDir);
-      File file3 = new File(pageDir);
-      deleteDirectory(file);
-      file.mkdirs();
-      deleteDirectory(file2);
-      file2.mkdirs();
-      deleteDirectory(file3);
-      file3.mkdirs();
-   }
-
-
-   protected MessagingService createService(boolean realFiles, boolean netty, Configuration configuration, Map<String, QueueSettings> settings)
-   {
-      TransportConfiguration transportConfig = new TransportConfiguration(INVM_ACCEPTOR_FACTORY);
-      configuration.getAcceptorConfigurations().add(transportConfig);
-      
-      if (netty)
-      {
-         configuration.getAcceptorConfigurations().add(new TransportConfiguration(NETTY_ACCEPTOR_FACTORY));
-      }
-      
-      MessagingService service;
-      
-      if (realFiles)
-      {
-         service = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir);
-      }
-      else
-      {
-         service = MessagingServiceImpl.newNullStorageMessagingServer(configuration);
-      }
-         
-      
-      for (Map.Entry<String, QueueSettings> setting: settings.entrySet())
-      {
-         service.getServer().getQueueSettingsRepository().addMatch(setting.getKey(), setting.getValue());
-      }
-   
-      
-      return service;
-   }
-
-   protected MessagingService createService(boolean realFiles)
-   {
-      return createService(realFiles, false, createDefaultConfig(), new HashMap<String, QueueSettings>());
-   }
-
-
-   protected Configuration createDefaultConfig()
-   {
-      Configuration configuration = new ConfigurationImpl();
-      configuration.setSecurityEnabled(false);
-      configuration.setJournalMinFiles(2);
-      configuration.setPagingDirectory(pageDir);
-      
-      return configuration;
-   }
-
-
-   protected ClientSessionFactory createInVMFactory()
-   {
-      return new ClientSessionFactoryImpl(new TransportConfiguration(INVM_CONNECTOR_FACTORY));
-   }
-   
-   protected ClientSessionFactory createNettyFactory()
-   {
-      return new ClientSessionFactoryImpl(new TransportConfiguration(NETTY_CONNECTOR_FACTORY));
-   }
-   
-   protected ClientMessage createTextMessage(ClientSession session, String s)
-   {
-      return createTextMessage(session, s, true);
-   }
-
-   protected ClientMessage createTextMessage(ClientSession session, String s, boolean durable)
-   {
-      ClientMessage message = session.createClientMessage(JBossTextMessage.TYPE, durable, 0, System.currentTimeMillis(), (byte) 1);
-      message.getBody().putString(s);
-      message.getBody().flip();
-      return message;
-   }
-
-   protected ClientMessage createBytesMessage(ClientSession session, byte[] b, boolean durable)
-   {
-      ClientMessage message = session.createClientMessage(JBossBytesMessage.TYPE, durable, 0, System.currentTimeMillis(), (byte) 1);
-      message.getBody().putBytes(b);
-      message.getBody().flip();
-      return message;
-   }
-
-   
-   
-   // Private -------------------------------------------------------
-   
-   // Inner classes -------------------------------------------------
-   
-}

Added: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/chunkmessage/MessageChunkTest.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/chunkmessage/MessageChunkTest.java	                        (rev 0)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/chunkmessage/MessageChunkTest.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -0,0 +1,784 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.jboss.messaging.tests.integration.chunkmessage;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.util.HashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import junit.framework.AssertionFailedError;
+
+import org.jboss.messaging.core.client.ClientConsumer;
+import org.jboss.messaging.core.client.ClientMessage;
+import org.jboss.messaging.core.client.ClientProducer;
+import org.jboss.messaging.core.client.ClientSession;
+import org.jboss.messaging.core.client.ClientSessionFactory;
+import org.jboss.messaging.core.client.FileClientMessage;
+import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
+import org.jboss.messaging.core.client.impl.ClientSessionImpl;
+import org.jboss.messaging.core.config.Configuration;
+import org.jboss.messaging.core.config.TransportConfiguration;
+import org.jboss.messaging.core.exception.MessagingException;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.remoting.impl.ByteBufferWrapper;
+import org.jboss.messaging.core.remoting.impl.RemotingConnectionImpl;
+import org.jboss.messaging.core.remoting.impl.RemotingServiceImpl;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
+import org.jboss.messaging.core.server.ServerMessage;
+import org.jboss.messaging.core.server.impl.ServerMessageImpl;
+import org.jboss.messaging.core.settings.impl.QueueSettings;
+import org.jboss.messaging.tests.integration.chunkmessage.mock.MockConnector;
+import org.jboss.messaging.tests.integration.chunkmessage.mock.MockConnectorFactory;
+import org.jboss.messaging.tests.util.ServiceTestBase;
+import org.jboss.messaging.util.DataConstants;
+import org.jboss.messaging.util.SimpleString;
+
+/**
+ * A TestMessageChunk
+ *
+ * @author <a href="mailto:clebert.suconic at jboss.org">Clebert Suconic</a>
+ * 
+ * Created 29-Sep-08 4:04:10 PM
+ *
+ *
+ */
+public class MessageChunkTest extends ServiceTestBase
+{
+
+   // Constants -----------------------------------------------------
+
+   // Attributes ----------------------------------------------------
+
+   private static final SimpleString ADDRESS = new SimpleString("SimpleAddress");
+
+   // Static --------------------------------------------------------
+   private static final Logger log = Logger.getLogger(MessageChunkTest.class);
+
+   // Constructors --------------------------------------------------
+
+   // Public --------------------------------------------------------
+
+   public void testFailureOnSendingFile() throws Exception
+   {
+      clearData();
+
+      Configuration config = createDefaultConfig();
+
+      config.setPagingMaxGlobalSizeBytes(20 * 1024);
+      config.setPagingDefaultSize(10 * 1024);
+
+      messagingService = createService(true, config, new HashMap<String, QueueSettings>());
+
+      messagingService.start();
+
+      final int numberOfIntegersBigMessage = 150000;
+
+      ClientSession session = null;
+
+      class LocalCallback implements MockConnector.MockCallback
+      {
+
+         AtomicInteger counter = new AtomicInteger(0);
+
+         ClientSession session;
+
+         public void onWrite(final MessagingBuffer buffer)
+         {
+            if (counter.incrementAndGet() == 10)
+            {
+               RemotingConnectionImpl conn = (RemotingConnectionImpl)((ClientSessionImpl)session).getConnection();
+               RemotingServiceImpl remotingServiceImpl = (RemotingServiceImpl)messagingService.getServer()
+                                                                                              .getRemotingService();
+               remotingServiceImpl.connectionException(conn.getID(),
+                                                       new MessagingException(MessagingException.NOT_CONNECTED, "blah!"));
+               conn.fail(new MessagingException(MessagingException.NOT_CONNECTED, "blah"));
+               throw new IllegalStateException("blah");
+            }
+         }
+
+      }
+
+      LocalCallback callback = new LocalCallback();
+
+      try
+      {
+         HashMap<String, Object> parameters = new HashMap<String, Object>();
+         parameters.put("callback", callback);
+
+         TransportConfiguration transport = new TransportConfiguration(MockConnectorFactory.class.getCanonicalName(),
+                                                                       parameters);
+
+         ClientSessionFactory mockFactory = new ClientSessionFactoryImpl(transport);
+
+         mockFactory.setBlockOnNonPersistentSend(false);
+         mockFactory.setBlockOnPersistentSend(false);
+         mockFactory.setBlockOnAcknowledge(false);
+
+         session = mockFactory.createSession(false, true, true, true);
+
+         callback.session = session;
+
+         session.createQueue(ADDRESS, ADDRESS, null, true, false);
+
+         ClientProducer producer = session.createProducer(ADDRESS);
+
+         FileClientMessage clientLarge = createLargeClientMessage(session, numberOfIntegersBigMessage);
+
+         try
+         {
+            producer.send(clientLarge);
+            fail("Exception was expected!");
+         }
+         catch (Exception e)
+         {
+         }
+
+         File largeMessagesFileDir = new File(largeMessagesDir);
+
+         // Deleting the file is async... we keep looking for a period of the time until the file is really gone
+         for (int i = 0; i < 100; i++)
+         {
+            if (largeMessagesFileDir.listFiles().length > 0)
+            {
+               Thread.sleep(10);
+            }
+            else
+            {
+               break;
+            }
+         }
+
+         assertEquals(0, largeMessagesFileDir.listFiles().length);
+
+      }
+      finally
+      {
+         try
+         {
+            messagingService.stop();
+         }
+         catch (Exception ignored)
+         {
+            ignored.printStackTrace();
+         }
+      }
+
+   }
+
+   public void testMessageChunkNullPersistence() throws Exception
+   {
+      testInternal(false, false, 100, 5000, false, 0);
+   }
+
+   public void testMessageChunkNullPersistenceDelayed() throws Exception
+   {
+      testInternal(false, false, 100, 5000, false, 100);
+   }
+
+   public void testMessageChunkFilePersistence() throws Exception
+   {
+      testInternal(true, false, 100, 262144, false, 0);
+   }
+
+   public void testMessageChunkFilePersistence100M() throws Exception
+   {
+      testInternal(true, true, 1, 268435456, true, 0);
+      //testInternal(true, true, 1, 26214400, false, 0);
+   }
+
+   public void testMessageChunkFilePersistenceDelayed() throws Exception
+   {
+      testInternal(true, false, 1000, 50000, false, 1000);
+   }
+
+   public void testSendfileMessage() throws Exception
+   {
+      testInternal(true, true, 100, 50000, false, 0);
+
+   }
+
+   public void testSendfileMessageOnNullPersistence() throws Exception
+   {
+      testInternal(false, true, 100, 50000, false, 0);
+   }
+
+   public void testSendfileMessageSmallMessage() throws Exception
+   {
+      testInternal(true, true, 100, 4, false, 0);
+
+   }
+
+   public void testSendfileMessageOnNullPersistenceSmallMessage() throws Exception
+   {
+      testInternal(false, true, 100, 100, false, 0);
+   }
+
+   public void testSendRegularMessageNullPersistence() throws Exception
+   {
+      testInternal(false, false, 100, 100, false, 0);
+   }
+
+   public void testSendRegularMessageNullPersistenceDelayed() throws Exception
+   {
+      testInternal(false, false, 100, 100, false, 1000);
+   }
+
+   public void testSendRegularMessagePersistence() throws Exception
+   {
+      testInternal(true, false, 100, 100, false, 0);
+   }
+
+   public void testSendRegularMessagePersistenceDelayed() throws Exception
+   {
+      testInternal(true, false, 100, 100, false, 1000);
+   }
+
+   public void testTwoBindingsOneAckAndrestart() throws Exception
+   {
+      // there are two bindings.. one is ACKed, the other is not, the server is restarted
+      // The other binding is acked... The file must be deleted
+
+      clearData();
+
+      try
+      {
+
+         messagingService = createService(true);
+
+         messagingService.start();
+
+         SimpleString queue[] = new SimpleString[] { new SimpleString("queue1"), new SimpleString("queue2") };
+
+         ClientSessionFactory sf = createInVMFactory();
+
+         ClientSession session = sf.createSession(false, true, true, false);
+
+         session.createQueue(ADDRESS, queue[0], null, true, false);
+         session.createQueue(ADDRESS, queue[1], null, true, false);
+
+         int numberOfIntegers = 50000;
+
+         FileClientMessage clientFile = createLargeClientMessage(session, numberOfIntegers);
+
+         ClientProducer producer = session.createProducer(ADDRESS);
+         producer.send(clientFile);
+
+         producer.close();
+
+         readMessage(session, queue[0], numberOfIntegers);
+
+         session.close();
+
+         messagingService.stop();
+
+         messagingService = createService(true);
+
+         messagingService.start();
+
+         sf = createInVMFactory();
+
+         session = sf.createSession(false, true, true, false);
+
+         readMessage(session, queue[1], numberOfIntegers);
+
+         session.close();
+
+         File largeMessagesFileDir = new File(largeMessagesDir);
+         assertEquals(0, largeMessagesFileDir.listFiles().length);
+      }
+      finally
+      {
+         try
+         {
+            messagingService.stop();
+         }
+         catch (Throwable ignored)
+         {
+         }
+      }
+
+   }
+
+   public void testPageOnLargeMessage() throws Exception
+   {
+      testPageOnLargeMessage(true, false);
+
+   }
+
+   public void testPageOnLargeMessageNullPersistence() throws Exception
+   {
+      testPageOnLargeMessage(false, false);
+
+   }
+
+   private void testPageOnLargeMessage(final boolean realFiles, final boolean sendBlocking) throws Exception
+   {
+
+      clearData();
+
+      Configuration config = createDefaultConfig();
+
+      config.setPagingMaxGlobalSizeBytes(20 * 1024);
+      config.setPagingDefaultSize(10 * 1024);
+
+      messagingService = createService(realFiles, config, new HashMap<String, QueueSettings>());
+
+      messagingService.start();
+
+      final int numberOfIntegers = 256;
+
+      final int numberOfIntegersBigMessage = 100000;
+
+      try
+      {
+         ClientSessionFactory sf = createInVMFactory();
+
+         if (sendBlocking)
+         {
+            sf.setBlockOnNonPersistentSend(true);
+            sf.setBlockOnPersistentSend(true);
+            sf.setBlockOnAcknowledge(true);
+         }
+
+         ClientSession session = sf.createSession(false, true, true, false);
+
+         session.createQueue(ADDRESS, ADDRESS, null, true, false);
+
+         ClientProducer producer = session.createProducer(ADDRESS);
+
+         ByteBuffer ioBuffer = ByteBuffer.allocate(DataConstants.SIZE_INT * numberOfIntegers);
+
+         // printBuffer("body to be sent : " , body);
+
+         ClientMessage message = null;
+
+         MessagingBuffer body = null;
+
+         for (int i = 0; i < 100; i++)
+         {
+            MessagingBuffer bodyLocal = new ByteBufferWrapper(ioBuffer);
+
+            for (int j = 1; j <= numberOfIntegers; j++)
+            {
+               bodyLocal.putInt(j);
+            }
+            bodyLocal.flip();
+
+            if (i == 0)
+            {
+               body = bodyLocal;
+            }
+
+            message = session.createClientMessage(true);
+            message.setBody(bodyLocal);
+
+            producer.send(message);
+         }
+
+         FileClientMessage clientFile = createLargeClientMessage(session, numberOfIntegersBigMessage);
+
+         producer.send(clientFile);
+
+         session.close();
+
+         if (realFiles)
+         {
+            messagingService.stop();
+
+            messagingService = createService(true, config, new HashMap<String, QueueSettings>());
+            messagingService.start();
+
+            sf = createInVMFactory();
+         }
+
+         session = sf.createSession(false, true, true, false);
+
+         ClientConsumer consumer = session.createConsumer(ADDRESS);
+
+         // if (realFiles)
+         // {
+         // consumer.setLargeMessagesAsFiles(true);
+         // consumer.setLargeMessagesDir(new File(clientLargeMessagesDir));
+         // }
+
+         session.start();
+
+         for (int i = 0; i < 100; i++)
+         {
+            ClientMessage message2 = consumer.receive(10000);
+
+            assertNotNull(message2);
+
+            message2.acknowledge();
+
+            System.out.println("msg on client = " + message2.getMessageID());
+
+            assertNotNull(message2);
+
+            try
+            {
+               assertEqualsByteArrays(body.limit(), body.array(), message2.getBody().array());
+            }
+            catch (AssertionFailedError e)
+            {
+               log.info("Expected buffer:" + dumbBytesHex(body.array(), 40));
+               log.info("Arriving buffer:" + dumbBytesHex(message2.getBody().array(), 40));
+               throw e;
+            }
+         }
+
+         consumer.close();
+
+         session.close();
+
+         session = sf.createSession(false, true, true, false);
+
+         readMessage(session, ADDRESS, numberOfIntegersBigMessage);
+
+         // printBuffer("message received : ", message2.getBody());
+
+         session.close();
+      }
+      finally
+      {
+         try
+         {
+            messagingService.stop();
+         }
+         catch (Throwable ignored)
+         {
+         }
+      }
+
+   }
+   
+   private MessagingBuffer createLargeBuffer(int numberOfIntegers)
+   {
+      ByteBuffer ioBuffer = ByteBuffer.allocate(DataConstants.SIZE_INT * numberOfIntegers);
+      MessagingBuffer body = new ByteBufferWrapper(ioBuffer);
+
+      for (int i = 1; i <= numberOfIntegers; i++)
+      {
+         body.putInt(i);
+      }
+      body.flip();
+      
+      return body;
+      
+   }
+
+   public void testInternal(final boolean realFiles,
+                            final boolean useFile,
+                            final int numberOfMessages,
+                            final int numberOfIntegers,
+                            final boolean sendingBlocking,
+                            final long delayDelivery) throws Exception
+   {
+
+      clearData();
+
+      messagingService = createService(realFiles);
+      messagingService.start();
+
+      try
+      {
+         ClientSessionFactory sf = createInVMFactory();
+
+         if (sendingBlocking)
+         {
+            sf.setBlockOnNonPersistentSend(true);
+            sf.setBlockOnPersistentSend(true);
+            sf.setBlockOnAcknowledge(true);
+         }
+
+         ClientSession session = sf.createSession(false, true, true, false);
+
+         session.createQueue(ADDRESS, ADDRESS, null, true, false);
+
+         ClientProducer producer = session.createProducer(ADDRESS);
+
+         if (useFile)
+         {
+            File tmpData = createLargeFile("someFile.dat", numberOfIntegers); 
+
+            for (int i = 0; i < numberOfMessages; i++)
+            {
+               ClientMessage message = session.createFileMessage(true);
+               ((FileClientMessage)message).setFile(tmpData);
+               message.putIntProperty(new SimpleString("counter-message"), i);
+               if (delayDelivery > 0)
+               {
+                  message.putLongProperty(new SimpleString("original-time"), System.currentTimeMillis());
+                  producer.send(message, System.currentTimeMillis() + delayDelivery);
+               }
+               else
+               {
+                  producer.send(message);
+               }
+            }
+         }
+         else
+         {
+            for (int i = 0; i < numberOfMessages; i++)
+            {
+               ClientMessage message = session.createClientMessage(true);
+               message.putIntProperty(new SimpleString("counter-message"), i);
+               message.setBody(createLargeBuffer(numberOfIntegers));
+               if (delayDelivery > 0)
+               {
+                  message.putLongProperty(new SimpleString("original-time"), System.currentTimeMillis());
+                  producer.send(message, System.currentTimeMillis() + delayDelivery);
+               }
+               else
+               {
+                  producer.send(message);
+               }
+            }
+         }
+
+
+         session.close();
+
+         if (realFiles)
+         {
+            messagingService.stop();
+
+            messagingService = createService(realFiles);
+            messagingService.start();
+
+            sf = createInVMFactory();
+         }
+
+         session = sf.createSession(false, true, true, false);
+
+         ClientConsumer consumer = null;
+         
+         if (realFiles)
+         {
+            consumer = session.createFileConsumer(new File(clientLargeMessagesDir), ADDRESS);
+         }
+         else
+         {
+            consumer = session.createConsumer(ADDRESS);
+         }
+         
+         session.start();
+
+         for (int i = 0; i < numberOfMessages; i++)
+         {
+            ClientMessage message = consumer.receive(1000 + delayDelivery);
+            
+            assertNotNull(message);
+            
+            
+            if (delayDelivery > 0)
+            {
+               long originalTime = (Long)message.getProperty(new SimpleString("original-time"));
+               assertTrue("difference = "+ (System.currentTimeMillis() - originalTime), System.currentTimeMillis() - originalTime >= delayDelivery);
+            }
+   
+            message.acknowledge();
+   
+            assertNotNull(message);
+   
+            System.out.println("msg on client = " + message.getMessageID());
+            
+            
+            if (delayDelivery <= 0)
+            { // right now there is no guarantee of ordered delivered on multiple scheduledMessages
+               assertEquals(i, ((Integer)message.getProperty(new SimpleString("counter-message"))).intValue());
+            }
+   
+            if (message instanceof FileClientMessage)
+            {
+               checkFileRead(((FileClientMessage)message).getFile(), numberOfIntegers);
+            }
+            else
+            {
+               MessagingBuffer buffer = message.getBody();
+               buffer.rewind();
+               assertEquals(numberOfIntegers * DataConstants.SIZE_INT, buffer.limit());
+               for (int b = 0; b < numberOfIntegers; b++)
+               {
+                  assertEquals(b, buffer.getInt());
+               }
+            }
+         }
+
+         session.close();
+      }
+      finally
+      {
+         try
+         {
+            messagingService.stop();
+         }
+         catch (Throwable ignored)
+         {
+         }
+      }
+   }
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   @Override
+   protected void setUp() throws Exception
+   {
+   }
+
+   @Override
+   protected void tearDown() throws Exception
+   {
+   }
+
+   // Private -------------------------------------------------------
+
+   private FileClientMessage createLargeClientMessage(final ClientSession session, final int numberOfIntegers) throws Exception
+   {
+
+      FileClientMessage clientMessage = session.createFileMessage(true);
+
+      File tmpFile = createLargeFile("tmpUpload.data", numberOfIntegers);
+
+      clientMessage.setFile(tmpFile);
+
+      return clientMessage;
+   }
+
+   /**
+    * @param name
+    * @param numberOfIntegers
+    * @return
+    * @throws FileNotFoundException
+    * @throws IOException
+    */
+   private File createLargeFile(String name, final int numberOfIntegers) throws FileNotFoundException, IOException
+   {
+      File tmpFile = new File(temporaryDir + "/" + name);
+      
+      log.info("Creating file " + tmpFile);
+
+      RandomAccessFile random = new RandomAccessFile(tmpFile, "rw");
+      FileChannel channel = random.getChannel();
+
+      ByteBuffer buffer = ByteBuffer.allocate(4 * 1000);
+
+      for (int i = 0; i < numberOfIntegers; i++)
+      {
+         if (buffer.position() > 0 && i % 1000 == 0)
+         {
+            buffer.rewind();
+            channel.write(buffer);
+            buffer.rewind();
+         }
+         buffer.putInt(i);
+      }
+      
+      if (buffer.position() > 0)
+      {
+         buffer.rewind();
+         channel.write(buffer);
+      }
+
+      channel.close();
+      random.close();
+
+      log.info("file " + tmpFile + " created");
+
+      return tmpFile;
+   }
+
+   /**
+    * @param session
+    * @param queueToRead
+    * @param numberOfIntegers
+    * @throws MessagingException
+    * @throws FileNotFoundException
+    * @throws IOException
+    */
+   private void readMessage(final ClientSession session, final SimpleString queueToRead, final int numberOfIntegers) throws MessagingException,
+                                                                                                                    FileNotFoundException,
+                                                                                                                    IOException
+   {
+      session.start();
+
+      ClientConsumer consumer = session.createFileConsumer(new File(clientLargeMessagesDir), queueToRead);
+
+      ClientMessage clientMessage = consumer.receive(100000);
+
+      if (!(clientMessage instanceof FileClientMessage))
+      {
+         System.out.println("Size = " + clientMessage.getBodySize());
+      }
+
+      assertTrue(clientMessage instanceof FileClientMessage);
+
+      FileClientMessage fileClientMessage = (FileClientMessage)clientMessage;
+
+      assertNotNull(fileClientMessage);
+      File receivedFile = fileClientMessage.getFile();
+
+      checkFileRead(receivedFile, numberOfIntegers);
+
+      clientMessage.acknowledge();
+
+      consumer.close();
+   }
+
+   /**
+    * @param receivedFile
+    * @throws FileNotFoundException
+    * @throws IOException
+    */
+   private void checkFileRead(final File receivedFile, final int numberOfIntegers) throws FileNotFoundException,
+                                                                                  IOException
+   {
+      RandomAccessFile random2 = new RandomAccessFile(receivedFile, "r");
+      FileChannel channel2 = random2.getChannel();
+
+      ByteBuffer buffer2 = ByteBuffer.allocate(4);
+
+      channel2.position(0l);
+
+      for (int i = 0; i < numberOfIntegers; i++)
+      {
+         buffer2.rewind();
+         channel2.read(buffer2);
+         buffer2.rewind();
+
+         assertEquals(i, buffer2.getInt());
+      }
+
+      channel2.close();
+   }
+
+   // Inner classes -------------------------------------------------
+
+}

Added: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/chunkmessage/mock/MockConnector.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/chunkmessage/mock/MockConnector.java	                        (rev 0)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/chunkmessage/mock/MockConnector.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -0,0 +1,112 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.jboss.messaging.tests.integration.chunkmessage.mock;
+
+import java.util.Map;
+
+import org.jboss.messaging.core.remoting.impl.invm.InVMConnection;
+import org.jboss.messaging.core.remoting.impl.invm.InVMConnector;
+import org.jboss.messaging.core.remoting.spi.BufferHandler;
+import org.jboss.messaging.core.remoting.spi.Connection;
+import org.jboss.messaging.core.remoting.spi.ConnectionLifeCycleListener;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
+
+/**
+ * A MockConnector
+ *
+ * @author <a href="mailto:clebert.suconic at jboss.org">Clebert Suconic</a>
+ * 
+ * Created Oct 22, 2008 11:23:18 AM
+ *
+ *
+ */
+public class MockConnector extends InVMConnector
+{
+   private final MockCallback callback;
+
+   /**
+    * @param configuration
+    * @param handler
+    * @param listener
+    */
+   public MockConnector(final Map<String, Object> configuration,
+                        final BufferHandler handler,
+                        final ConnectionLifeCycleListener listener)
+   {
+      super(configuration, handler, listener);
+      callback = (MockCallback)configuration.get("callback");
+   }
+
+   // Constants -----------------------------------------------------
+
+   // Attributes ----------------------------------------------------
+
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   // Public --------------------------------------------------------
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   @Override
+   protected Connection internalCreateConnection(final BufferHandler handler, final ConnectionLifeCycleListener listener)
+   {
+      return new MockConnection(handler, listener);
+   }
+
+   // Private -------------------------------------------------------
+
+   // Inner classes -------------------------------------------------
+
+   public static interface MockCallback
+   {
+      void onWrite(final MessagingBuffer buffer);
+   }
+
+   class MockConnection extends InVMConnection
+   {
+
+      /**
+       * @param handler
+       * @param listener
+       */
+      public MockConnection(final BufferHandler handler, final ConnectionLifeCycleListener listener)
+      {
+         super(handler, listener);
+      }
+
+      @Override
+      public void write(final MessagingBuffer buffer)
+      {
+         if (callback != null)
+         {
+            callback.onWrite(buffer);
+         }
+
+         super.write(buffer);
+      }
+   }
+}

Added: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/chunkmessage/mock/MockConnectorFactory.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/chunkmessage/mock/MockConnectorFactory.java	                        (rev 0)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/chunkmessage/mock/MockConnectorFactory.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -0,0 +1,71 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.jboss.messaging.tests.integration.chunkmessage.mock;
+
+import java.util.Map;
+
+import org.jboss.messaging.core.remoting.spi.BufferHandler;
+import org.jboss.messaging.core.remoting.spi.ConnectionLifeCycleListener;
+import org.jboss.messaging.core.remoting.spi.Connector;
+import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
+
+/**
+ * A MockConnectorFactory
+ *
+ * @author <a href="mailto:clebert.suconic at jboss.org">Clebert Suconic</a>
+ * 
+ * Created Oct 22, 2008 12:04:11 PM
+ *
+ *
+ */
+public class MockConnectorFactory implements ConnectorFactory
+{
+   // Constants -----------------------------------------------------
+
+   // Attributes ----------------------------------------------------
+
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   // Public --------------------------------------------------------
+
+   /* (non-Javadoc)
+    * @see org.jboss.messaging.core.remoting.spi.ConnectorFactory#createConnector(java.util.Map, org.jboss.messaging.core.remoting.spi.BufferHandler, org.jboss.messaging.core.remoting.spi.ConnectionLifeCycleListener)
+    */
+   public Connector createConnector(final Map<String, Object> configuration,
+                                    final BufferHandler handler,
+                                    final ConnectionLifeCycleListener listener)
+   {
+      return new MockConnector(configuration, handler, listener);
+   }
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   // Private -------------------------------------------------------
+
+   // Inner classes -------------------------------------------------
+
+}

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/paging/PagingManagerIntegrationTest.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/paging/PagingManagerIntegrationTest.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/paging/PagingManagerIntegrationTest.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -69,7 +69,8 @@
       PagingManagerImpl managerImpl = new PagingManagerImpl(new PagingManagerFactoryNIO(journalDir),
                                                             null,
                                                             queueSettings,
-                                                            -1);
+                                                            -1,
+                                                            1024 * 1024);
       managerImpl.start();
 
       PagingStore store = managerImpl.getPageStore(new SimpleString("simple-test"));
@@ -92,7 +93,7 @@
 
       assertEquals(1, msgs.length);
 
-      assertEqualsByteArrays(msg.getBody().array(), msgs[0].getMessage().getBody().array());
+      assertEqualsByteArrays(msg.getBody().array(), (msgs[0].getMessage(null)).getBody().array());
 
       assertTrue(store.isPaging());
 
@@ -115,7 +116,8 @@
       PagingManagerImpl managerImpl = new PagingManagerImpl(new PagingManagerFactoryNIO(journalDir),
                                                             null,
                                                             queueSettings,
-                                                            -1);
+                                                            -1,
+                                                            1024 * 1024);
       managerImpl.start();
 
       ServerMessage msg = createMessage(1l, new SimpleString("simple-test"), createRandomBuffer(100));

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/remoting/DestroyConsumerTest.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/remoting/DestroyConsumerTest.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/remoting/DestroyConsumerTest.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -32,10 +32,10 @@
 import org.jboss.messaging.core.postoffice.Binding;
 import org.jboss.messaging.core.server.MessagingService;
 import org.jboss.messaging.core.settings.impl.QueueSettings;
-import org.jboss.messaging.tests.integration.base.IntegrationTestBase;
+import org.jboss.messaging.tests.util.ServiceTestBase;
 import org.jboss.messaging.util.SimpleString;
 
-public class DestroyConsumerTest extends IntegrationTestBase
+public class DestroyConsumerTest extends ServiceTestBase
 {
    
    // Constants -----------------------------------------------------

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/scheduling/ScheduledMessageTest.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/scheduling/ScheduledMessageTest.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/scheduling/ScheduledMessageTest.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -162,7 +162,7 @@
       TransportConfiguration transportConfig = new TransportConfiguration(ACCEPTOR_FACTORY);
       configuration.getAcceptorConfigurations().add(transportConfig);
       configuration.setPagingMaxGlobalSizeBytes(0);
-      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir);
+      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir, null);
       // start the server
       messagingService.start();
       // then we create a client as normal
@@ -200,7 +200,7 @@
       TransportConfiguration transportConfig = new TransportConfiguration(ACCEPTOR_FACTORY);
       configuration.getAcceptorConfigurations().add(transportConfig);
       configuration.setPagingMaxGlobalSizeBytes(0);
-      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir);
+      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir, null);
       // start the server
       messagingService.start();
       QueueSettings qs = new QueueSettings();
@@ -255,7 +255,7 @@
       TransportConfiguration transportConfig = new TransportConfiguration(ACCEPTOR_FACTORY);
       configuration.getAcceptorConfigurations().add(transportConfig);
       configuration.setPagingMaxGlobalSizeBytes(0);
-      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir);
+      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir, null);
       // start the server
       messagingService.start();
       QueueSettings qs = new QueueSettings();
@@ -288,7 +288,7 @@
       session.close();
       messagingService.stop();
       messagingService = null;
-      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir);
+      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir, null);
       messagingService.start();
       sessionFactory = new ClientSessionFactoryImpl(new TransportConfiguration(CONNECTOR_FACTORY));
       session = sessionFactory.createSession(false, true, true, false);
@@ -318,7 +318,7 @@
 
       TransportConfiguration transportConfig = new TransportConfiguration(ACCEPTOR_FACTORY);
       configuration.getAcceptorConfigurations().add(transportConfig);
-      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir);
+      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir, null);
       // start the server
       messagingService.start();
       // then we create a client as normal
@@ -344,7 +344,7 @@
          session.close();
          messagingService.stop();
          messagingService = null;
-         messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir);
+         messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir, null);
          messagingService.start();
          sessionFactory = new ClientSessionFactoryImpl(new TransportConfiguration(CONNECTOR_FACTORY));
          session = sessionFactory.createSession(false, true, true, false);
@@ -372,7 +372,7 @@
 
       TransportConfiguration transportConfig = new TransportConfiguration(ACCEPTOR_FACTORY);
       configuration.getAcceptorConfigurations().add(transportConfig);
-      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir);
+      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir, null);
       // start the server
       messagingService.start();
       // then we create a client as normal
@@ -403,7 +403,7 @@
          session.close();
          messagingService.stop();
          messagingService = null;
-         messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir);
+         messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir, null);
          messagingService.start();
 
          sessionFactory = new ClientSessionFactoryImpl(new TransportConfiguration(CONNECTOR_FACTORY));
@@ -453,7 +453,7 @@
 
       TransportConfiguration transportConfig = new TransportConfiguration(ACCEPTOR_FACTORY);
       configuration.getAcceptorConfigurations().add(transportConfig);
-      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir);
+      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir, null);
       // start the server
       messagingService.start();
       // then we create a client as normal
@@ -485,7 +485,7 @@
          session.close();
          messagingService.stop();
          messagingService = null;
-         messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir);
+         messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir, null);
          messagingService.start();
 
          sessionFactory = new ClientSessionFactoryImpl(new TransportConfiguration(CONNECTOR_FACTORY));
@@ -535,7 +535,7 @@
 
       TransportConfiguration transportConfig = new TransportConfiguration(ACCEPTOR_FACTORY);
       configuration.getAcceptorConfigurations().add(transportConfig);
-      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir);
+      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir, null);
       // start the server
       messagingService.start();
       // then we create a client as normal
@@ -565,7 +565,7 @@
          session.close();
          messagingService.stop();
          messagingService = null;
-         messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir);
+         messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir, null);
          messagingService.start();
 
          sessionFactory = new ClientSessionFactoryImpl(new TransportConfiguration(CONNECTOR_FACTORY));
@@ -611,7 +611,7 @@
       Xid xid2 = new XidImpl("xa2".getBytes(), 1, new GUID().toString().getBytes());
       TransportConfiguration transportConfig = new TransportConfiguration(ACCEPTOR_FACTORY);
       configuration.getAcceptorConfigurations().add(transportConfig);
-      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir);
+      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir, null);
       // start the server
       messagingService.start();
       // then we create a client as normal
@@ -639,7 +639,7 @@
          session.close();
          messagingService.stop();
          messagingService = null;
-         messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir);
+         messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir, null);
          messagingService.start();
 
          sessionFactory = new ClientSessionFactoryImpl(new TransportConfiguration(CONNECTOR_FACTORY));

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/xa/BasicXaRecoveryTest.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/xa/BasicXaRecoveryTest.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/integration/xa/BasicXaRecoveryTest.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -55,6 +55,7 @@
 
    private String journalDir = System.getProperty("java.io.tmpdir", "/tmp") + "/xa-recovery-test/journal";
    private String bindingsDir = System.getProperty("java.io.tmpdir", "/tmp") + "/xa-recovery-test/bindings";
+   private String largeMessagesDir = System.getProperty("java.io.tmpdir", "/tmp") + "/xa-recovery-test/largemsg";
    private String pageDir = System.getProperty("java.io.tmpdir", "/tmp") + "/xa-recovery-test/page";
    private MessagingService messagingService;
    private ClientSession clientSession;
@@ -83,7 +84,7 @@
 
       TransportConfiguration transportConfig = new TransportConfiguration(ACCEPTOR_FACTORY);
       configuration.getAcceptorConfigurations().add(transportConfig);
-      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir);
+      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir, largeMessagesDir);
       //start the server
       messagingService.start();
       //then we create a client as normal
@@ -1188,7 +1189,7 @@
       clientSession = null;
       messagingService.stop();
       messagingService = null;
-      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir);
+      messagingService = MessagingServiceImpl.newNioStorageMessagingServer(configuration, journalDir, bindingsDir, largeMessagesDir);
       
       addSettings();
       

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/stress/paging/MultipleDestinationPagingTest.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/stress/paging/MultipleDestinationPagingTest.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/stress/paging/MultipleDestinationPagingTest.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -23,7 +23,7 @@
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.server.MessagingService;
 import org.jboss.messaging.core.settings.impl.QueueSettings;
-import org.jboss.messaging.tests.integration.base.IntegrationTestBase;
+import org.jboss.messaging.tests.util.ServiceTestBase;
 import org.jboss.messaging.util.SimpleString;
 
 /**
@@ -31,7 +31,7 @@
  * 
  * @author <a href="mailto:clebert.suconic at jboss.com">Clebert Suconic</a>
  */
-public class MultipleDestinationPagingTest extends IntegrationTestBase
+public class MultipleDestinationPagingTest extends ServiceTestBase
 {
 
    // Constants -----------------------------------------------------
@@ -77,7 +77,7 @@
          settings.put("page-adr", setting);
       }
 
-      service = createService(true, false, config, settings);
+      service = createService(true, config, settings);
       service.start();
 
       ClientSessionFactory factory = createInVMFactory();

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/ReclaimerTest.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/ReclaimerTest.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/ReclaimerTest.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -757,7 +757,7 @@
          return null;
       }
 
-      public int getOffset()
+      public long getOffset()
       {
          return 0;
       }
@@ -767,7 +767,7 @@
          return 0;
       }
 
-      public void setOffset(final int offset)
+      public void setOffset(final long offset)
       {
       }
 

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/fakes/FakeSequentialFileFactory.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/fakes/FakeSequentialFileFactory.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/journal/impl/fakes/FakeSequentialFileFactory.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -82,7 +82,7 @@
 
    // Public --------------------------------------------------------
 
-   public SequentialFile createSequentialFile(final String fileName, final int maxAIO) throws Exception
+   public SequentialFile createSequentialFile(final String fileName, final int maxAIO)
    {
       FakeSequentialFile sf = fileMap.get(fileName);
 
@@ -416,7 +416,7 @@
          return bytesRead.length;
       }
 
-      public void position(final int pos) throws Exception
+      public void position(final long pos) throws Exception
       {
          if (!open)
          {
@@ -425,10 +425,10 @@
 
          checkAlignment(pos);
 
-         data.position(pos);
+         data.position((int)pos);
       }
 
-      public int position() throws Exception
+      public long position() throws Exception
       {
          return data.position();
       }
@@ -546,7 +546,7 @@
          return "FakeSequentialFile:" + fileName;
       }
 
-      private void checkAlignment(final int position)
+      private void checkAlignment(final long position)
       {
          if (position % alignment != 0)
          {
@@ -554,6 +554,14 @@
          }
       }
 
+      /* (non-Javadoc)
+       * @see org.jboss.messaging.core.journal.SequentialFile#renameTo(org.jboss.messaging.core.journal.SequentialFile)
+       */
+      public void renameTo(SequentialFile file) throws Exception
+      {
+         throw new IllegalStateException("Method rename not supoprted on FakeSequentialFile");
+      }
+
    }
 
 }

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PageImplTestBase.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PageImplTestBase.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PageImplTestBase.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -119,11 +119,11 @@
 
       for (int i = 0; i < msgs.length; i++)
       {
-         assertEquals(i, msgs[i].getMessage().getMessageID());
+         assertEquals(i, (msgs[i].getMessage(null)).getMessageID());
 
-         assertEquals(simpleDestination, msgs[i].getMessage().getDestination());
+         assertEquals(simpleDestination, (msgs[i].getMessage(null)).getDestination());
 
-         assertEqualsByteArrays(buffers.get(i).array(), msgs[i].getMessage().getBody().array());
+         assertEqualsByteArrays(buffers.get(i).array(), (msgs[i].getMessage(null)).getBody().array());
       }
 
       impl.delete();

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PageManagerImplTest.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PageManagerImplTest.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PageManagerImplTest.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -73,7 +73,7 @@
       queueSettings.setDefault(new QueueSettings());
 
       PagingStoreFactory spi = EasyMock.createMock(PagingStoreFactory.class);
-      PagingManagerImpl manager = new PagingManagerImpl(spi, null, queueSettings, -1);
+      PagingManagerImpl manager = new PagingManagerImpl(spi, null, queueSettings, -1, 1024 * 1024);
 
       SimpleString destination = new SimpleString("some-destination");
 
@@ -125,7 +125,7 @@
    public void testMultipleThreadsGetStore() throws Exception
    {
       PagingStoreFactory spi = EasyMock.createMock(PagingStoreFactory.class);
-      final PagingManagerImpl manager = new PagingManagerImpl(spi, null, repoSettings, -1);
+      final PagingManagerImpl manager = new PagingManagerImpl(spi, null, repoSettings, -1, 1024 * 1024);
 
       final SimpleString destination = new SimpleString("some-destination");
 
@@ -210,7 +210,7 @@
       PagingStoreFactory spi = EasyMock.createMock(PagingStoreFactory.class);
       PagingStore store = EasyMock.createNiceMock(PagingStore.class);
       StorageManager storageManager = EasyMock.createStrictMock(StorageManager.class);
-      PagingManagerImpl manager = new PagingManagerImpl(spi, storageManager, queueSettings, -1);
+      PagingManagerImpl manager = new PagingManagerImpl(spi, storageManager, queueSettings, -1, 1024 * 1024);
       manager.setPostOffice(po);
       ServerMessage message = EasyMock.createStrictMock(ServerMessage.class);
 
@@ -243,7 +243,7 @@
       PagingStoreFactory spi = EasyMock.createMock(PagingStoreFactory.class);
       PagingStore store = EasyMock.createNiceMock(PagingStore.class);
       StorageManager storageManager = EasyMock.createStrictMock(StorageManager.class);
-      PagingManagerImpl manager = new PagingManagerImpl(spi, storageManager, queueSettings, -1);
+      PagingManagerImpl manager = new PagingManagerImpl(spi, storageManager, queueSettings, -1, 1024 * 1024);
       manager.setPostOffice(po);
       ServerMessage message = EasyMock.createStrictMock(ServerMessage.class);
 

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PagingStoreImplTest.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PagingStoreImplTest.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PagingStoreImplTest.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -22,6 +22,10 @@
 
 package org.jboss.messaging.tests.unit.core.paging.impl;
 
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.List;
+
 import org.jboss.messaging.core.journal.SequentialFileFactory;
 import org.jboss.messaging.core.paging.Page;
 import org.jboss.messaging.core.paging.PageMessage;
@@ -33,10 +37,6 @@
 import org.jboss.messaging.tests.unit.core.journal.impl.fakes.FakeSequentialFileFactory;
 import org.jboss.messaging.util.SimpleString;
 
-import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.List;
-
 /**
  * 
  * @author <a href="mailto:clebert.suconic at jboss.com">Clebert Suconic</a>
@@ -201,8 +201,8 @@
 
       for (int i = 0; i < 10; i++)
       {
-         assertEquals(0, msg[i].getMessage().getMessageID());
-         assertEqualsByteArrays(buffers.get(i).array(), msg[i].getMessage().getBody().array());
+         assertEquals(0, (msg[i].getMessage(null)).getMessageID());
+         assertEqualsByteArrays(buffers.get(i).array(), (msg[i].getMessage(null)).getBody().array());
       }
 
    }
@@ -264,8 +264,8 @@
 
          for (int i = 0; i < 5; i++)
          {
-            assertEquals(0, msg[i].getMessage().getMessageID());
-            assertEqualsByteArrays(buffers.get(pageNr * 5 + i).array(), msg[i].getMessage().getBody().array());
+            assertEquals(0, (msg[i].getMessage(null)).getMessageID());
+            assertEqualsByteArrays(buffers.get(pageNr * 5 + i).array(), (msg[i].getMessage(null)).getBody().array());
          }
       }
 
@@ -307,9 +307,9 @@
 
       assertEquals(1, msgs.length);
 
-      assertEquals(0l, msgs[0].getMessage().getMessageID());
+      assertEquals(0l, (msgs[0].getMessage(null)).getMessageID());
 
-      assertEqualsByteArrays(buffers.get(0).array(), msgs[0].getMessage().getBody().array());
+      assertEqualsByteArrays(buffers.get(0).array(), (msgs[0].getMessage(null)).getBody().array());
 
       assertEquals(1, storeImpl.getNumberOfPages());
 

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PagingStoreTestBase.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PagingStoreTestBase.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/paging/impl/PagingStoreTestBase.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -229,15 +229,16 @@
 
          for (PageMessage msg : msgs)
          {
-            msg.getMessage().getBody().rewind();
-            long id = msg.getMessage().getBody().getLong();
-            msg.getMessage().getBody().rewind();
+            (msg.getMessage(null)).getBody().rewind();
+            long id = (msg.getMessage(null)).getBody().getLong();
+            (msg.getMessage(null)).getBody().rewind();
 
             PageMessageImpl msgWritten = buffers.remove(id);
             buffers2.put(id, msg);
             assertNotNull(msgWritten);
-            assertEquals(msg.getMessage().getDestination(), msgWritten.getMessage().getDestination());
-            assertEqualsByteArrays(msgWritten.getMessage().getBody().array(), msg.getMessage().getBody().array());
+            assertEquals((msg.getMessage(null)).getDestination(), (msgWritten.getMessage(null)).getDestination());
+            assertEqualsByteArrays((msgWritten.getMessage(null)).getBody().array(), (msg.getMessage(null)).getBody()
+                                                                                                          .array());
          }
       }
 
@@ -293,12 +294,13 @@
          for (PageMessage msg : msgs)
          {
 
-            msg.getMessage().getBody().rewind();
-            long id = msg.getMessage().getBody().getLong();
+            (msg.getMessage(null)).getBody().rewind();
+            long id = (msg.getMessage(null)).getBody().getLong();
             PageMessage msgWritten = buffers2.remove(id);
             assertNotNull(msgWritten);
-            assertEquals(msg.getMessage().getDestination(), msgWritten.getMessage().getDestination());
-            assertEqualsByteArrays(msgWritten.getMessage().getBody().array(), msg.getMessage().getBody().array());
+            assertEquals((msg.getMessage(null)).getDestination(), (msgWritten.getMessage(null)).getDestination());
+            assertEqualsByteArrays((msgWritten.getMessage(null)).getBody().array(), (msg.getMessage(null)).getBody()
+                                                                                                          .array());
          }
       }
 
@@ -307,9 +309,10 @@
       lastPage.close();
       assertEquals(1, lastMessages.length);
 
-      lastMessages[0].getMessage().getBody().rewind();
-      assertEquals(lastMessages[0].getMessage().getBody().getLong(), lastMessageId);
-      assertEqualsByteArrays(lastMessages[0].getMessage().getBody().array(), lastMsg.getMessage().getBody().array());
+      (lastMessages[0].getMessage(null)).getBody().rewind();
+      assertEquals((lastMessages[0].getMessage(null)).getBody().getLong(), lastMessageId);
+      assertEqualsByteArrays((lastMessages[0].getMessage(null)).getBody().array(), (lastMsg.getMessage(null)).getBody()
+                                                                                                             .array());
 
       assertEquals(0, buffers2.size());
 

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/persistence/impl/journal/JournalStorageManagerTest.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/persistence/impl/journal/JournalStorageManagerTest.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/persistence/impl/journal/JournalStorageManagerTest.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -76,11 +76,12 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       ServerMessage msg = EasyMock.createStrictMock(ServerMessage.class);
       long msgID = 1021092;
-      EasyMock.expect(msg.getMessageID()).andReturn(msgID);
+      EasyMock.expect(msg.getMessageID()).andStubReturn(msgID);
+      
       messageJournal.appendAddRecord(msgID, JournalStorageManager.ADD_MESSAGE, msg);
       EasyMock.replay(messageJournal, bindingsJournal, msg);
       jsm.storeMessage(msg);
@@ -92,7 +93,7 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       final long queueID = 1210981;
       final long messageID = 101921092;
@@ -110,7 +111,7 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       final long messageID = 101921092;
 
@@ -125,11 +126,11 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       ServerMessage msg = EasyMock.createStrictMock(ServerMessage.class);
       long msgID = 1021092;
-      EasyMock.expect(msg.getMessageID()).andReturn(msgID);
+      EasyMock.expect(msg.getMessageID()).andStubReturn(msgID);
       long txID = 192872;
       messageJournal.appendAddRecordTransactional(txID, msgID, JournalStorageManager.ADD_MESSAGE, msg);
       EasyMock.replay(messageJournal, bindingsJournal, msg);
@@ -142,7 +143,7 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       final long queueID = 1210981;
       final long messageID = 101921092;
@@ -162,7 +163,7 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       final long messageID = 101921092;
       final long txID = 1209373;
@@ -178,7 +179,7 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       final long txID = 1209373;
 
@@ -196,7 +197,7 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       final long txID = 1209373;
 
@@ -211,7 +212,7 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       final long txID = 1209373;
 
@@ -226,7 +227,7 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       final long msgID = 120912901;
       final long queueID = 1283743;
@@ -254,7 +255,7 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       messageJournal.load((List<RecordInfo>)EasyMock.anyObject(), (List<PreparedTransactionInfo>)EasyMock.anyObject());
 
@@ -422,7 +423,7 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       Queue queue = EasyMock.createStrictMock(Queue.class);
       SimpleString queueName = new SimpleString("saiohsiudh");
@@ -493,7 +494,7 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       Binding binding = EasyMock.createStrictMock(Binding.class);
       Queue queue = EasyMock.createStrictMock(Queue.class);
@@ -515,7 +516,7 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       Binding binding = EasyMock.createStrictMock(Binding.class);
       Queue queue = EasyMock.createStrictMock(Queue.class);
@@ -543,7 +544,7 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       SimpleString dest = new SimpleString("oaskokas");
 
@@ -667,7 +668,7 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       bindingsJournal.load((List<RecordInfo>)EasyMock.anyObject(), (List<PreparedTransactionInfo>)EasyMock.anyObject());
 
@@ -734,7 +735,7 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       assertFalse(jsm.isStarted());
       bindingsJournal.start();
@@ -788,7 +789,7 @@
       Journal messageJournal = EasyMock.createStrictMock(Journal.class);
       Journal bindingsJournal = EasyMock.createStrictMock(Journal.class);
 
-      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal);
+      JournalStorageManager jsm = new JournalStorageManager(messageJournal, bindingsJournal, null);
 
       long id = jsm.generateUniqueID();
 

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/server/impl/MessageReferenceImplTest.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/server/impl/MessageReferenceImplTest.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/server/impl/MessageReferenceImplTest.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -180,7 +180,6 @@
       EasyMock.expect(po.route(serverMessage)).andReturn(new ArrayList<MessageReference>());
       
       EasyMock.expect(serverMessage.getDurableRefCount()).andReturn(0);
-      EasyMock.expect(serverMessage.decrementRefCount()).andReturn(1);
       EasyMock.expect(serverMessage.decrementDurableRefCount()).andReturn(0);
       
       EasyMock.expect(sm.generateUniqueID()).andReturn(1l);
@@ -299,7 +298,6 @@
       EasyMock.expect(repos.getMatch(queueName.toString())).andStubReturn(queueSettings);
       EasyMock.expect(serverMessage.isDurable()).andStubReturn(true);
       EasyMock.expect(serverMessage.getMessageID()).andStubReturn(999l);
-      EasyMock.expect(serverMessage.decrementRefCount()).andReturn(1);
       EasyMock.expect(queue.isDurable()).andStubReturn(true);
       EasyMock.expect(serverMessage.decrementDurableRefCount()).andReturn(0);
       EasyMock.expect(sm.generateUniqueID()).andReturn(1l);

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/server/impl/QueueImplTest.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/server/impl/QueueImplTest.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/server/impl/QueueImplTest.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -449,7 +449,7 @@
 
    public void testChangeConsumersAndDeliver() throws Exception
    {
-      Queue queue = new QueueImpl(1, queue1, null, false, true, false, scheduledExecutor, null);
+      Queue queue = new QueueImpl(1, queue1, null, false, true, false, scheduledExecutor, createMockPostOffice());
 
       final int numMessages = 10;
 
@@ -719,7 +719,7 @@
 
    public void testDeleteAllReferences() throws Exception
    {
-      Queue queue = new QueueImpl(1, queue1, null, false, true, false, scheduledExecutor, null);
+      Queue queue = new QueueImpl(1, queue1, null, false, true, false, scheduledExecutor, createMockPostOffice());
 
       StorageManager storageManager = EasyMock.createStrictMock(StorageManager.class);
 
@@ -939,7 +939,7 @@
 
    public void testConsumeWithFiltersAddAndRemoveConsumer() throws Exception
    {
-      Queue queue = new QueueImpl(1, queue1, null, false, true, false, scheduledExecutor, null);
+      Queue queue = new QueueImpl(1, queue1, null, false, true, false, scheduledExecutor, createMockPostOffice());
 
       Filter filter = new FakeFilter("fruit", "orange");
 
@@ -1012,7 +1012,7 @@
 
    private void testConsumerWithFilters(boolean direct) throws Exception
    {
-      Queue queue = new QueueImpl(1, queue1, null, false, true, false, scheduledExecutor, null);
+      Queue queue = new QueueImpl(1, queue1, null, false, true, false, scheduledExecutor, createMockPostOffice());
 
       Filter filter = new FakeFilter("fruit", "orange");
 
@@ -1250,7 +1250,7 @@
    {
       long messageID = randomLong();
       final SimpleString expiryQueue = new SimpleString("expiryQueue");
-      Queue queue = new QueueImpl(1, queue1, null, false, true, false, scheduledExecutor, null);
+      Queue queue = new QueueImpl(1, queue1, null, false, true, false, scheduledExecutor, createMockPostOffice());
       MessageReference messageReference = generateReference(queue, messageID);
       StorageManager storageManager = EasyMock.createMock(StorageManager.class);
       EasyMock.expect(storageManager.generateUniqueID()).andReturn(randomLong());
@@ -1308,7 +1308,7 @@
    {
       long messageID = randomLong();
       final SimpleString dlqName = new SimpleString("dlq");
-      Queue queue = new QueueImpl(1, queue1, null, false, true, false, scheduledExecutor, null);
+      Queue queue = new QueueImpl(1, queue1, null, false, true, false, scheduledExecutor, createMockPostOffice());
       MessageReference messageReference = generateReference(queue, messageID);
       StorageManager storageManager = createMock(StorageManager.class);
       expect(storageManager.generateUniqueID()).andReturn(randomLong());
@@ -1367,7 +1367,7 @@
       long newMessageID = randomLong();
       long tid = randomLong();
       final SimpleString toQueueName = new SimpleString("toQueueName");
-      Queue queue = new QueueImpl(1, queue1, null, false, true, false, scheduledExecutor, null);
+      Queue queue = new QueueImpl(1, queue1, null, false, true, false, scheduledExecutor, createMockPostOffice());
       Queue toQueue = createMock(Queue.class);
     
       MessageReference messageReference = generateReference(queue, messageID);
@@ -1413,6 +1413,19 @@
 
       EasyMock.verify(storageManager, postOffice, queueSettingsRepository, toBinding, pm);
    }
+
+   /**
+    * @return
+    */
+   private PostOffice createMockPostOffice()
+   {
+      PagingManager niceManager = EasyMock.createNiceMock(PagingManager.class);
+      PostOffice nicePostOffice = EasyMock.createNiceMock(PostOffice.class);
+      EasyMock.expect(nicePostOffice.getPagingManager()).andStubReturn(niceManager);
+      EasyMock.replay(niceManager, nicePostOffice);
+      return nicePostOffice;
+   }
+
    
    // Inner classes ---------------------------------------------------------------
 

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerMessageImplTest.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerMessageImplTest.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/server/impl/ServerMessageImplTest.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -134,10 +134,10 @@
       
       assertEquals(2, msg.getDurableRefCount());
       
-      msg.incrementReference(true);
+      msg.incrementDurableRefCount();
       assertEquals(3, msg.getDurableRefCount());
       
-      msg.incrementReference(true);
+      msg.incrementDurableRefCount();
       assertEquals(4, msg.getDurableRefCount());
       
       msg.decrementDurableRefCount();

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/settings/impl/QueueSettingsTest.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/settings/impl/QueueSettingsTest.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/settings/impl/QueueSettingsTest.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -41,7 +41,7 @@
       assertEquals(queueSettings.getExpiryQueue(), null);
       assertEquals(queueSettings.getMaxDeliveryAttempts(), QueueSettings.DEFAULT_MAX_DELIVERY_ATTEMPTS);
       assertEquals(queueSettings.getMaxSizeBytes(), QueueSettings.DEFAULT_MAX_SIZE_BYTES);
-      assertEquals(queueSettings.getPageSizeBytes(), QueueSettings.DEFAULT_PAGE_SIZE_BYTES);
+      assertEquals(queueSettings.getPageSizeBytes(), null);
       assertEquals(queueSettings.getMessageCounterHistoryDayLimit(), QueueSettings.DEFAULT_MESSAGE_COUNTER_HISTORY_DAY_LIMIT);
       assertEquals(queueSettings.getRedeliveryDelay(), QueueSettings.DEFAULT_REDELIVER_DELAY);
 

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/transaction/impl/TransactionImplTest.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/transaction/impl/TransactionImplTest.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/unit/core/transaction/impl/TransactionImplTest.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -23,6 +23,8 @@
 package org.jboss.messaging.tests.unit.core.transaction.impl;
 
 import org.easymock.EasyMock;
+import org.jboss.messaging.core.paging.PagingManager;
+import org.jboss.messaging.core.paging.PagingStore;
 import org.jboss.messaging.core.persistence.StorageManager;
 import org.jboss.messaging.core.postoffice.PostOffice;
 import org.jboss.messaging.core.server.MessageReference;
@@ -532,14 +534,24 @@
    
    public void testAckCommit() throws Exception
    {
+      
+      PagingManager pagingManager = EasyMock.createStrictMock(PagingManager.class);
+      PostOffice postOffice = EasyMock.createMock(PostOffice.class);
+      PagingStore pagingStore = EasyMock.createStrictMock(PagingStore.class);
+      
+      EasyMock.expect(pagingManager.getPageStore((SimpleString)EasyMock.anyObject())).andStubReturn(pagingStore);
+      EasyMock.expect(postOffice.getPagingManager()).andStubReturn(pagingManager);
+      
+      EasyMock.replay(pagingManager, postOffice);
+      
       //Durable queue
-      Queue queue1 = new QueueImpl(12, new SimpleString("queue1"), null, false, true, false, scheduledExecutor, null);
+      Queue queue1 = new QueueImpl(12, new SimpleString("queue1"), null, false, true, false, scheduledExecutor, postOffice);
       
       //Durable queue
-      Queue queue2 = new QueueImpl(34, new SimpleString("queue2"), null, false, true, false, scheduledExecutor, null);
+      Queue queue2 = new QueueImpl(34, new SimpleString("queue2"), null, false, true, false, scheduledExecutor, postOffice);
       
       //Non durable queue
-      Queue queue3 = new QueueImpl(65, new SimpleString("queue3"), null, false, false, false, scheduledExecutor, null);
+      Queue queue3 = new QueueImpl(65, new SimpleString("queue3"), null, false, false, false, scheduledExecutor, postOffice);
       
       //Some refs to ack
       
@@ -568,7 +580,9 @@
       
       EasyMock.expect(sm.generateUniqueID()).andReturn(txID);
       
-      EasyMock.replay(sm);
+      EasyMock.reset(postOffice, pagingManager, pagingStore);
+      
+      EasyMock.replay(sm, postOffice, pagingManager, pagingStore);
             
       Transaction tx = new TransactionImpl(sm, po);
       
@@ -576,16 +590,16 @@
       
       assertFalse(tx.isContainsPersistent());
             
-      EasyMock.verify(sm);
+      EasyMock.verify(sm, postOffice, pagingManager, pagingStore);
       
-      EasyMock.reset(sm);
+      EasyMock.reset(sm, postOffice, pagingManager, pagingStore);
       
       //Expect:
       
       sm.storeAcknowledgeTransactional(txID, queue1.getPersistenceID(), message1.getMessageID());
       sm.storeDeleteMessageTransactional(txID, queue2.getPersistenceID(), message1.getMessageID());
       
-      EasyMock.replay(sm);
+      EasyMock.replay(sm, postOffice, pagingManager, pagingStore);
       
       tx.addAcknowledgement(ref3);
       
@@ -603,35 +617,39 @@
       
       assertEquals(3, tx.getAcknowledgementsCount());
       
-      EasyMock.verify(sm);
+      EasyMock.verify(sm, postOffice, pagingManager, pagingStore);
       
-      EasyMock.reset(sm);
+      EasyMock.reset(sm, postOffice, pagingManager, pagingStore);
       
       //Expect:
       
       //Nothing
       
-      EasyMock.replay(sm);
+      EasyMock.replay(sm, postOffice, pagingManager, pagingStore);
       
       tx.addAcknowledgement(ref4);
       
       assertEquals(4, tx.getAcknowledgementsCount());
       
-      EasyMock.verify(sm);
+      EasyMock.verify(sm, postOffice, pagingManager, pagingStore);
       
-      EasyMock.reset(sm);
+      EasyMock.reset(sm, postOffice, pagingManager, pagingStore);
       
       //Expect:
       
       sm.commit(txID);
       
-      EasyMock.replay(sm);
+      pagingManager.messageDone(message1);
       
+      pagingManager.messageDone(message2);
+      
+      EasyMock.replay(sm, postOffice, pagingManager, pagingStore);
+      
       tx.commit();
       
-      EasyMock.verify(sm);
+      EasyMock.verify(sm, postOffice, pagingManager, pagingStore);
       
-      EasyMock.reset(sm);            
+      EasyMock.reset(sm, postOffice, pagingManager, pagingStore);            
       
       //TODO test messages are routed and refs count reduced
    }

Added: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/util/ServiceTestBase.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/util/ServiceTestBase.java	                        (rev 0)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/util/ServiceTestBase.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -0,0 +1,227 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+
+package org.jboss.messaging.tests.util;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.jboss.messaging.core.client.ClientMessage;
+import org.jboss.messaging.core.client.ClientSession;
+import org.jboss.messaging.core.client.ClientSessionFactory;
+import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
+import org.jboss.messaging.core.config.Configuration;
+import org.jboss.messaging.core.config.TransportConfiguration;
+import org.jboss.messaging.core.config.impl.ConfigurationImpl;
+import org.jboss.messaging.core.remoting.impl.invm.InVMAcceptorFactory;
+import org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory;
+import org.jboss.messaging.core.remoting.impl.netty.NettyAcceptorFactory;
+import org.jboss.messaging.core.remoting.impl.netty.NettyConnectorFactory;
+import org.jboss.messaging.core.server.MessagingService;
+import org.jboss.messaging.core.server.impl.MessagingServiceImpl;
+import org.jboss.messaging.core.settings.impl.QueueSettings;
+import org.jboss.messaging.jms.client.JBossBytesMessage;
+import org.jboss.messaging.jms.client.JBossTextMessage;
+
+/**
+ * 
+ * Base class with basic utilities on starting up a basic server
+ * 
+ * @author <a href="mailto:clebert.suconic at jboss.com">Clebert Suconic</a>
+ *
+ */
+public class ServiceTestBase extends UnitTestCase
+{
+
+   // Constants -----------------------------------------------------
+
+   // Attributes ----------------------------------------------------
+
+   protected static final String INVM_ACCEPTOR_FACTORY = InVMAcceptorFactory.class.getCanonicalName();
+
+   protected static final String INVM_CONNECTOR_FACTORY = InVMConnectorFactory.class.getCanonicalName();
+
+   protected static final String NETTY_ACCEPTOR_FACTORY = NettyAcceptorFactory.class.getCanonicalName();
+
+   protected static final String NETTY_CONNECTOR_FACTORY = NettyConnectorFactory.class.getCanonicalName();
+
+   protected String journalDir = System.getProperty("java.io.tmpdir", "/tmp") + "/unit-test/journal";
+
+   protected String bindingsDir = System.getProperty("java.io.tmpdir", "/tmp") + "/unit-test/bindings";
+
+   protected String pageDir = System.getProperty("java.io.tmpdir", "/tmp") + "/unit-test/page";
+
+   protected String largeMessagesDir = System.getProperty("java.io.tmpdir", "/tmp") + "/unit-test/large-msg";
+
+   protected String clientLargeMessagesDir = System.getProperty("java.io.tmpdir", "/tmp") + "/unit-test/client-large-msg";
+
+   protected String temporaryDir = System.getProperty("java.io.tmpdir", "/tmp") + "/unit-test/temporary";
+
+   protected MessagingService messagingService;
+
+   // Static --------------------------------------------------------
+
+   // Constructors --------------------------------------------------
+
+   // Public --------------------------------------------------------
+
+   // Package protected ---------------------------------------------
+
+   // Protected -----------------------------------------------------
+
+   protected void clearData()
+   {
+      deleteAndCreateDir(journalDir);
+      deleteAndCreateDir(bindingsDir);
+      deleteAndCreateDir(pageDir);
+      deleteAndCreateDir(largeMessagesDir);
+      deleteAndCreateDir(clientLargeMessagesDir);
+      deleteAndCreateDir(temporaryDir);
+   }
+
+   protected void deleteAndCreateDir(String directory)
+   {
+      File file = new File(directory);
+      deleteDirectory(file);
+      file.mkdirs();
+   }
+
+   protected MessagingService createService(final boolean realFiles,
+                                            final Configuration configuration,
+                                            final Map<String, QueueSettings> settings)
+   {
+
+      MessagingService service;
+
+      if (realFiles)
+      {
+         service = MessagingServiceImpl.newNioStorageMessagingServer(configuration,
+                                                                     journalDir,
+                                                                     bindingsDir,
+                                                                     largeMessagesDir);
+      }
+      else
+      {
+         service = MessagingServiceImpl.newNullStorageMessagingServer(configuration);
+      }
+
+      for (Map.Entry<String, QueueSettings> setting : settings.entrySet())
+      {
+         service.getServer().getQueueSettingsRepository().addMatch(setting.getKey(), setting.getValue());
+      }
+
+      return service;
+   }
+
+   protected MessagingService createService(final boolean realFiles)
+   {
+      return createService(realFiles, createDefaultConfig(), new HashMap<String, QueueSettings>());
+   }
+
+   protected Configuration createDefaultConfig()
+   {
+      return createDefaultConfig(false);
+   }
+
+   
+   protected Configuration createDefaultConfig(final boolean netty)
+   {
+      if (netty)
+      {
+         return createDefaultConfig(INVM_ACCEPTOR_FACTORY, NETTY_ACCEPTOR_FACTORY);
+      }
+      else
+      {
+         return createDefaultConfig(INVM_ACCEPTOR_FACTORY);
+      }
+      
+   }
+
+   protected Configuration createDefaultConfig(final String... acceptors)
+   {
+      Configuration configuration = new ConfigurationImpl();
+      configuration.setSecurityEnabled(false);
+      configuration.setJournalMinFiles(2);
+      configuration.setJournalFileSize(100 * 1024);
+      configuration.setPagingDirectory(pageDir);
+
+      configuration.getAcceptorConfigurations().clear();
+
+      for (String acceptor : acceptors)
+      {
+         TransportConfiguration transportConfig = new TransportConfiguration(acceptor);
+         configuration.getAcceptorConfigurations().add(transportConfig);
+      }
+
+      return configuration;
+   }
+
+   protected ClientSessionFactory createInVMFactory()
+   {
+      return createFactory(INVM_CONNECTOR_FACTORY);
+   }
+
+   protected ClientSessionFactory createNettyFactory()
+   {
+      return createFactory(NETTY_CONNECTOR_FACTORY);
+   }
+
+   protected ClientSessionFactory createFactory(final String connectorClass)
+   {
+      return new ClientSessionFactoryImpl(new TransportConfiguration(connectorClass));
+   }
+
+   protected ClientMessage createTextMessage(final ClientSession session, final String s)
+   {
+      return createTextMessage(session, s, true);
+   }
+
+   protected ClientMessage createTextMessage(final ClientSession session, final String s, final boolean durable)
+   {
+      ClientMessage message = session.createClientMessage(JBossTextMessage.TYPE,
+                                                          durable,
+                                                          0,
+                                                          System.currentTimeMillis(),
+                                                          (byte)1);
+      message.getBody().putString(s);
+      message.getBody().flip();
+      return message;
+   }
+
+   protected ClientMessage createBytesMessage(final ClientSession session, final byte[] b, final boolean durable)
+   {
+      ClientMessage message = session.createClientMessage(JBossBytesMessage.TYPE,
+                                                          durable,
+                                                          0,
+                                                          System.currentTimeMillis(),
+                                                          (byte)1);
+      message.getBody().putBytes(b);
+      message.getBody().flip();
+      return message;
+   }
+
+   // Private -------------------------------------------------------
+
+   // Inner classes -------------------------------------------------
+
+}

Modified: branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/util/UnitTestCase.java
===================================================================
--- branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/util/UnitTestCase.java	2008-10-27 16:42:42 UTC (rev 5182)
+++ branches/Branch_Chunk_CRS2/tests/src/org/jboss/messaging/tests/util/UnitTestCase.java	2008-10-27 16:51:46 UTC (rev 5183)
@@ -87,6 +87,33 @@
       return buff.toString();      
    }
    
+   
+   public static String dumbBytesHex(final byte[] buffer, int bytesPerLine)
+   {
+
+      StringBuffer buff = new StringBuffer();
+
+      buff.append("[");
+
+      for (int i = 0; i < buffer.length; i++)
+      {
+         buff.append(String.format("%1$2X", buffer[i]));
+         if (i + 1 < buffer.length) 
+         {
+            buff.append(", ");
+         }
+         if ((i + 1) % bytesPerLine == 0)
+         {
+            buff.append("\n ");
+         }
+      }
+      buff.append("]");
+      
+      return buff.toString();
+   }
+
+
+   
    public static void assertEqualsByteArrays(byte[] expected, byte[] actual)
    {
       assertEquals(expected.length, actual.length);




More information about the jboss-cvs-commits mailing list