You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@qpid.apache.org by lq...@apache.org on 2017/10/18 15:21:35 UTC

[01/10] qpid-broker-j git commit: QPID-7832: [Java Broker] Refactor store/protocol API using Collection

Repository: qpid-broker-j
Updated Branches:
  refs/heads/master 955a79b7d -> 660c206de


http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/Utils.java
----------------------------------------------------------------------
diff --git a/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/Utils.java b/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/Utils.java
index 7fa98c5..a0eab61 100644
--- a/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/Utils.java
+++ b/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/Utils.java
@@ -21,10 +21,8 @@
 package org.apache.qpid.tests.protocol.v1_0;
 
 import java.net.InetSocketAddress;
-import java.util.List;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.UnsignedInteger;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.Header;
 import org.apache.qpid.server.protocol.v1_0.type.transport.Attach;
@@ -94,41 +92,27 @@ public class Utils
         final Header header = new Header();
         messageEncoder.setHeader(header);
         messageEncoder.addData(messageContent);
-        List<QpidByteBuffer> payload = messageEncoder.getPayload();
-        long size = QpidByteBufferUtils.remaining(payload);
-
-        QpidByteBuffer[] result = new QpidByteBuffer[numberOfParts];
-        int chunkSize = (int) size / numberOfParts;
-        int lastChunkSize = (int) size - chunkSize * (numberOfParts - 1);
-        for (int i = 0; i < numberOfParts; i++)
-        {
-            result[i] = QpidByteBuffer.allocate(false, i == numberOfParts - 1 ? lastChunkSize : chunkSize);
-        }
-
-        int currentBufferIndex = 0;
-        for (QpidByteBuffer p : payload)
+        final QpidByteBuffer[] result;
+        try (QpidByteBuffer payload = messageEncoder.getPayload())
         {
-            final int limit = p.limit();
+            long size = (long) payload.remaining();
 
-            while (p.hasRemaining())
+            result = new QpidByteBuffer[numberOfParts];
+            int chunkSize = (int) size / numberOfParts;
+            int lastChunkSize = (int) size - chunkSize * (numberOfParts - 1);
+            for (int i = 0; i < numberOfParts; i++)
             {
-                QpidByteBuffer currentBuffer = result[currentBufferIndex];
-                if (currentBuffer.hasRemaining())
+                result[i] = QpidByteBuffer.allocate(false, i == numberOfParts - 1 ? lastChunkSize : chunkSize);
+                final int remaining = result[i].remaining();
+                try (QpidByteBuffer view = payload.view(0, remaining))
                 {
-                    int length = Math.min(p.remaining(), currentBuffer.remaining());
-                    p.limit(p.position() + length);
-                    currentBuffer.put(p.slice());
-                    p.position(p.position() + length);
-                    p.limit(limit);
-                }
-
-                if (!currentBuffer.hasRemaining())
-                {
-                    currentBuffer.flip();
-                    currentBufferIndex++;
+                    result[i].put(view);
                 }
+                result[i].flip();
+                payload.position(payload.position() + remaining);
             }
         }
+
         return result;
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/DecodeErrorTest.java
----------------------------------------------------------------------
diff --git a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/DecodeErrorTest.java b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/DecodeErrorTest.java
index 8cc6f92..8a150fa 100644
--- a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/DecodeErrorTest.java
+++ b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/DecodeErrorTest.java
@@ -77,34 +77,39 @@ public class DecodeErrorTest extends BrokerAdminUsingTestBase
         try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
         {
 
-            List<QpidByteBuffer> combinedPayload = new ArrayList<>();
+            List<QpidByteBuffer> payloads = new ArrayList<>();
             final HeaderSection headerSection = new Header().createEncodingRetainingSection();
-            combinedPayload.addAll(headerSection.getEncodedForm());
+            payloads.add(headerSection.getEncodedForm());
             headerSection.dispose();
             final StringWriter stringWriter = new StringWriter("string in between annotation sections");
             QpidByteBuffer encodedString = QpidByteBuffer.allocate(stringWriter.getEncodedSize());
             stringWriter.writeToBuffer(encodedString);
             encodedString.flip();
-            combinedPayload.add(encodedString);
+            payloads.add(encodedString);
             final DeliveryAnnotationsSection
                     deliveryAnnotationsSection =
                     new DeliveryAnnotations(Collections.emptyMap()).createEncodingRetainingSection();
-            combinedPayload.addAll(deliveryAnnotationsSection.getEncodedForm());
+            payloads.add(deliveryAnnotationsSection.getEncodedForm());
             deliveryAnnotationsSection.dispose();
 
-            final Detach detachResponse = transport.newInteraction()
-                                                   .negotiateProtocol().consumeResponse()
-                                                   .open().consumeResponse(Open.class)
-                                                   .begin().consumeResponse(Begin.class)
-                                                   .attachRole(Role.SENDER)
-                                                   .attachTargetAddress(BrokerAdmin.TEST_QUEUE_NAME)
-                                                   .attach().consumeResponse(Attach.class)
-                                                   .consumeResponse(Flow.class)
-                                                   .transferMessageFormat(UnsignedInteger.ZERO)
-                                                   .transferPayload(combinedPayload)
-                                                   .transfer()
-                                                   .consumeResponse()
-                                                   .getLatestResponse(Detach.class);
+            final Detach detachResponse;
+            try (QpidByteBuffer combinedPayload = QpidByteBuffer.concatenate(payloads))
+            {
+                detachResponse = transport.newInteraction()
+                                          .negotiateProtocol().consumeResponse()
+                                          .open().consumeResponse(Open.class)
+                                          .begin().consumeResponse(Begin.class)
+                                          .attachRole(Role.SENDER)
+                                          .attachTargetAddress(BrokerAdmin.TEST_QUEUE_NAME)
+                                          .attach().consumeResponse(Attach.class)
+                                          .consumeResponse(Flow.class)
+                                          .transferMessageFormat(UnsignedInteger.ZERO)
+                                          .transferPayload(combinedPayload)
+                                          .transfer()
+                                          .consumeResponse()
+                                          .getLatestResponse(Detach.class);
+            }
+            payloads.forEach(QpidByteBuffer::dispose);
             assertThat(detachResponse.getError(), is(notNullValue()));
             assertThat(detachResponse.getError().getCondition(), is(equalTo(DECODE_ERROR)));
         }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/MessageFormat.java
----------------------------------------------------------------------
diff --git a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/MessageFormat.java b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/MessageFormat.java
index 6a373d1..97fe3bb 100644
--- a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/MessageFormat.java
+++ b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/MessageFormat.java
@@ -26,7 +26,6 @@ import static org.hamcrest.Matchers.is;
 import static org.junit.Assert.fail;
 
 import java.net.InetSocketAddress;
-import java.util.Collections;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -83,18 +82,22 @@ public class MessageFormat extends BrokerAdminUsingTestBase
                                                         .consumeResponse(Flow.class)
                                                         .transferMore(true)
                                                         .transferMessageFormat(UnsignedInteger.ZERO)
-                                                        .transferPayload(Collections.singletonList(payloads[0]))
+                                                        .transferPayload(payloads[0])
                                                         .transfer()
                                                         .consumeResponse(null, Flow.class, Disposition.class)
                                                         .transferDeliveryTag(null)
                                                         .transferDeliveryId(null)
                                                         .transferMore(false)
                                                         .transferMessageFormat(UnsignedInteger.ONE)
-                                                        .transferPayload(Collections.singletonList(payloads[1]))
+                                                        .transferPayload(payloads[1])
                                                         .transfer()
                                                         .consumeResponse(Detach.class, End.class, Close.class)
                                                         .getLatestResponse();
 
+            for (final QpidByteBuffer payload : payloads)
+            {
+                payload.dispose();
+            }
             assertThat(latestResponse, is(notNullValue()));
             final Object responseBody = latestResponse.getBody();
             final Error error;

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/MultiTransferTest.java
----------------------------------------------------------------------
diff --git a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/MultiTransferTest.java b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/MultiTransferTest.java
index 5c7a7f5..bcd155f 100644
--- a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/MultiTransferTest.java
+++ b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/MultiTransferTest.java
@@ -29,7 +29,6 @@ import static org.hamcrest.Matchers.is;
 import static org.hamcrest.Matchers.isOneOf;
 
 import java.net.InetSocketAddress;
-import java.util.Collections;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -51,13 +50,13 @@ import org.apache.qpid.server.protocol.v1_0.type.transport.Flow;
 import org.apache.qpid.server.protocol.v1_0.type.transport.Open;
 import org.apache.qpid.server.protocol.v1_0.type.transport.ReceiverSettleMode;
 import org.apache.qpid.server.protocol.v1_0.type.transport.Role;
-import org.apache.qpid.tests.utils.BrokerAdmin;
 import org.apache.qpid.tests.protocol.v1_0.FrameTransport;
 import org.apache.qpid.tests.protocol.v1_0.Interaction;
-import org.apache.qpid.tests.utils.BrokerAdminUsingTestBase;
 import org.apache.qpid.tests.protocol.v1_0.Response;
 import org.apache.qpid.tests.protocol.v1_0.SpecificationTest;
 import org.apache.qpid.tests.protocol.v1_0.Utils;
+import org.apache.qpid.tests.utils.BrokerAdmin;
+import org.apache.qpid.tests.utils.BrokerAdminUsingTestBase;
 
 public class MultiTransferTest extends BrokerAdminUsingTestBase
 {
@@ -111,18 +110,22 @@ public class MultiTransferTest extends BrokerAdminUsingTestBase
                                                  .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL)
                                                  .attach().consumeResponse(Attach.class)
                                                  .consumeResponse(Flow.class)
-                                                 .transferPayload(Collections.singletonList(payloads[0]))
+                                                 .transferPayload(payloads[0])
                                                  .transferDeliveryId(deliveryId)
                                                  .transferDeliveryTag(deliveryTag)
                                                  .transferMore(true)
                                                  .transfer()
                                                  .sync()
                                                  .transferMore(false)
-                                                 .transferPayload(Collections.singletonList(payloads[1]))
+                                                 .transferPayload(payloads[1])
                                                  .transfer()
                                                  .consumeResponse()
                                                  .getLatestResponse(Disposition.class);
 
+            for (final QpidByteBuffer payload : payloads)
+            {
+                payload.dispose();
+            }
             assertThat(disposition.getFirst(), is(equalTo(deliveryId)));
             assertThat(disposition.getLast(), isOneOf(null, deliveryId));
             assertThat(disposition.getSettled(), is(equalTo(false)));
@@ -155,30 +158,34 @@ public class MultiTransferTest extends BrokerAdminUsingTestBase
                        .transferDeliveryId(deliveryId)
                        .transferDeliveryTag(deliveryTag)
                        .transferMore(true)
-                       .transferPayload(Collections.singletonList(payloads[0]))
+                       .transferPayload(payloads[0])
                        .transfer()
                        .sync()
                        .transferDeliveryId(deliveryId)
                        .transferDeliveryTag(null)
                        .transferMore(true)
-                       .transferPayload(Collections.singletonList(payloads[1]))
+                       .transferPayload(payloads[1])
                        .transfer()
                        .sync()
                        .transferDeliveryId(null)
                        .transferDeliveryTag(deliveryTag)
                        .transferMore(true)
-                       .transferPayload(Collections.singletonList(payloads[2]))
+                       .transferPayload(payloads[2])
                        .transfer()
                        .sync()
                        .transferDeliveryId(null)
                        .transferDeliveryTag(null)
                        .transferMore(false)
-                       .transferPayload(Collections.singletonList(payloads[3]))
+                       .transferPayload(payloads[3])
                        .transfer()
                        .consumeResponse();
 
             Disposition disposition = interaction.getLatestResponse(Disposition.class);
 
+            for (final QpidByteBuffer payload : payloads)
+            {
+                payload.dispose();
+            }
             assertThat(disposition.getFirst(), is(equalTo(deliveryId)));
             assertThat(disposition.getLast(), isOneOf(null, deliveryId));
             assertThat(disposition.getSettled(), is(equalTo(false)));
@@ -212,7 +219,7 @@ public class MultiTransferTest extends BrokerAdminUsingTestBase
                        .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL)
                        .attach().consumeResponse(Attach.class)
                        .consumeResponse(Flow.class)
-                       .transferPayload(Collections.singletonList(payloads[0]))
+                       .transferPayload(payloads[0])
                        .transferDeliveryId(deliveryId)
                        .transferDeliveryTag(deliveryTag)
                        .transferMore(true)
@@ -223,6 +230,10 @@ public class MultiTransferTest extends BrokerAdminUsingTestBase
                        .transferAborted(true)
                        .transfer();
 
+            for (final QpidByteBuffer payload : payloads)
+            {
+                payload.dispose();
+            }
             Response<?> latestResponse = interaction.consumeResponse(new Class<?>[] {null}).getLatestResponse();
             assertThat(latestResponse, is(nullValue()));
         }
@@ -272,7 +283,7 @@ public class MultiTransferTest extends BrokerAdminUsingTestBase
                        .transferDeliveryId(deliverId1)
                        .transferDeliveryTag(deliveryTag1)
                        .transferMore(true)
-                       .transferPayload(Collections.singletonList(messagePayload1[0]))
+                       .transferPayload(messagePayload1[0])
                        .transfer()
                        .sync()
 
@@ -280,7 +291,7 @@ public class MultiTransferTest extends BrokerAdminUsingTestBase
                        .transferDeliveryId(deliveryId2)
                        .transferDeliveryTag(deliveryTag2)
                        .transferMore(true)
-                       .transferPayload(Collections.singletonList(messagePayload2[0]))
+                       .transferPayload(messagePayload2[0])
                        .transfer()
                        .sync()
 
@@ -288,7 +299,7 @@ public class MultiTransferTest extends BrokerAdminUsingTestBase
                        .transferDeliveryId(deliverId1)
                        .transferDeliveryTag(deliveryTag1)
                        .transferMore(false)
-                       .transferPayload(Collections.singletonList(messagePayload1[1]))
+                       .transferPayload(messagePayload1[1])
                        .transfer()
                        .sync()
 
@@ -296,10 +307,19 @@ public class MultiTransferTest extends BrokerAdminUsingTestBase
                        .transferDeliveryId(deliveryId2)
                        .transferDeliveryTag(deliveryTag2)
                        .transferMore(false)
-                       .transferPayload(Collections.singletonList(messagePayload2[1]))
+                       .transferPayload(messagePayload2[1])
                        .transfer()
                        .sync();
 
+            for (final QpidByteBuffer payload : messagePayload1)
+            {
+                payload.dispose();
+            }
+            for (final QpidByteBuffer payload : messagePayload2)
+            {
+                payload.dispose();
+            }
+
             Map<UnsignedInteger, Disposition> dispositionMap = new HashMap<>();
             for (int i = 0; i < 2; i++)
             {
@@ -349,16 +369,24 @@ public class MultiTransferTest extends BrokerAdminUsingTestBase
                        .transferDeliveryId(deliverId1)
                        .transferDeliveryTag(deliveryTag1)
                        .transferMore(true)
-                       .transferPayload(Collections.singletonList(messagePayload1[0]))
+                       .transferPayload(messagePayload1[0])
                        .transfer()
                        .sync()
 
                        .transferDeliveryId(deliveryId2)
                        .transferDeliveryTag(deliveryTag2)
                        .transferMore(true)
-                       .transferPayload(Collections.singletonList(messagePayload2[0]))
+                       .transferPayload(messagePayload2[0])
                        .transfer()
                        .sync();
+            for (final QpidByteBuffer payload : messagePayload1)
+            {
+                payload.dispose();
+            }
+            for (final QpidByteBuffer payload : messagePayload2)
+            {
+                payload.dispose();
+            }
 
             interaction.consumeResponse(Detach.class, End.class, Close.class);
         }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/OutcomeTest.java
----------------------------------------------------------------------
diff --git a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/OutcomeTest.java b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/OutcomeTest.java
index f081006..1853446 100644
--- a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/OutcomeTest.java
+++ b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/OutcomeTest.java
@@ -94,7 +94,6 @@ public class OutcomeTest extends BrokerAdminUsingTestBase
                        .flow()
                        .receiveDelivery()
                        .decodeLatestDelivery();
-            ;
 
             Object secondDeliveryPayload = interaction.getDecodedLatestDelivery();
             assertThat(secondDeliveryPayload, is(equalTo("message2")));

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/TransferTest.java
----------------------------------------------------------------------
diff --git a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/TransferTest.java b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/TransferTest.java
index 5ce5e5d..eb72532 100644
--- a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/TransferTest.java
+++ b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/messaging/TransferTest.java
@@ -47,7 +47,7 @@ import org.junit.Before;
 import org.junit.Ignore;
 import org.junit.Test;
 
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
+import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.type.Binary;
 import org.apache.qpid.server.protocol.v1_0.type.ErrorCarryingFrameBody;
 import org.apache.qpid.server.protocol.v1_0.type.Outcome;
@@ -618,7 +618,11 @@ public class TransferTest extends BrokerAdminUsingTestBase
             assertThat(first.getMore(), is(equalTo(true)));
             messageDecoder.addTransfer(first);
 
-            final long firstRemaining = QpidByteBufferUtils.remaining(first.getPayload());
+            final long firstRemaining;
+            try (QpidByteBuffer payload = first.getPayload())
+            {
+                firstRemaining = payload.remaining();
+            }
 
             Received state = new Received();
             state.setSectionNumber(UnsignedInteger.ZERO);

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/transport/link/ResumeDeliveriesTest.java
----------------------------------------------------------------------
diff --git a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/transport/link/ResumeDeliveriesTest.java b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/transport/link/ResumeDeliveriesTest.java
index 5769255..35ee4e7 100644
--- a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/transport/link/ResumeDeliveriesTest.java
+++ b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/transport/link/ResumeDeliveriesTest.java
@@ -67,13 +67,13 @@ import org.apache.qpid.server.protocol.v1_0.type.transport.ReceiverSettleMode;
 import org.apache.qpid.server.protocol.v1_0.type.transport.Role;
 import org.apache.qpid.server.protocol.v1_0.type.transport.SenderSettleMode;
 import org.apache.qpid.server.protocol.v1_0.type.transport.Transfer;
-import org.apache.qpid.tests.utils.BrokerAdmin;
 import org.apache.qpid.tests.protocol.v1_0.FrameTransport;
 import org.apache.qpid.tests.protocol.v1_0.Interaction;
-import org.apache.qpid.tests.utils.BrokerAdminUsingTestBase;
 import org.apache.qpid.tests.protocol.v1_0.Response;
 import org.apache.qpid.tests.protocol.v1_0.SpecificationTest;
 import org.apache.qpid.tests.protocol.v1_0.Utils;
+import org.apache.qpid.tests.utils.BrokerAdmin;
+import org.apache.qpid.tests.utils.BrokerAdminUsingTestBase;
 
 public class ResumeDeliveriesTest extends BrokerAdminUsingTestBase
 {
@@ -715,7 +715,7 @@ public class ResumeDeliveriesTest extends BrokerAdminUsingTestBase
                        .transferDeliveryId(UnsignedInteger.ZERO)
                        .transferDeliveryTag(deliveryTag)
                        .transferMore(true)
-                       .transferPayload(Collections.singletonList(messagePayload[0]))
+                       .transferPayload(messagePayload[0])
                        .transfer();
 
             // 3. detach the link
@@ -740,9 +740,14 @@ public class ResumeDeliveriesTest extends BrokerAdminUsingTestBase
                        .transfer()
                        .sync()
                        .transferMore(false)
-                       .transferPayload(Collections.singletonList(messagePayload[1]))
+                       .transferPayload(messagePayload[1])
                        .transfer();
 
+            for (final QpidByteBuffer payload : messagePayload)
+            {
+                payload.dispose();
+            }
+
             boolean settled = false;
             do
             {

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/systests/src/test/java/org/apache/qpid/transport/ProtocolNegotiationTest.java
----------------------------------------------------------------------
diff --git a/systests/src/test/java/org/apache/qpid/transport/ProtocolNegotiationTest.java b/systests/src/test/java/org/apache/qpid/transport/ProtocolNegotiationTest.java
index b06eb3e..d27eb1b 100644
--- a/systests/src/test/java/org/apache/qpid/transport/ProtocolNegotiationTest.java
+++ b/systests/src/test/java/org/apache/qpid/transport/ProtocolNegotiationTest.java
@@ -310,6 +310,7 @@ public class ProtocolNegotiationTest extends QpidBrokerTestCase
             ConnectionHeartbeat heartbeat = new ConnectionHeartbeat();
             ServerDisassembler serverDisassembler = new ServerDisassembler(sender, Frame.HEADER_SIZE + 1);
             serverDisassembler.command(null, heartbeat);
+            serverDisassembler.closed();
         }
         else if(isBrokerPre010())
         {


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[09/10] qpid-broker-j git commit: QPID-7832: [Java Broker] Refactor store/protocol API using Collection

Posted by lq...@apache.org.
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBuffer.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBuffer.java b/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBuffer.java
index 346e203..6f293dc 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBuffer.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBuffer.java
@@ -27,14 +27,16 @@ import java.nio.BufferOverflowException;
 import java.nio.BufferUnderflowException;
 import java.nio.ByteBuffer;
 import java.nio.CharBuffer;
+import java.nio.InvalidMarkException;
 import java.nio.channels.GatheringByteChannel;
-import java.nio.channels.ReadableByteChannel;
+import java.nio.channels.ScatteringByteChannel;
 import java.nio.charset.Charset;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
+import java.util.LinkedList;
 import java.util.List;
+import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
 import java.util.zip.GZIPInputStream;
 import java.util.zip.GZIPOutputStream;
@@ -43,68 +45,144 @@ import javax.net.ssl.SSLEngine;
 import javax.net.ssl.SSLEngineResult;
 import javax.net.ssl.SSLException;
 
-import org.apache.qpid.server.streams.CompositeInputStream;
+import com.google.common.primitives.Chars;
+import com.google.common.primitives.Ints;
+import com.google.common.primitives.Longs;
+import com.google.common.primitives.Shorts;
 
 public class QpidByteBuffer implements AutoCloseable
 {
-    private static final AtomicIntegerFieldUpdater<QpidByteBuffer>
-            DISPOSED_UPDATER = AtomicIntegerFieldUpdater.newUpdater(
-            QpidByteBuffer.class,
-            "_disposed");
-
-    private static final ThreadLocal<QpidByteBuffer> _cachedBuffer = new ThreadLocal<>();
     private static final ByteBuffer[] EMPTY_BYTE_BUFFER_ARRAY = new ByteBuffer[0];
-    private static final double REALLOCATION_CAPACITY_THRESHOLD_FRACTION = 0.9;
+    private static final QpidByteBuffer EMPTY_QPID_BYTE_BUFFER = QpidByteBuffer.wrap(new byte[0]);
+    private static final ThreadLocal<QpidByteBufferFragment> _cachedBuffer = new ThreadLocal<>();
     private volatile static boolean _isPoolInitialized;
     private volatile static BufferPool _bufferPool;
     private volatile static int _pooledBufferSize;
-    private volatile static ByteBuffer _zeroed;
     private volatile static double _sparsityFraction;
-    private final int _offset;
+    private volatile static ByteBuffer _zeroed;
+    private volatile List<QpidByteBufferFragment> _fragments = new ArrayList<>();
+    private volatile int _resetFragmentIndex = -1;
 
-    final ByteBufferRef _ref;
-    volatile ByteBuffer _buffer;
-    @SuppressWarnings("unused")
-    private volatile int _disposed;
+    //////////////////
+    // Absolute puts
+    //////////////////
 
+    public QpidByteBuffer put(final int index, final byte b)
+    {
+        return put(index, new byte[]{b});
+    }
 
-    QpidByteBuffer(ByteBufferRef ref)
+    public QpidByteBuffer putShort(final int index, final short value)
     {
-        this(ref, ref.getBuffer(), 0);
+        byte[] valueArray = Shorts.toByteArray(value);
+        return put(index, valueArray);
     }
 
-    private QpidByteBuffer(ByteBufferRef ref, ByteBuffer buffer, int offset)
+    public QpidByteBuffer putChar(final int index, final char value)
     {
-        _ref = ref;
-        _buffer = buffer;
-        _offset = offset;
-        _ref.incrementRef(capacity());
+        byte[] valueArray = Chars.toByteArray(value);
+        return put(index, valueArray);
     }
 
-    public final boolean isDirect()
+    public QpidByteBuffer putInt(final int index, final int value)
     {
-        return _buffer.isDirect();
+        byte[] valueArray = Ints.toByteArray(value);
+        return put(index, valueArray);
     }
 
-    public final short getUnsignedByte()
+    public QpidByteBuffer putLong(final int index, final long value)
     {
-        return (short) (((short) get()) & 0xFF);
+        byte[] valueArray = Longs.toByteArray(value);
+        return put(index, valueArray);
     }
 
-    public final int getUnsignedShort()
+    public QpidByteBuffer putFloat(final int index, final float value)
     {
-        return ((int) getShort()) & 0xffff;
+        int intValue = Float.floatToRawIntBits(value);
+        return putInt(index, intValue);
     }
 
-    public final int getUnsignedShort(int pos)
+    public QpidByteBuffer putDouble(final int index, final double value)
     {
-        return ((int) getShort(pos)) & 0xffff;
+        long longValue = Double.doubleToRawLongBits(value);
+        return putLong(index, longValue);
     }
 
+    public final QpidByteBuffer put(final int index, final byte[] src)
+    {
+        final int valueWidth = src.length;
+        if (index < 0 || index + valueWidth > limit())
+        {
+            throw new IndexOutOfBoundsException(String.format("index %d is out of bounds [%d, %d)", index, 0, limit()));
+        }
+        boolean bytewise = false;
+        int written = 0;
+        int bytesToSkip = index;
+        for (int i = 0, size = _fragments.size(); i < size; i++)
+        {
+            final QpidByteBufferFragment buffer = _fragments.get(i);
+            final int limit = buffer.limit();
+            boolean isLastFragmentToConsider = valueWidth + bytesToSkip - written <= limit;
+            if (!isLastFragmentToConsider && limit != buffer.capacity())
+            {
+                throw new IllegalStateException(String.format("Unexpected limit %d on fragment %d", limit, i));
+            }
 
-    public final long getUnsignedInt()
+            if (bytewise)
+            {
+                int offset = 0;
+                while (limit > offset && written < valueWidth)
+                {
+                    buffer.put(offset, src[written]);
+                    offset++;
+                    written++;
+                }
+                if (written == valueWidth)
+                {
+                    break;
+                }
+            }
+            else
+            {
+                if (limit >= bytesToSkip + valueWidth)
+                {
+                    for (int i1 = 0; i1 < valueWidth; i1++)
+                    {
+                        buffer.put(bytesToSkip + i1, src[i1]);
+                        written++;
+                    }
+                    break;
+                }
+                else if (limit > bytesToSkip)
+                {
+                    bytewise = true;
+                    while (limit > bytesToSkip + written)
+                    {
+                        buffer.put(bytesToSkip + written, src[written]);
+                        written++;
+                    }
+                    bytesToSkip = 0;
+                }
+                else
+                {
+                    bytesToSkip -= limit;
+                }
+            }
+        }
+        if (valueWidth != written)
+        {
+            throw new BufferOverflowException();
+        }
+        return this;
+    }
+
+    ////////////////
+    // Relative Puts
+    ////////////////
+
+    public final QpidByteBuffer put(final byte b)
     {
-        return ((long) getInt()) & 0xffffffffL;
+        return put(new byte[]{b});
     }
 
     public final QpidByteBuffer putUnsignedByte(final short s)
@@ -113,224 +191,493 @@ public class QpidByteBuffer implements AutoCloseable
         return this;
     }
 
+    public final QpidByteBuffer putShort(final short value)
+    {
+        byte[] valueArray = Shorts.toByteArray(value);
+        return put(valueArray);
+    }
+
     public final QpidByteBuffer putUnsignedShort(final int i)
     {
         putShort((short) i);
         return this;
     }
 
+    public final QpidByteBuffer putChar(final char value)
+    {
+        byte[] valueArray = Chars.toByteArray(value);
+        return put(valueArray);
+    }
+
+    public final QpidByteBuffer putInt(final int value)
+    {
+        byte[] valueArray = Ints.toByteArray(value);
+        return put(valueArray);
+    }
+
     public final QpidByteBuffer putUnsignedInt(final long value)
     {
         putInt((int) value);
         return this;
     }
 
-    @Override
-    public final void close()
+    public final QpidByteBuffer putLong(final long value)
     {
-        dispose();
+        byte[] valueArray = Longs.toByteArray(value);
+        return put(valueArray);
     }
 
-    public final void dispose()
+    public final QpidByteBuffer putFloat(final float value)
     {
-        if (DISPOSED_UPDATER.compareAndSet(this, 0, 1))
-        {
-            _ref.decrementRef(capacity());
-            _buffer = null;
-        }
+        int intValue = Float.floatToRawIntBits(value);
+        return putInt(intValue);
     }
 
-    public final InputStream asInputStream()
+    public final QpidByteBuffer putDouble(final double value)
     {
-        return new BufferInputStream(this);
+        long longValue = Double.doubleToRawLongBits(value);
+        return putLong(longValue);
     }
 
-    public final ByteBuffer asByteBuffer()
+    public final QpidByteBuffer put(byte[] src)
     {
-        try
+        return put(src, 0, src.length);
+    }
+
+    public final QpidByteBuffer put(final byte[] src, final int offset, final int length)
+    {
+        final int valueWidth = length;
+        if (valueWidth > remaining())
         {
-            return getUnderlyingBuffer();
+            throw new BufferOverflowException();
         }
-        finally
+        boolean bytewise = false;
+        int written = 0;
+        for (int i = 0, size = _fragments.size(); i < size; i++)
         {
-            dispose();
+            final QpidByteBufferFragment buffer = _fragments.get(i);
+            if (bytewise)
+            {
+                while (buffer.remaining() > 0 && written < valueWidth)
+                {
+                    buffer.put(src[offset + written]);
+                    written++;
+                }
+                if (written == valueWidth)
+                {
+                    break;
+                }
+            }
+            else
+            {
+                final int remaining = buffer.remaining();
+                if (remaining >= valueWidth)
+                {
+                    buffer.put(src, offset, length);
+                    written += length;
+                    break;
+                }
+                else
+                {
+                    bytewise = true;
+                    buffer.put(src, offset, remaining);
+                    written = remaining;
+                }
+            }
         }
+        if (written != length)
+        {
+            throw new IllegalStateException(String.format("Unexpectedly only wrote %d of %d bytes.", written, length));
+        }
+        return this;
     }
 
-    public final CharBuffer decode(Charset charset)
+    public final QpidByteBuffer put(final ByteBuffer src)
     {
-        return charset.decode(getUnderlyingBuffer());
+        final int valueWidth = src.remaining();
+        if (valueWidth > remaining())
+        {
+            throw new BufferOverflowException();
+        }
+        boolean bytewise = false;
+        int written = 0;
+        for (int i = 0, size = _fragments.size(); i < size; i++)
+        {
+            final QpidByteBufferFragment buffer = _fragments.get(i);
+            if (bytewise)
+            {
+                while (src.remaining() > 0 && buffer.remaining() > 0)
+                {
+                    buffer.put(src.get());
+                    written++;
+                }
+                if (written == valueWidth)
+                {
+                    break;
+                }
+            }
+            else
+            {
+                final int remaining = buffer.remaining();
+                if (remaining >= valueWidth)
+                {
+                    buffer.put(src);
+                    written += valueWidth;
+                    break;
+                }
+                else
+                {
+                    bytewise = true;
+                    while (remaining > written)
+                    {
+                        buffer.put(src.get());
+                        written++;
+                    }
+                }
+            }
+        }
+        if (written != valueWidth)
+        {
+            throw new IllegalStateException(String.format("Unexpectedly only wrote %d of %d bytes.", written, valueWidth));
+        }
+        return this;
     }
 
-    public final int read(ReadableByteChannel channel) throws IOException
+    public final QpidByteBuffer put(final QpidByteBuffer src)
     {
-        return channel.read(getUnderlyingBuffer());
+        final int valueWidth = src.remaining();
+        if (valueWidth > remaining())
+        {
+            throw new BufferOverflowException();
+        }
+        int i = 0;
+        boolean bytewise = false;
+        int written = 0;
+        int size = _fragments.size();
+        final List<QpidByteBufferFragment> fragments = src._fragments;
+        for (int i1 = 0, fragmentsSize = fragments.size(); i1 < fragmentsSize; i1++)
+        {
+            final QpidByteBufferFragment srcFragment = fragments.get(i1);
+            for (; i < size; i++)
+            {
+                final QpidByteBufferFragment dstFragment = _fragments.get(i);
+                if (dstFragment.hasRemaining())
+                {
+                    final int srcFragmentRemaining = srcFragment.remaining();
+                    if (bytewise)
+                    {
+                        while (srcFragmentRemaining > 0 && dstFragment.remaining() > 0)
+                        {
+                            dstFragment.put(srcFragment.get());
+                            written++;
+                        }
+                        if (!srcFragment.hasRemaining())
+                        {
+                            break;
+                        }
+                    }
+                    else
+                    {
+                        final int remaining = dstFragment.remaining();
+                        if (remaining >= srcFragmentRemaining)
+                        {
+                            dstFragment.put(srcFragment);
+                            written += srcFragmentRemaining;
+                            break;
+                        }
+                        else
+                        {
+                            bytewise = true;
+                            while (remaining > written)
+                            {
+                                dstFragment.put(srcFragment.get());
+                                written++;
+                            }
+                        }
+                    }
+                }
+            }
+        }
+        if (written != valueWidth)
+        {
+            throw new IllegalStateException(String.format("Unexpectedly only wrote %d of %d bytes.", written, valueWidth));
+        }
+        return this;
     }
 
-    public final SSLEngineResult decryptSSL(SSLEngine engine, QpidByteBuffer dest) throws SSLException
-    {
-        return engine.unwrap(getUnderlyingBuffer(), dest.getUnderlyingBuffer());
-    }
+    ///////////////////
+    // Absolute Gets
+    ///////////////////
 
-    @Override
-    public String toString()
+    public byte get(final int index)
     {
-        return "QpidByteBuffer{" +
-               "_buffer=" + _buffer +
-               ", _disposed=" + _disposed +
-               '}';
+        final byte[] byteArray = getByteArray(index, 1);
+        return byteArray[0];
     }
 
-    public final boolean hasRemaining()
+    public short getShort(final int index)
     {
-        return _buffer.hasRemaining();
+        final byte[] byteArray = getByteArray(index, 2);
+        return Shorts.fromByteArray(byteArray);
     }
 
-    public QpidByteBuffer putInt(final int index, final int value)
+    public final int getUnsignedShort(int index)
     {
-        _buffer.putInt(index, value);
-        return this;
+        return ((int) getShort(index)) & 0xFFFF;
     }
 
-    public QpidByteBuffer putShort(final int index, final short value)
+    public char getChar(final int index)
     {
-        _buffer.putShort(index, value);
-        return this;
+        final byte[] byteArray = getByteArray(index, 2);
+        return Chars.fromByteArray(byteArray);
     }
 
-    public QpidByteBuffer putChar(final int index, final char value)
+    public int getInt(final int index)
     {
-        _buffer.putChar(index, value);
-        return this;
+        final byte[] byteArray = getByteArray(index, 4);
+        return Ints.fromByteArray(byteArray);
     }
 
-    public final QpidByteBuffer put(final byte b)
+    public long getLong(final int index)
     {
-        _buffer.put(b);
-        return this;
+        final byte[] byteArray = getByteArray(index, 8);
+        return Longs.fromByteArray(byteArray);
     }
 
-    public QpidByteBuffer put(final int index, final byte b)
+    public float getFloat(final int index)
     {
-        _buffer.put(index, b);
-        return this;
+        final int intValue = getInt(index);
+        return Float.intBitsToFloat(intValue);
     }
 
-    public short getShort(final int index)
+    public double getDouble(final int index)
     {
-        return _buffer.getShort(index);
+        final long longValue = getLong(index);
+        return Double.longBitsToDouble(longValue);
     }
 
-    public final QpidByteBuffer mark()
+    private byte[] getByteArray(final int index, final int length)
     {
-        _buffer.mark();
-        return this;
-    }
+        if (index + length > limit())
+        {
+            throw new IndexOutOfBoundsException(String.format("%d bytes at index %d do not fit into bounds [%d, %d)", length, index, 0, limit()));
+        }
 
-    public final long getLong()
-    {
-        return _buffer.getLong();
+        byte[] value = new byte[length];
+        boolean bytewise = false;
+        int consumed = 0;
+        int bytesToSkip = index;
+        for (int i = 0, size = _fragments.size(); i < size; i++)
+        {
+            final QpidByteBufferFragment buffer = _fragments.get(i);
+            final int limit = buffer.limit();
+            boolean isLastFragmentToConsider = length + bytesToSkip - consumed <= limit;
+            if (!isLastFragmentToConsider && limit != buffer.capacity())
+            {
+                throw new IllegalStateException(String.format("Unexpectedly limit %d on fragment %d.", limit, i));
+            }
+            if (bytewise)
+            {
+                int offset = 0;
+                while (limit > offset && consumed < length)
+                {
+                    value[consumed] = buffer.get(offset);
+                    offset++;
+                    consumed++;
+                }
+                if (consumed == length)
+                {
+                    break;
+                }
+            }
+            else
+            {
+                if (limit >= bytesToSkip + length)
+                {
+                    while (consumed < length)
+                    {
+                        value[consumed] = buffer.get(bytesToSkip + consumed);
+                        consumed++;
+                    }
+                    break;
+                }
+                else if (limit > bytesToSkip)
+                {
+                    bytewise = true;
+                    while (limit > bytesToSkip + consumed)
+                    {
+                        value[consumed] = buffer.get(bytesToSkip + consumed);
+                        consumed++;
+                    }
+                    bytesToSkip = 0;
+                }
+                else
+                {
+                    bytesToSkip -= limit;
+                }
+            }
+        }
+        if (consumed != length)
+        {
+            throw new IllegalStateException(String.format("Unexpectedly only consumed %d of %d bytes.", consumed, length));
+        }
+        return value;
     }
 
-    public QpidByteBuffer putFloat(final int index, final float value)
-    {
-        _buffer.putFloat(index, value);
-        return this;
-    }
+    //////////////////
+    // Relative Gets
+    //////////////////
 
-    public double getDouble(final int index)
+    public final byte get()
     {
-        return _buffer.getDouble(index);
+        byte[] value = new byte[1];
+        get(value, 0, 1);
+        return value[0];
     }
 
-    public final boolean hasArray()
+    public final short getUnsignedByte()
     {
-        return _buffer.hasArray();
+        return (short) (get() & 0xFF);
     }
 
-    public final double getDouble()
+    public final short getShort()
     {
-        return _buffer.getDouble();
+        byte[] value = new byte[2];
+        get(value, 0, value.length);
+        return Shorts.fromByteArray(value);
     }
 
-    public final QpidByteBuffer putFloat(final float value)
+    public final int getUnsignedShort()
     {
-        _buffer.putFloat(value);
-        return this;
+        return ((int) getShort()) & 0xFFFF;
     }
 
-    public final QpidByteBuffer putInt(final int value)
+    public final char getChar()
     {
-        _buffer.putInt(value);
-        return this;
+        byte[] value = new byte[2];
+        get(value, 0, value.length);
+        return Chars.fromByteArray(value);
     }
 
-    public byte[] array()
+    public final int getInt()
     {
-        return _buffer.array();
+        byte[] value = new byte[4];
+        get(value, 0, value.length);
+        return Ints.fromByteArray(value);
     }
 
-    public final QpidByteBuffer putShort(final short value)
+    public final long getUnsignedInt()
     {
-        _buffer.putShort(value);
-        return this;
+        return ((long) getInt()) & 0xFFFFFFFFL;
     }
 
-    public int getInt(final int index)
+    public final long getLong()
     {
-        return _buffer.getInt(index);
+        byte[] value = new byte[8];
+        get(value, 0, value.length);
+        return Longs.fromByteArray(value);
     }
 
-    public final int remaining()
+    public final float getFloat()
     {
-        return _buffer.remaining();
+        final int intValue = getInt();
+        return Float.intBitsToFloat(intValue);
     }
 
-    public final QpidByteBuffer put(final byte[] src)
+    public final double getDouble()
     {
-        _buffer.put(src);
-        return this;
+        final long longValue = getLong();
+        return Double.longBitsToDouble(longValue);
     }
 
-    public final QpidByteBuffer put(final ByteBuffer src)
+    public final QpidByteBuffer get(final byte[] dst)
     {
-        _buffer.put(src);
-        return this;
+        return get(dst, 0, dst.length);
     }
 
-    public final QpidByteBuffer put(final QpidByteBuffer src)
+    public final QpidByteBuffer get(final byte[] dst, final int offset, final int length)
     {
-        int sourceRemaining = src.remaining();
-        if (sourceRemaining > remaining())
+        if (remaining() < length)
         {
-            throw new BufferOverflowException();
+            throw new BufferUnderflowException();
+        }
+        boolean bytewise = false;
+        int consumed = 0;
+        for (int i = 0, size = _fragments.size(); i < size; i++)
+        {
+            final QpidByteBufferFragment buffer = _fragments.get(i);
+            if (bytewise)
+            {
+                while (buffer.hasRemaining() && consumed < length)
+                {
+                    dst[offset + consumed] = buffer.get();
+                    consumed++;
+                }
+                if (consumed == length)
+                {
+                    return this;
+                }
+            }
+            else
+            {
+                final int remaining = buffer.remaining();
+                if (remaining >= length)
+                {
+                    buffer.get(dst, offset, length);
+                    return this;
+                }
+                else if (remaining > 0)
+                {
+                    bytewise = true;
+                    while (remaining > consumed)
+                    {
+                        dst[offset + consumed] = buffer.get();
+                        consumed++;
+                    }
+                }
+            }
+        }
+        if (consumed != length)
+        {
+            throw new IllegalStateException(String.format("Unexpectedly only consumed %d of %d bytes.", consumed, length));
         }
-
-        _buffer.put(src.getUnderlyingBuffer());
         return this;
     }
 
-    public final QpidByteBuffer get(final byte[] dst, final int offset, final int length)
-    {
-        _buffer.get(dst, offset, length);
-        return this;
-    }
+    ///////////////
+    // Other stuff
+    ////////////////
 
-    public final QpidByteBuffer get(final ByteBuffer dst)
+    public final void copyTo(final byte[] dst)
     {
-        int destinationRemaining = dst.remaining();
-        int remaining = remaining();
-        if (destinationRemaining < remaining)
+        if (remaining() < dst.length)
         {
             throw new BufferUnderflowException();
         }
-        dst.put(_buffer);
-        return this;
+        if (remaining() > dst.length)
+        {
+            throw new BufferOverflowException();
+        }
+        int offset = 0;
+        for (QpidByteBufferFragment fragment : _fragments)
+        {
+            final int length = Math.min(fragment.remaining(), dst.length - offset);
+            fragment._buffer.duplicate().get(dst, offset, length);
+            offset += length;
+        }
     }
 
     public final void copyTo(final ByteBuffer dst)
     {
-        dst.put(_buffer.duplicate());
+        if (dst.remaining() < remaining())
+        {
+            throw new BufferOverflowException();
+        }
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize; i++)
+        {
+            final QpidByteBufferFragment fragment = _fragments.get(i);
+            dst.put(fragment._buffer.duplicate());
+        }
     }
 
     public final void putCopyOf(final QpidByteBuffer source)
@@ -341,218 +688,345 @@ public class QpidByteBuffer implements AutoCloseable
         {
             throw new BufferOverflowException();
         }
-
-        put(source.getUnderlyingBuffer().duplicate());
+        for (int i = 0, fragmentsSize = source._fragments.size(); i < fragmentsSize; i++)
+        {
+            final QpidByteBufferFragment srcFragment = source._fragments.get(i);
+            put(srcFragment._buffer.duplicate());
+        }
     }
 
-    public QpidByteBuffer rewind()
+    public final boolean isDirect()
     {
-        _buffer.rewind();
-        return this;
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize; i++)
+        {
+            final QpidByteBufferFragment fragment = _fragments.get(i);
+            if (!fragment.isDirect())
+            {
+                return false;
+            }
+        }
+        return true;
     }
 
-    public QpidByteBuffer clear()
+    @Override
+    public final void close()
     {
-        _buffer.clear();
-        return this;
+        dispose();
     }
 
-    public QpidByteBuffer putLong(final int index, final long value)
+    public final void dispose()
     {
-        _buffer.putLong(index, value);
-        return this;
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize; i++)
+        {
+            final QpidByteBufferFragment fragment = _fragments.get(i);
+            fragment.dispose();
+        }
     }
 
-    public QpidByteBuffer compact()
+    public final InputStream asInputStream()
     {
-        _buffer.compact();
-        return this;
+        return new QpidByteBuffer.BufferInputStream(this);
     }
 
-    public final QpidByteBuffer putDouble(final double value)
+    public final long read(ScatteringByteChannel channel) throws IOException
     {
-        _buffer.putDouble(value);
-        return this;
+        ByteBuffer[] byteBuffers = new ByteBuffer[_fragments.size()];
+        for (int i = 0; i < byteBuffers.length; i++)
+        {
+            final QpidByteBufferFragment fragment = _fragments.get(i);
+            byteBuffers[i] = fragment.getUnderlyingBuffer();
+        }
+        return channel.read(byteBuffers);
     }
 
-    public int limit()
+    @Override
+    public String toString()
     {
-        return _buffer.limit();
+        return "QpidByteBuffer{" + _fragments.size() + " fragments}";
     }
 
     public QpidByteBuffer reset()
     {
-        _buffer.reset();
+        if (_resetFragmentIndex < 0)
+        {
+            throw new InvalidMarkException();
+        }
+        final QpidByteBufferFragment fragment = _fragments.get(_resetFragmentIndex);
+        fragment.reset();
+        for (int i = _resetFragmentIndex + 1, size = _fragments.size(); i < size; ++i)
+        {
+            _fragments.get(i).position(0);
+        }
         return this;
     }
 
-    public QpidByteBuffer flip()
+    public QpidByteBuffer rewind()
     {
-        _buffer.flip();
+        _resetFragmentIndex = -1;
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize; i++)
+        {
+            final QpidByteBufferFragment fragment = _fragments.get(i);
+            fragment.rewind();
+        }
         return this;
     }
 
-    public final short getShort()
+    public final boolean hasArray()
     {
-        return _buffer.getShort();
+        return _fragments.size() == 1 && _fragments.get(0).hasArray();
     }
 
-    public final float getFloat()
+    public byte[] array()
     {
-        return _buffer.getFloat();
+        if (!hasArray())
+        {
+            throw new UnsupportedOperationException("This QpidByteBuffer is not backed by an array.");
+        }
+        return _fragments.get(0).array();
     }
 
-    public QpidByteBuffer limit(final int newLimit)
+    public QpidByteBuffer clear()
     {
-        _buffer.limit(newLimit);
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize; i++)
+        {
+            _fragments.get(i).clear();
+        }
         return this;
     }
 
-    /**
-     * Method does not respect mark.
-     *
-     * @return QpidByteBuffer
-     */
-    public QpidByteBuffer duplicate()
+    public QpidByteBuffer compact()
     {
-        ByteBuffer buffer = _ref.getBuffer();
-        if (!(_ref instanceof PooledByteBufferRef))
+        if (_fragments.size() == 1)
         {
-            buffer = buffer.duplicate();
+            _fragments.get(0).compact();
         }
-
-        buffer.position(_offset );
-        buffer.limit(_offset + _buffer.capacity());
-
-        buffer = buffer.slice();
-
-        buffer.limit(_buffer.limit());
-        buffer.position(_buffer.position());
-        return new QpidByteBuffer(_ref, buffer, _offset);
-    }
-
-    public final QpidByteBuffer put(final byte[] src, final int offset, final int length)
-    {
-        _buffer.put(src, offset, length);
+        else
+        {
+            int position = position();
+            int limit = limit();
+            if (position != 0)
+            {
+                int dstPos = 0;
+                for (int srcPos = position; srcPos < limit; ++srcPos, ++dstPos)
+                {
+                    put(dstPos, get(srcPos));
+                }
+                position(dstPos);
+                limit(capacity());
+            }
+        }
+        _resetFragmentIndex = -1;
         return this;
     }
 
-    public long getLong(final int index)
-    {
-        return _buffer.getLong(index);
-    }
-
-    public int capacity()
+    public int position()
     {
-        return _buffer.capacity();
+        int totalPosition = 0;
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize; i++)
+        {
+            final QpidByteBufferFragment fragment = _fragments.get(i);
+            totalPosition += fragment.position();
+            if (fragment.position() != fragment.limit())
+            {
+                break;
+            }
+        }
+        return totalPosition;
     }
 
-    public char getChar(final int index)
+    public QpidByteBuffer position(int newPosition)
     {
-        return _buffer.getChar(index);
+        if (newPosition < 0 || newPosition > limit())
+        {
+            throw new IllegalArgumentException(String.format("new position %d is out of bounds [%d, %d)", newPosition, 0, limit()));
+        }
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize; i++)
+        {
+            final QpidByteBufferFragment fragment = _fragments.get(i);
+            final int fragmentLimit = fragment.limit();
+            if (newPosition <= fragmentLimit)
+            {
+                fragment.position(newPosition);
+                newPosition = 0;
+            }
+            else
+            {
+                if (fragmentLimit != fragment.capacity())
+                {
+                    throw new IllegalStateException(String.format("QBB Fragment %d has limit %d != capacity %d",
+                                                                  i,
+                                                                  fragmentLimit,
+                                                                  fragment.capacity()));
+                }
+                fragment.position(fragmentLimit);
+                newPosition -= fragmentLimit;
+            }
+        }
+        return this;
     }
 
-    public final byte get()
+    public int limit()
     {
-        return _buffer.get();
-    }
+        int totalLimit = 0;
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize; i++)
+        {
+            final QpidByteBufferFragment fragment = _fragments.get(i);
+            final int fragmentLimit = fragment.limit();
+            totalLimit += fragmentLimit;
+            if (fragmentLimit != fragment.capacity())
+            {
+                break;
+            }
+        }
 
-    public byte get(final int index)
-    {
-        return _buffer.get(index);
+        return totalLimit;
     }
 
-    public final QpidByteBuffer get(final byte[] dst)
+    public QpidByteBuffer limit(int newLimit)
     {
-        _buffer.get(dst);
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize; i++)
+        {
+            final QpidByteBufferFragment fragment = _fragments.get(i);
+            final int fragmentCapacity = fragment.capacity();
+            final int fragmentLimit = Math.min(newLimit, fragmentCapacity);
+            fragment.limit(fragmentLimit);
+            newLimit -= fragmentLimit;
+        }
         return this;
     }
 
-    public final void copyTo(final byte[] dst)
+    public final QpidByteBuffer mark()
     {
-        if (remaining() < dst.length)
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize; i++)
         {
-            throw new BufferUnderflowException();
+            final QpidByteBufferFragment fragment = _fragments.get(i);
+            if (fragment.position() != fragment.limit())
+            {
+                fragment.mark();
+                _resetFragmentIndex = i;
+                return this;
+            }
         }
-        _buffer.duplicate().get(dst);
-    }
-
-    public final QpidByteBuffer putChar(final char value)
-    {
-        _buffer.putChar(value);
+        _resetFragmentIndex = _fragments.size() - 1;
+        _fragments.get(_resetFragmentIndex).mark();
         return this;
     }
 
-    public QpidByteBuffer position(final int newPosition)
+    public final int remaining()
     {
-        _buffer.position(newPosition);
-        return this;
+        int remaining = 0;
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize; i++)
+        {
+            final QpidByteBufferFragment fragment = _fragments.get(i);
+            remaining += fragment.remaining();
+        }
+        return remaining;
     }
 
-    public int arrayOffset()
+    public final boolean hasRemaining()
     {
-        return _buffer.arrayOffset();
+        return hasRemaining(1);
     }
 
-    public final char getChar()
+    public final boolean hasRemaining(int atLeast)
     {
-        return _buffer.getChar();
+        int remaining = 0;
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize; i++)
+        {
+            final QpidByteBufferFragment fragment = _fragments.get(i);
+            remaining += fragment.remaining();
+            if (remaining >= atLeast)
+            {
+                return true;
+            }
+        }
+        return false;
     }
 
-    public final int getInt()
+    public QpidByteBuffer flip()
     {
-        return _buffer.getInt();
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize; i++)
+        {
+            final QpidByteBufferFragment fragment = _fragments.get(i);
+            fragment.flip();
+        }
+        return this;
     }
 
-    public final QpidByteBuffer putLong(final long value)
+    public int capacity()
     {
-        _buffer.putLong(value);
-        return this;
+        int totalCapacity = 0;
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize; i++)
+        {
+            totalCapacity += _fragments.get(i).capacity();
+        }
+        return totalCapacity;
     }
 
-    public float getFloat(final int index)
+    /**
+     * Method does not respect mark.
+     *
+     * @return QpidByteBuffer
+     */
+    public QpidByteBuffer duplicate()
     {
-        return _buffer.getFloat(index);
+        final QpidByteBuffer newQpidByteBuffer = new QpidByteBuffer();
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize; i++)
+        {
+            newQpidByteBuffer._fragments.add(_fragments.get(i).duplicate());
+        }
+        return newQpidByteBuffer;
     }
 
     public QpidByteBuffer slice()
     {
-        return view(0, _buffer.remaining());
+        return view(0, remaining());
     }
 
     public QpidByteBuffer view(int offset, int length)
     {
-        ByteBuffer buffer = _ref.getBuffer();
-        if (!(_ref instanceof PooledByteBufferRef))
+        if (offset + length > remaining())
         {
-            buffer = buffer.duplicate();
+            throw new IllegalArgumentException(String.format("offset: %d, length: %d, remaining: %d", offset, length, remaining()));
+        }
+        final QpidByteBuffer newQpidByteBuffer = new QpidByteBuffer();
+        boolean firstFragmentToBeConsidered = true;
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize && length > 0; i++)
+        {
+            final QpidByteBufferFragment fragment = _fragments.get(i);
+            if (fragment.hasRemaining())
+            {
+                if (!firstFragmentToBeConsidered && fragment.position() != 0)
+                {
+                    throw new IllegalStateException(String.format("Unexpectedly position %d on fragment %d.", fragment.position(), i));
+                }
+                firstFragmentToBeConsidered = false;
+                if (fragment.remaining() > offset)
+                {
+                    final int fragmentViewLength = Math.min(fragment.remaining() - offset, length);
+                    newQpidByteBuffer._fragments.add(fragment.view(offset, fragmentViewLength));
+                    length -= fragmentViewLength;
+                    offset = 0;
+                }
+                else
+                {
+                    offset -= fragment.remaining();
+                }
+            }
         }
 
-        int newRemaining = Math.min(_buffer.remaining() - offset, length);
-
-        int newPosition = _offset + _buffer.position() + offset;
-        buffer.limit(newPosition + newRemaining);
-        buffer.position(newPosition);
-
-        buffer = buffer.slice();
-
-        return new QpidByteBuffer(_ref, buffer, newPosition);
-    }
-
-    public int position()
-    {
-        return _buffer.position();
+        return newQpidByteBuffer;
     }
 
-    public QpidByteBuffer putDouble(final int index, final double value)
+    List<ByteBuffer> getUnderlyingBuffers()
     {
-        _buffer.putDouble(index, value);
-        return this;
-    }
+        List<ByteBuffer> byteBuffers = new ArrayList<>();
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize; i++)
+        {
+            byteBuffers.add(_fragments.get(i).getUnderlyingBuffer());
+        }
+        return byteBuffers;
 
-    ByteBuffer getUnderlyingBuffer()
-    {
-        return _buffer;
     }
 
     public static QpidByteBuffer allocate(boolean direct, int size)
@@ -562,113 +1036,47 @@ public class QpidByteBuffer implements AutoCloseable
 
     public static QpidByteBuffer allocate(int size)
     {
-        return new QpidByteBuffer(new NonPooledByteBufferRef(ByteBuffer.allocate(size)));
+        final QpidByteBuffer qpidByteBuffer = new QpidByteBuffer();
+        qpidByteBuffer._fragments.add(QpidByteBufferFragment.allocate(size));
+        return qpidByteBuffer;
     }
 
     public static QpidByteBuffer allocateDirect(int size)
     {
         if (size < 0)
         {
-            throw new IllegalArgumentException("Cannot allocate QpidByteBuffer with size "
-                                               + size
-                                               + " which is negative.");
-        }
-
-        final ByteBufferRef ref;
-        if (_isPoolInitialized && _pooledBufferSize >= size)
-        {
-            if (_pooledBufferSize == size)
-            {
-                ByteBuffer buf = _bufferPool.getBuffer();
-                if (buf == null)
-                {
-                    buf = ByteBuffer.allocateDirect(size);
-                }
-                ref = new PooledByteBufferRef(buf);
-            }
-            else
-            {
-                QpidByteBuffer buf = _cachedBuffer.get();
-                if (buf == null || buf.remaining() < size)
-                {
-                    if (buf != null)
-                    {
-                        buf.dispose();
-                    }
-                    buf = allocateDirect(_pooledBufferSize);
-                    _cachedBuffer.set(buf);
-                }
-                QpidByteBuffer rVal = buf.view(0, size);
-                buf.position(buf.position() + size);
-
-                return rVal;
-            }
-        }
-        else
-        {
-            ref = new NonPooledByteBufferRef(ByteBuffer.allocateDirect(size));
-        }
-        return new QpidByteBuffer(ref);
-    }
-
-    public static Collection<QpidByteBuffer> allocateDirectCollection(int size)
-    {
-        if (_pooledBufferSize == 0)
-        {
-            return Collections.singleton(allocateDirect(size));
+            throw new IllegalArgumentException("Cannot allocate QpidByteBufferFragment with size "
+                                               + size
+                                               + " which is negative.");
         }
-        else
-        {
-            List<QpidByteBuffer> buffers = new ArrayList<>((size / _pooledBufferSize) + 2);
-            int remaining = size;
-
-            QpidByteBuffer buf = _cachedBuffer.get();
-            if (buf == null)
-            {
-                buf = allocateDirect(_pooledBufferSize);
-            }
-            while (remaining > buf.remaining())
-            {
-                int bufRemaining = buf.remaining();
-                if (buf == _cachedBuffer.get())
-                {
-                    buffers.add(buf.view(0, bufRemaining));
-                    buf.dispose();
-                }
-                else
-                {
-                    buffers.add(buf);
-                }
-                remaining -= bufRemaining;
-                buf = allocateDirect(_pooledBufferSize);
-            }
-            buffers.add(buf.view(0, remaining));
-            buf.position(buf.position() + remaining);
 
-            if (buf.hasRemaining())
+        if (_isPoolInitialized)
+        {
+            QpidByteBuffer qpidByteBuffer = new QpidByteBuffer();
+            int allocatedSize = 0;
+            while (size - allocatedSize >= _pooledBufferSize)
             {
-                _cachedBuffer.set(buf);
+                qpidByteBuffer._fragments.add(QpidByteBufferFragment.allocateDirect(_pooledBufferSize));
+                allocatedSize += _pooledBufferSize;
             }
-            else
+            if (allocatedSize != size)
             {
-                _cachedBuffer.set(allocateDirect(_pooledBufferSize));
-                buf.dispose();
+                qpidByteBuffer._fragments.add(QpidByteBufferFragment.allocateDirect(size - allocatedSize));
             }
-            return buffers;
+            return qpidByteBuffer;
+        }
+        else
+        {
+            return allocate(size);
         }
     }
 
-    public static Collection<QpidByteBuffer> asQpidByteBuffers(final byte[] data)
-    {
-        return asQpidByteBuffers(data, 0, data.length);
-    }
-
-    public static Collection<QpidByteBuffer> asQpidByteBuffers(final byte[] data, final int offset, final int length)
+    private static QpidByteBuffer asQpidByteBuffer(final byte[] data, final int offset, final int length)
     {
         try (QpidByteBufferOutputStream outputStream = new QpidByteBufferOutputStream(true, getPooledBufferSize()))
         {
             outputStream.write(data, offset, length);
-            return outputStream.fetchAccumulatedBuffers();
+            return outputStream.fetchAccumulatedBuffer();
         }
         catch (IOException e)
         {
@@ -676,20 +1084,46 @@ public class QpidByteBuffer implements AutoCloseable
         }
     }
 
-    public static List<QpidByteBuffer> asQpidByteBuffers(final InputStream stream) throws IOException
+    public static QpidByteBuffer asQpidByteBuffer(final InputStream stream) throws IOException
+    {
+        final QpidByteBuffer qpidByteBuffer = new QpidByteBuffer();
+        final int pooledBufferSize = QpidByteBuffer.getPooledBufferSize();
+        byte[] transferBuf = new byte[pooledBufferSize];
+        int readFragment = 0;
+        int read = stream.read(transferBuf, readFragment, pooledBufferSize - readFragment);
+        while (read > 0)
+        {
+            readFragment += read;
+            if (readFragment == pooledBufferSize)
+            {
+                QpidByteBufferFragment fragment = QpidByteBufferFragment.allocateDirect(pooledBufferSize);
+                fragment.put(transferBuf, 0, pooledBufferSize);
+                fragment.flip();
+                qpidByteBuffer._fragments.add(fragment);
+                readFragment = 0;
+            }
+            read = stream.read(transferBuf, readFragment, pooledBufferSize - readFragment);
+        }
+        if (readFragment != 0)
+        {
+            QpidByteBufferFragment fragment = QpidByteBufferFragment.allocateDirect(readFragment);
+            fragment.put(transferBuf, 0, readFragment);
+            fragment.flip();
+            qpidByteBuffer._fragments.add(fragment);
+        }
+        return qpidByteBuffer;
+    }
+
+    public final SSLEngineResult decryptSSL(SSLEngine engine, QpidByteBuffer dst) throws SSLException
     {
-        List<QpidByteBuffer> bufs = new ArrayList<>();
-        byte[] transferBuf = new byte[QpidByteBuffer.getPooledBufferSize()];
-        int read = stream.read(transferBuf);
-        while(read > 0)
+        final List<ByteBuffer> dstUnderlyingBuffers = dst.getUnderlyingBuffers();
+        final List<ByteBuffer> underlyingBuffers = getUnderlyingBuffers();
+        if (underlyingBuffers.size() != 1)
         {
-            QpidByteBuffer chunk = QpidByteBuffer.allocateDirect(read);
-            chunk.put(transferBuf, 0, read);
-            chunk.flip();
-            bufs.add(chunk);
-            read = stream.read(transferBuf);
+            throw new IllegalStateException("Expected single fragment buffer");
         }
-        return bufs;
+        return engine.unwrap(underlyingBuffers.get(0),
+                             dstUnderlyingBuffers.toArray(new ByteBuffer[dstUnderlyingBuffers.size()]));
     }
 
     public static SSLEngineResult encryptSSL(SSLEngine engine,
@@ -704,72 +1138,62 @@ public class QpidByteBuffer implements AutoCloseable
         }
         else
         {
-            src = new ByteBuffer[buffers.size()];
-            Iterator<QpidByteBuffer> iterator = buffers.iterator();
-            for (int i = 0; i < src.length; i++)
+            List<ByteBuffer> buffers_ = new LinkedList<>();
+            for (QpidByteBuffer buffer : buffers)
             {
-                src[i] = iterator.next().getUnderlyingBuffer();
+                buffers_.addAll(buffer.getUnderlyingBuffers());
             }
+            src = buffers_.toArray(new ByteBuffer[buffers_.size()]);
         }
-        return engine.wrap(src, dest.getUnderlyingBuffer());
+        final List<ByteBuffer> dstUnderlyingBuffers = dest.getUnderlyingBuffers();
+        if (dstUnderlyingBuffers.size() != 1)
+        {
+            throw new IllegalStateException("Expected a single fragment output buffer");
+        }
+        return engine.wrap(src, dstUnderlyingBuffers.get(0));
     }
 
-    public static Collection<QpidByteBuffer> inflate(Collection<QpidByteBuffer> compressedBuffers) throws IOException
+    public static QpidByteBuffer inflate(QpidByteBuffer compressedBuffer) throws IOException
     {
-        if (compressedBuffers == null)
+        if (compressedBuffer == null)
         {
-            throw new IllegalArgumentException("compressedBuffers cannot be null");
+            throw new IllegalArgumentException("compressedBuffer cannot be null");
         }
 
-        boolean isDirect = false;
-        Collection<InputStream> streams = new ArrayList<>(compressedBuffers.size());
-        for (QpidByteBuffer buffer : compressedBuffers)
-        {
-            isDirect = isDirect || buffer.isDirect();
-            streams.add(buffer.asInputStream());
-        }
+        boolean isDirect = compressedBuffer.isDirect();
         final int bufferSize = (isDirect && _pooledBufferSize > 0) ? _pooledBufferSize : 65536;
 
-        Collection<QpidByteBuffer> uncompressedBuffers = new ArrayList<>();
-        try (GZIPInputStream gzipInputStream = new GZIPInputStream(new CompositeInputStream(streams)))
+        List<QpidByteBuffer> uncompressedBuffers = new ArrayList<>();
+        try (GZIPInputStream gzipInputStream = new GZIPInputStream(compressedBuffer.asInputStream()))
         {
             byte[] buf = new byte[bufferSize];
             int read;
             while ((read = gzipInputStream.read(buf)) != -1)
             {
-                uncompressedBuffers.addAll(asQpidByteBuffers(buf, 0, read));
+                uncompressedBuffers.add(QpidByteBuffer.asQpidByteBuffer(buf, 0, read));
             }
-            return uncompressedBuffers;
+            return QpidByteBuffer.concatenate(uncompressedBuffers);
         }
-        catch (IOException e)
+        finally
         {
-            for (QpidByteBuffer uncompressedBuffer : uncompressedBuffers)
-            {
-                uncompressedBuffer.dispose();
-            }
-            throw e;
+            uncompressedBuffers.forEach(QpidByteBuffer::dispose);
         }
     }
 
-    public static Collection<QpidByteBuffer> deflate(Collection<QpidByteBuffer> uncompressedBuffers) throws IOException
+    public static QpidByteBuffer deflate(QpidByteBuffer uncompressedBuffer) throws IOException
     {
-        if (uncompressedBuffers == null)
+        if (uncompressedBuffer == null)
         {
-            throw new IllegalArgumentException("uncompressedBuffers cannot be null");
+            throw new IllegalArgumentException("uncompressedBuffer cannot be null");
         }
 
-        boolean isDirect = false;
-        Collection<InputStream> streams = new ArrayList<>(uncompressedBuffers.size());
-        for (QpidByteBuffer buffer : uncompressedBuffers)
-        {
-            isDirect = isDirect || buffer.isDirect();
-            streams.add(buffer.asInputStream());
-        }
+        boolean isDirect = uncompressedBuffer.isDirect();
         final int bufferSize = (isDirect && _pooledBufferSize > 0) ? _pooledBufferSize : 65536;
 
-        try(QpidByteBufferOutputStream compressedOutput = new QpidByteBufferOutputStream(isDirect, bufferSize);
-            InputStream compressedInput = new CompositeInputStream(streams);
-            GZIPOutputStream gzipStream = new GZIPOutputStream(new BufferedOutputStream(compressedOutput, bufferSize)))
+        try (QpidByteBufferOutputStream compressedOutput = new QpidByteBufferOutputStream(isDirect, bufferSize);
+             InputStream compressedInput = uncompressedBuffer.asInputStream();
+             GZIPOutputStream gzipStream = new GZIPOutputStream(new BufferedOutputStream(compressedOutput,
+                                                                                         bufferSize)))
         {
             byte[] buf = new byte[16384];
             int read;
@@ -779,25 +1203,29 @@ public class QpidByteBuffer implements AutoCloseable
             }
             gzipStream.finish();
             gzipStream.flush();
-            return compressedOutput.fetchAccumulatedBuffers();
+            return compressedOutput.fetchAccumulatedBuffer();
         }
     }
 
     public static long write(GatheringByteChannel channel, Collection<QpidByteBuffer> qpidByteBuffers)
             throws IOException
     {
-        ByteBuffer[] byteBuffers = new ByteBuffer[qpidByteBuffers.size()];
-        Iterator<QpidByteBuffer> iterator = qpidByteBuffers.iterator();
-        for (int i = 0; i < byteBuffers.length; i++)
+        List<ByteBuffer> byteBuffers = new ArrayList<>();
+        for (QpidByteBuffer qpidByteBuffer : qpidByteBuffers)
         {
-            byteBuffers[i] = iterator.next().getUnderlyingBuffer();
+            for (QpidByteBufferFragment fragment : qpidByteBuffer._fragments)
+            {
+                byteBuffers.add(fragment.getUnderlyingBuffer());
+            }
         }
-        return channel.write(byteBuffers);
+        return channel.write(byteBuffers.toArray(new ByteBuffer[byteBuffers.size()]));
     }
 
     public static QpidByteBuffer wrap(final ByteBuffer wrap)
     {
-        return new QpidByteBuffer(new NonPooledByteBufferRef(wrap));
+        final QpidByteBuffer qpidByteBuffer = new QpidByteBuffer();
+        qpidByteBuffer._fragments.add(new QpidByteBufferFragment(new NonPooledByteBufferRef(wrap)));
+        return qpidByteBuffer;
     }
 
     public static QpidByteBuffer wrap(final byte[] data)
@@ -813,19 +1241,25 @@ public class QpidByteBuffer implements AutoCloseable
     static void returnToPool(final ByteBuffer buffer)
     {
         buffer.clear();
-        final ByteBuffer duplicate = _zeroed.duplicate();
-        duplicate.limit(buffer.capacity());
-        buffer.put(duplicate);
+        if (_isPoolInitialized)
+        {
+            final ByteBuffer duplicate = _zeroed.duplicate();
+            duplicate.limit(buffer.capacity());
+            buffer.put(duplicate);
 
-        _bufferPool.returnBuffer(buffer);
+            _bufferPool.returnBuffer(buffer);
+        }
     }
 
     public synchronized static void initialisePool(int bufferSize, int maxPoolSize, final double sparsityFraction)
     {
-        if (_isPoolInitialized && (bufferSize != _pooledBufferSize || maxPoolSize != _bufferPool.getMaxSize() || sparsityFraction != _sparsityFraction))
+        if (_isPoolInitialized && (bufferSize != _pooledBufferSize
+                                   || maxPoolSize != _bufferPool.getMaxSize()
+                                   || sparsityFraction != _sparsityFraction))
         {
             final String errorMessage = String.format(
-                    "QpidByteBuffer pool has already been initialised with bufferSize=%d, maxPoolSize=%d, and sparsityFraction=%f." +
+                    "QpidByteBuffer pool has already been initialised with bufferSize=%d, maxPoolSize=%d, and sparsityFraction=%f."
+                    +
                     "Re-initialisation with different bufferSize=%d and maxPoolSize=%d is not allowed.",
                     _pooledBufferSize,
                     _bufferPool.getMaxSize(),
@@ -846,7 +1280,9 @@ public class QpidByteBuffer implements AutoCloseable
         _isPoolInitialized = true;
     }
 
-    /** Test use only */
+    /**
+     * Test use only
+     */
     public synchronized static void deinitialisePool()
     {
         if (_isPoolInitialized)
@@ -856,18 +1292,15 @@ public class QpidByteBuffer implements AutoCloseable
             _zeroed = null;
             _isPoolInitialized = false;
             _sparsityFraction = 1.0;
+            final QpidByteBufferFragment cachedBuffer = _cachedBuffer.get();
+            if (cachedBuffer != null)
+            {
+                cachedBuffer.dispose();
+                _cachedBuffer.remove();
+            }
         }
     }
 
-    /**
-     * Not for general use!
-     * Used to clear threadlocal buffer when shutting down thread pools.
-     */
-    public static QpidByteBuffer getCachedThreadLocalBuffer()
-    {
-        return _cachedBuffer.get();
-    }
-
     public static int getPooledBufferSize()
     {
         return _pooledBufferSize;
@@ -893,23 +1326,6 @@ public class QpidByteBuffer implements AutoCloseable
         return PooledByteBufferRef.getDisposalCounter();
     }
 
-    public static List<QpidByteBuffer> reallocateIfNecessary(Collection<QpidByteBuffer> data)
-    {
-        if (data != null)
-        {
-            List<QpidByteBuffer> newCopy = new ArrayList<>(data.size());
-            for (QpidByteBuffer buf : data)
-            {
-                newCopy.add(reallocateIfNecessary(buf));
-            }
-            return newCopy;
-        }
-        else
-        {
-            return null;
-        }
-    }
-
     public static QpidByteBuffer reallocateIfNecessary(final QpidByteBuffer data)
     {
         if (data != null && data.isDirect() && data.isSparse())
@@ -928,7 +1344,57 @@ public class QpidByteBuffer implements AutoCloseable
 
     boolean isSparse()
     {
-        return _ref.isSparse(_sparsityFraction);
+        for (int i = 0, fragmentsSize = _fragments.size(); i < fragmentsSize; i++)
+        {
+            final QpidByteBufferFragment fragment = _fragments.get(i);
+            if (fragment.isSparse())
+            {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    public static QpidByteBuffer concatenate(final List<QpidByteBuffer> buffers)
+    {
+        final QpidByteBuffer qpidByteBuffer = new QpidByteBuffer();
+        for (QpidByteBuffer buffer : buffers)
+        {
+            for (QpidByteBufferFragment fragment : buffer._fragments)
+            {
+                qpidByteBuffer._fragments.add(fragment.slice());
+            }
+        }
+        return qpidByteBuffer;
+    }
+
+    public static QpidByteBuffer concatenate(QpidByteBuffer... buffers)
+    {
+        return concatenate(Arrays.asList(buffers));
+    }
+
+    public static QpidByteBuffer emptyQpidByteBuffer()
+    {
+        return EMPTY_QPID_BYTE_BUFFER.duplicate();
+    }
+
+    public static ThreadFactory createQpidByteBufferTrackingThreadFactory(final ThreadFactory factory)
+    {
+        return r -> factory.newThread(() -> {
+            try
+            {
+                r.run();
+            }
+            finally
+            {
+                final QpidByteBufferFragment cachedThreadLocalBuffer = _cachedBuffer.get();
+                if (cachedThreadLocalBuffer != null)
+                {
+                    cachedThreadLocalBuffer.dispose();
+                    _cachedBuffer.remove();
+                }
+            }
+        });
     }
 
     private static final class BufferInputStream extends InputStream
@@ -937,7 +1403,7 @@ public class QpidByteBuffer implements AutoCloseable
 
         private BufferInputStream(final QpidByteBuffer buffer)
         {
-            _qpidByteBuffer = buffer;
+            _qpidByteBuffer = buffer.duplicate();
         }
 
         @Override
@@ -945,7 +1411,7 @@ public class QpidByteBuffer implements AutoCloseable
         {
             if (_qpidByteBuffer.hasRemaining())
             {
-                return _qpidByteBuffer.get() & 0xFF;
+                return _qpidByteBuffer.getUnsignedByte();
             }
             return -1;
         }
@@ -1001,6 +1467,324 @@ public class QpidByteBuffer implements AutoCloseable
         @Override
         public void close()
         {
+            _qpidByteBuffer.dispose();
+        }
+    }
+
+
+    static class QpidByteBufferFragment implements AutoCloseable
+    {
+
+        private static final AtomicIntegerFieldUpdater<QpidByteBufferFragment>
+                DISPOSED_UPDATER = AtomicIntegerFieldUpdater.newUpdater(
+                QpidByteBufferFragment.class,
+                "_disposed");
+
+        private final int _offset;
+
+        final ByteBufferRef _ref;
+        volatile ByteBuffer _buffer;
+        @SuppressWarnings("unused")
+        private volatile int _disposed;
+
+
+        QpidByteBufferFragment(ByteBufferRef ref)
+        {
+            this(ref, ref.getBuffer(), 0);
+        }
+
+        private QpidByteBufferFragment(ByteBufferRef ref, ByteBuffer buffer, int offset)
+        {
+            _ref = ref;
+            _buffer = buffer;
+            _offset = offset;
+            _ref.incrementRef(capacity());
+        }
+
+        public final boolean isDirect()
+        {
+            return _buffer.isDirect();
+        }
+
+        @Override
+        public final void close()
+        {
+            dispose();
+        }
+
+        public final void dispose()
+        {
+            if (DISPOSED_UPDATER.compareAndSet(this, 0, 1))
+            {
+                _ref.decrementRef(capacity());
+                _buffer = null;
+            }
+        }
+
+        public final CharBuffer decode(Charset charset)
+        {
+            return charset.decode(getUnderlyingBuffer());
+        }
+
+        @Override
+        public String toString()
+        {
+            return "QpidByteBufferFragment{" +
+                   "_buffer=" + _buffer +
+                   ", _disposed=" + _disposed +
+                   '}';
+        }
+
+        public final boolean hasRemaining()
+        {
+            return _buffer.hasRemaining();
+        }
+
+        public final QpidByteBufferFragment put(final byte b)
+        {
+            _buffer.put(b);
+            return this;
+        }
+
+        public QpidByteBufferFragment put(final int index, final byte b)
+        {
+            _buffer.put(index, b);
+            return this;
+        }
+
+        public final QpidByteBufferFragment mark()
+        {
+            _buffer.mark();
+            return this;
+        }
+
+        public final boolean hasArray()
+        {
+            return _buffer.hasArray();
+        }
+
+        public byte[] array()
+        {
+            return _buffer.array();
+        }
+
+        public final int remaining()
+        {
+            return _buffer.remaining();
+        }
+
+
+        public final QpidByteBufferFragment put(final ByteBuffer src)
+        {
+            _buffer.put(src);
+            return this;
+        }
+
+        public final QpidByteBufferFragment put(final QpidByteBufferFragment src)
+        {
+            int sourceRemaining = src.remaining();
+            if (sourceRemaining > remaining())
+            {
+                throw new BufferOverflowException();
+            }
+
+            _buffer.put(src.getUnderlyingBuffer());
+            return this;
+        }
+
+        public final QpidByteBufferFragment get(final byte[] dst, final int offset, final int length)
+        {
+            _buffer.get(dst, offset, length);
+            return this;
+        }
+
+        public QpidByteBufferFragment rewind()
+        {
+            _buffer.rewind();
+            return this;
+        }
+
+        public QpidByteBufferFragment clear()
+        {
+            _buffer.clear();
+            return this;
+        }
+
+        public QpidByteBufferFragment compact()
+        {
+            _buffer.compact();
+            return this;
+        }
+
+        public int limit()
+        {
+            return _buffer.limit();
+        }
+
+        public QpidByteBufferFragment reset()
+        {
+            _buffer.reset();
+            return this;
+        }
+
+        public QpidByteBufferFragment flip()
+        {
+            _buffer.flip();
+            return this;
+        }
+
+        public QpidByteBufferFragment limit(final int newLimit)
+        {
+            _buffer.limit(newLimit);
+            return this;
+        }
+
+        /**
+         * Method does not respect mark.
+         *
+         * @return QpidByteBufferFragment
+         */
+        public QpidByteBufferFragment duplicate()
+        {
+            ByteBuffer buffer = _ref.getBuffer();
+            if (!(_ref instanceof PooledByteBufferRef))
+            {
+                buffer = buffer.duplicate();
+            }
+
+            buffer.position(_offset);
+            buffer.limit(_offset + _buffer.capacity());
+
+            buffer = buffer.slice();
+
+            buffer.limit(_buffer.limit());
+            buffer.position(_buffer.position());
+            return new QpidByteBufferFragment(_ref, buffer, _offset);
+        }
+
+        public final QpidByteBufferFragment put(final byte[] src, final int offset, final int length)
+        {
+            _buffer.put(src, offset, length);
+            return this;
+        }
+
+
+        public int capacity()
+        {
+            return _buffer.capacity();
+        }
+
+
+        public final byte get()
+        {
+            return _buffer.get();
+        }
+
+        public byte get(final int index)
+        {
+            return _buffer.get(index);
+        }
+
+        public QpidByteBufferFragment position(final int newPosition)
+        {
+            _buffer.position(newPosition);
+            return this;
+        }
+
+        public QpidByteBufferFragment slice()
+        {
+            return view(0, _buffer.remaining());
+        }
+
+        public QpidByteBufferFragment view(int offset, int length)
+        {
+            ByteBuffer buffer = _ref.getBuffer();
+            if (!(_ref instanceof PooledByteBufferRef))
+            {
+                buffer = buffer.duplicate();
+            }
+
+            int newRemaining = Math.min(_buffer.remaining() - offset, length);
+
+            int newPosition = _offset + _buffer.position() + offset;
+            buffer.limit(newPosition + newRemaining);
+            buffer.position(newPosition);
+
+            buffer = buffer.slice();
+
+            return new QpidByteBufferFragment(_ref, buffer, newPosition);
+        }
+
+        public int position()
+        {
+            return _buffer.position();
+        }
+
+        ByteBuffer getUnderlyingBuffer()
+        {
+            return _buffer;
+        }
+
+        public static QpidByteBufferFragment allocate(boolean direct, int size)
+        {
+            return direct ? allocateDirect(size) : allocate(size);
+        }
+
+        public static QpidByteBufferFragment allocate(int size)
+        {
+            return new QpidByteBufferFragment(new NonPooledByteBufferRef(ByteBuffer.allocate(size)));
+        }
+
+        public static QpidByteBufferFragment allocateDirect(int size)
+        {
+            if (size < 0)
+            {
+                throw new IllegalArgumentException("Cannot allocate QpidByteBufferFragment with size "
+                                                   + size
+                                                   + " which is negative.");
+            }
+
+            final ByteBufferRef ref;
+            if (_isPoolInitialized && _pooledBufferSize >= size)
+            {
+                if (_pooledBufferSize == size)
+                {
+                    ByteBuffer buf = _bufferPool.getBuffer();
+                    if (buf == null)
+                    {
+                        buf = ByteBuffer.allocateDirect(size);
+                    }
+                    ref = new PooledByteBufferRef(buf);
+                }
+                else
+                {
+                    QpidByteBufferFragment buf = _cachedBuffer.get();
+                    if (buf == null || buf.remaining() < size)
+                    {
+                        if (buf != null)
+                        {
+                            buf.dispose();
+                        }
+                        buf = allocateDirect(_pooledBufferSize);
+                        _cachedBuffer.set(buf);
+                    }
+                    QpidByteBufferFragment rVal = buf.view(0, size);
+                    buf.position(buf.position() + size);
+
+                    return rVal;
+                }
+            }
+            else
+            {
+                ref = new NonPooledByteBufferRef(ByteBuffer.allocateDirect(size));
+            }
+            return new QpidByteBufferFragment(ref);
+        }
+
+        boolean isSparse()
+        {
+            return _ref.isSparse(_sparsityFraction);
         }
+
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBufferInputStream.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBufferInputStream.java b/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBufferInputStream.java
deleted file mode 100644
index d7ce698..0000000
--- a/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBufferInputStream.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-package org.apache.qpid.server.bytebuffer;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collection;
-
-import org.apache.qpid.server.streams.CompositeInputStream;
-
-/**
- * InputStream implementation that takes a list QpidByteBuffers.
- * The QpidByteBufferInputStream takes ownership of the buffers and disposes them on close().
- *
- * Not thread safe.
- */
-public class QpidByteBufferInputStream extends InputStream
-{
-    private final CompositeInputStream _compositeInputStream;
-    private final Collection<QpidByteBuffer> _buffers;
-
-    public QpidByteBufferInputStream(Collection<QpidByteBuffer> buffers)
-    {
-        _buffers = buffers;
-
-        final Collection<InputStream> streams = new ArrayList<>(buffers.size());
-        for (QpidByteBuffer buffer : buffers)
-        {
-            streams.add(buffer.asInputStream());
-        }
-        _compositeInputStream = new CompositeInputStream(streams);
-    }
-
-    @Override
-    public int read() throws IOException
-    {
-        return _compositeInputStream.read();
-    }
-
-    @Override
-    public int read(byte[] b, int off, int len) throws IOException
-    {
-        return _compositeInputStream.read(b, off, len);
-    }
-
-    @Override
-    public void mark(int readlimit)
-    {
-        _compositeInputStream.mark(readlimit);
-    }
-
-    @Override
-    public void reset() throws IOException
-    {
-        _compositeInputStream.reset();
-    }
-
-    @Override
-    public boolean markSupported()
-    {
-        return _compositeInputStream.markSupported();
-    }
-
-    @Override
-    public long skip(long n) throws IOException
-    {
-        return _compositeInputStream.skip(n);
-    }
-
-    @Override
-    public int available() throws IOException
-    {
-        return _compositeInputStream.available();
-    }
-
-    @Override
-    public void close() throws IOException
-    {
-        try
-        {
-            _compositeInputStream.close();
-        }
-        finally
-        {
-            for (QpidByteBuffer buffer : _buffers)
-            {
-                buffer.dispose();
-            }
-        }
-    }
-}

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBufferOutputStream.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBufferOutputStream.java b/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBufferOutputStream.java
index faaa332..08788df 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBufferOutputStream.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBufferOutputStream.java
@@ -23,23 +23,13 @@ package org.apache.qpid.server.bytebuffer;
 
 import java.io.IOException;
 import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.Collection;
 import java.util.LinkedList;
 
-/**
- * OutputStream implementation that yields a list QpidByteBuffers that contain a copy
- * of the incoming bytes.  Use fetchAccumulatedBuffers to get the buffers.  Caller
- * has responsibility to dispose the buffers after use.
- *
- * It will be normally be desirable to front this stream with java.io.BufferedOutputStream
- * to minimise the number of write and thus the number of buffers created.
- *
- * Not thread safe.
- */
 public class QpidByteBufferOutputStream extends OutputStream
 {
     private final LinkedList<QpidByteBuffer> _buffers = new LinkedList<>();
+    private int _bufferPosition = 0;
+    private final byte[] _buffer;
     private final boolean _isDirect;
     private final int _maximumBufferSize;
     private boolean _closed;
@@ -52,14 +42,13 @@ public class QpidByteBufferOutputStream extends OutputStream
         }
         _isDirect = isDirect;
         _maximumBufferSize = maximumBufferSize;
+        _buffer = new byte[_maximumBufferSize];
     }
 
     @Override
     public void write(int b) throws IOException
     {
-        int size = 1;
-        byte[] data = new byte[] {(byte)b};
-        allocateDataBuffers(data, 0, size);
+        write(new byte[] {(byte)b});
     }
 
     @Override
@@ -78,18 +67,18 @@ public class QpidByteBufferOutputStream extends OutputStream
     public void close() throws IOException
     {
         _closed = true;
-        for (QpidByteBuffer buffer : _buffers)
-        {
-            buffer.dispose();
-        }
+        _buffers.forEach(QpidByteBuffer::dispose);
         _buffers.clear();
     }
 
-    public Collection<QpidByteBuffer> fetchAccumulatedBuffers()
+    QpidByteBuffer fetchAccumulatedBuffer()
     {
-        Collection<QpidByteBuffer> bufs = new ArrayList<>(_buffers);
-        _buffers.clear();
-        return bufs;
+        if (_bufferPosition != 0)
+        {
+            addSingleQpidByteBuffer(_buffer, 0, _bufferPosition);
+        }
+        final QpidByteBuffer combined = QpidByteBuffer.concatenate(_buffers);
+        return combined;
     }
 
     private void allocateDataBuffers(byte[] data, int offset, int len) throws IOException
@@ -99,15 +88,28 @@ public class QpidByteBufferOutputStream extends OutputStream
             throw new IOException("Stream is closed");
         }
 
-        int size = Math.min(_maximumBufferSize, len);
+        do
+        {
+            int bytesWeCanWrite = Math.min(_buffer.length - _bufferPosition, len);
+            System.arraycopy(data, offset, _buffer, _bufferPosition, bytesWeCanWrite);
+            offset += bytesWeCanWrite;
+            len -= bytesWeCanWrite;
+            _bufferPosition += bytesWeCanWrite;
+            if (_buffer.length == _bufferPosition)
+            {
+                addSingleQpidByteBuffer(_buffer, 0, _buffer.length);
+            }
+        } while (len != 0);
+    }
 
-        QpidByteBuffer current = _isDirect ? QpidByteBuffer.allocateDirect(len) : QpidByteBuffer.allocate(len);
-        current.put(data, offset, size);
+    private void addSingleQpidByteBuffer(final byte[] buffer, final int offset, final int length)
+    {
+        QpidByteBuffer current = _isDirect
+                ? QpidByteBuffer.allocateDirect(length)
+                : QpidByteBuffer.allocate(length);
+        current.put(buffer, offset, length);
         current.flip();
         _buffers.add(current);
-        if (len > size)
-        {
-            allocateDataBuffers(data, offset + size, len - size);
-        }
+        _bufferPosition = 0;
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBufferUtils.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBufferUtils.java b/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBufferUtils.java
deleted file mode 100644
index a475ef7..0000000
--- a/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/QpidByteBufferUtils.java
+++ /dev/null
@@ -1,285 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.bytebuffer;
-
-import java.nio.BufferUnderflowException;
-import java.util.List;
-
-public class QpidByteBufferUtils
-{
-    public static void dispose(List<QpidByteBuffer> in)
-    {
-        for (int i = 0, inSize = in.size(); i < inSize; i++)
-        {
-            final QpidByteBuffer qpidByteBuffer = in.get(i);
-            qpidByteBuffer.dispose();
-        }
-    }
-
-    public static boolean hasRemaining(List<QpidByteBuffer> in)
-    {
-        if (in.isEmpty())
-        {
-            return false;
-        }
-        for (int i = 0; i < in.size(); i++)
-        {
-            if (in.get(i).hasRemaining())
-            {
-                return true;
-            }
-        }
-        return false;
-    }
-
-    public static long remaining(List<QpidByteBuffer> in)
-    {
-        long remaining = 0L;
-        for (int i = 0; i < in.size(); i++)
-        {
-            remaining += in.get(i).remaining();
-        }
-        return remaining;
-    }
-
-    public static byte get(List<QpidByteBuffer> in)
-    {
-        for (int i = 0; i < in.size(); i++)
-        {
-            final QpidByteBuffer buffer = in.get(i);
-            if (buffer.hasRemaining())
-            {
-                return buffer.get();
-            }
-        }
-        throw new BufferUnderflowException();
-    }
-
-    public static boolean hasRemaining(final List<QpidByteBuffer> in, int len)
-    {
-        for (int i = 0; i < in.size(); i++)
-        {
-            final QpidByteBuffer buffer = in.get(i);
-            int remaining = buffer.remaining();
-            if (remaining >= len)
-            {
-                return true;
-            }
-            len -= remaining;
-        }
-
-        return false;
-    }
-
-    public static long getLong(final List<QpidByteBuffer> in)
-    {
-        boolean bytewise = false;
-        int consumed = 0;
-        long result = 0L;
-        for (int i = 0; i < in.size(); i++)
-        {
-            final QpidByteBuffer buffer = in.get(i);
-            int remaining = buffer.remaining();
-            if (bytewise)
-            {
-                while (buffer.hasRemaining() && consumed < 8)
-                {
-                    result <<= 1;
-                    result |= (0xFF & buffer.get());
-                    consumed++;
-                }
-                if (consumed == 8)
-                {
-                    return result;
-                }
-            }
-            else
-            {
-                if (remaining >= 8)
-                {
-                    return buffer.getLong();
-                }
-                else if (remaining != 0)
-                {
-                    bytewise = true;
-                    while (buffer.hasRemaining())
-                    {
-                        result <<= 1;
-                        result |= (0xFF & buffer.get());
-                        consumed++;
-                    }
-                }
-            }
-        }
-        throw new BufferUnderflowException();
-    }
-
-    public static int getInt(final List<QpidByteBuffer> in)
-    {
-        boolean bytewise = false;
-        int consumed = 0;
-        int result = 0;
-        for (int i = 0; i < in.size(); i++)
-        {
-            final QpidByteBuffer buffer = in.get(i);
-            int remaining = buffer.remaining();
-            if (bytewise)
-            {
-                while (buffer.hasRemaining() && consumed < 4)
-                {
-                    result <<= 1;
-                    result |= (0xFF & buffer.get());
-                    consumed++;
-                }
-                if (consumed == 4)
-                {
-                    return result;
-                }
-            }
-            else
-            {
-                if (remaining >= 4)
-                {
-                    return buffer.getInt();
-                }
-                else if (remaining != 0)
-                {
-                    bytewise = true;
-                    while (buffer.hasRemaining())
-                    {
-                        result <<= 1;
-                        result |= (0xFF & buffer.get());
-                        consumed++;
-                    }
-                }
-            }
-        }
-        throw new BufferUnderflowException();
-    }
-
-    public static float getFloat(final List<QpidByteBuffer> in)
-    {
-        return Float.intBitsToFloat(getInt(in));
-    }
-
-    public static double getDouble(final List<QpidByteBuffer> in)
-    {
-        return Double.longBitsToDouble(getLong(in));
-    }
-
-    public static Short getShort(final List<QpidByteBuffer> in)
-    {
-        boolean bytewise = false;
-        int consumed = 0;
-        short result = 0;
-        for (int i = 0; i < in.size(); i++)
-        {
-            final QpidByteBuffer buffer = in.get(i);
-            int remaining = buffer.remaining();
-            if (bytewise)
-            {
-                while (buffer.hasRemaining() && consumed < 2)
-                {
-                    result <<= 1;
-                    result |= (0xFF & buffer.get());
-                    consumed++;
-                }
-                if (consumed == 2)
-                {
-                    return result;
-                }
-            }
-            else
-            {
-                if (remaining >= 2)
-                {
-                    return buffer.getShort();
-                }
-                else if (remaining != 0)
-                {
-                    bytewise = true;
-                    while (buffer.hasRemaining())
-                    {
-                        result <<= 1;
-                        result |= (0xFF & buffer.get());
-                        consumed++;
-                    }
-                }
-            }
-        }
-        throw new BufferUnderflowException();
-    }
-
-    public static int get(final List<QpidByteBuffer> in, final byte[] data)
-    {
-        int copied = 0;
-        int i = 0;
-        while (copied < data.length && i < in.size())
-        {
-            QpidByteBuffer buf = in.get(i);
-            if (buf.hasRemaining())
-            {
-                int remaining = buf.remaining();
-                if (remaining >= data.length - copied)
-                {
-                    buf.get(data, copied, data.length - copied);
-                    return data.length;
-                }
-                else
-                {
-                    buf.get(data, copied, remaining);
-                    copied += remaining;
-                }
-            }
-            i++;
-        }
-        return copied;
-    }
-
-    public static void skip(final List<QpidByteBuffer> in, int length)
-    {
-        int skipped = 0;
-        int i = 0;
-        while (skipped < length && i < in.size())
-        {
-            QpidByteBuffer buf = in.get(i);
-            if (buf.hasRemaining())
-            {
-                int remaining = buf.remaining();
-                if (remaining >= length - skipped)
-                {
-                    buf.position(buf.position() + length - skipped);
-                    return;
-                }
-                else
-                {
-                    buf.position(buf.position() + remaining);
-                    skipped += remaining;
-                }
-            }
-            i++;
-        }
-
-        if (skipped != length)
-        {
-            throw new BufferUnderflowException();
-        }
-    }
-}


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[07/10] qpid-broker-j git commit: QPID-7832: [Java Broker] Refactor store/protocol API using Collection

Posted by lq...@apache.org.
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferTest.java
----------------------------------------------------------------------
diff --git a/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferTest.java b/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferTest.java
index d98c4f1..3653c05 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferTest.java
@@ -29,23 +29,19 @@ import java.lang.reflect.Method;
 import java.nio.BufferOverflowException;
 import java.nio.BufferUnderflowException;
 import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
+import java.nio.InvalidMarkException;
 import java.nio.charset.StandardCharsets;
 import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
 
 import com.google.common.io.ByteStreams;
 import org.junit.Assert;
 import org.mockito.internal.util.Primitives;
 
 import org.apache.qpid.test.utils.QpidTestCase;
-import org.apache.qpid.server.util.ByteBufferUtils;
 
 public class QpidByteBufferTest extends QpidTestCase
 {
+    private static final int BUFFER_FRAGMENT_SIZE = 5;
     private static final int BUFFER_SIZE = 10;
     private static final int POOL_SIZE = 20;
     private static final double SPARSITY_FRACTION = 0.5;
@@ -59,20 +55,29 @@ public class QpidByteBufferTest extends QpidTestCase
     {
         super.setUp();
         QpidByteBuffer.deinitialisePool();
-        QpidByteBuffer.initialisePool(BUFFER_SIZE, POOL_SIZE, SPARSITY_FRACTION);
+        QpidByteBuffer.initialisePool(BUFFER_FRAGMENT_SIZE, POOL_SIZE, SPARSITY_FRACTION);
         _parent = QpidByteBuffer.allocateDirect(BUFFER_SIZE);
     }
 
     @Override
     public void tearDown() throws Exception
     {
-        super.tearDown();
-        _parent.dispose();
-        if (_slicedBuffer != null)
+        try
         {
-            _slicedBuffer.dispose();
+            super.tearDown();
+        }
+        finally
+        {
+            if (_parent != null)
+            {
+                _parent.dispose();
+            }
+            if (_slicedBuffer != null)
+            {
+                _slicedBuffer.dispose();
+            }
+            QpidByteBuffer.deinitialisePool();
         }
-        QpidByteBuffer.deinitialisePool();
     }
 
     public void testPutGetByIndex() throws Exception
@@ -113,6 +118,25 @@ public class QpidByteBufferTest extends QpidTestCase
         assertEquals("Unexpected position after reset", 0, _slicedBuffer.position());
     }
 
+    public void testMarkResetAcrossFragmentBoundary() throws Exception
+    {
+        for (int i = 0; i < BUFFER_SIZE; ++i)
+        {
+            _parent.put((byte) i);
+        }
+        _parent.flip();
+        _parent.mark();
+        for (int i = 0; i < BUFFER_FRAGMENT_SIZE + 2; ++i)
+        {
+            assertEquals("Unexpected value", i, _parent.get());
+        }
+        _parent.reset();
+        for (int i = 0; i < BUFFER_SIZE; ++i)
+        {
+            assertEquals("Unexpected value", i, _parent.get());
+        }
+    }
+
     public void testPosition() throws Exception
     {
         _slicedBuffer = createSlice();
@@ -135,155 +159,102 @@ public class QpidByteBufferTest extends QpidTestCase
         }
     }
 
-    public void testBulkPutGet() throws Exception
+    public void testSettingPositionBackwardsResetsMark()
     {
-        _slicedBuffer = createSlice();
-
-        final byte[] source = getTestBytes(_slicedBuffer.remaining());
-
-        QpidByteBuffer rv = _slicedBuffer.put(source, 0, source.length);
-        assertEquals("Unexpected builder return value", _slicedBuffer, rv);
-
-        _slicedBuffer.flip();
-        byte[] target = new byte[_slicedBuffer.remaining()];
-        rv = _slicedBuffer.get(target, 0, target.length);
-        assertEquals("Unexpected builder return value", _slicedBuffer, rv);
-
-        Assert.assertArrayEquals("Unexpected bulk put/get result", source, target);
-
-
-        _slicedBuffer.clear();
-        _slicedBuffer.position(1);
-
+        _parent.position(8);
+        _parent.mark();
+        _parent.position(7);
         try
         {
-            _slicedBuffer.put(source, 0, source.length);
-            fail("Exception not thrown");
+            _parent.reset();
+            fail("Expected exception not thrown");
         }
-        catch (BufferOverflowException e)
+        catch (InvalidMarkException e)
         {
             // pass
         }
+    }
 
-        assertEquals("Position should be unchanged after failed put", 1, _slicedBuffer.position());
+    public void testSettingPositionForwardDoeNotResetMark()
+    {
+        final int originalPosition = 3;
+        _parent.position(originalPosition);
+        _parent.mark();
+        _parent.position(9);
+
+        _parent.reset();
+
+        assertEquals("Unexpected position", originalPosition, _parent.position());
+    }
+
+    public void testRewind() throws Exception
+    {
+        final int expectedLimit = 7;
+        _parent.position(1);
+        _parent.limit(expectedLimit);
+        _parent.mark();
+        _parent.position(3);
+
+        _parent.rewind();
 
+        assertEquals("Unexpected position", 0, _parent.position());
+        assertEquals("Unexpected limit", expectedLimit, _parent.limit());
         try
         {
-            _slicedBuffer.get(target, 0, target.length);
-            fail("Exception not thrown");
+            _parent.reset();
+            fail("Expected exception not thrown");
         }
-        catch (BufferUnderflowException e)
+        catch (InvalidMarkException e)
         {
             // pass
         }
-
-        assertEquals("Position should be unchanged after failed get", 1, _slicedBuffer.position());
-
-
     }
 
-    public void testByteBufferPutGet()
+    public void testBulkPutGet() throws Exception
     {
         _slicedBuffer = createSlice();
-        final byte[] source = getTestBytes(_slicedBuffer.remaining());
 
-        ByteBuffer sourceByteBuffer = ByteBuffer.wrap(source);
+        final byte[] source = getTestBytes(_slicedBuffer.remaining());
 
-        QpidByteBuffer rv = _slicedBuffer.put(sourceByteBuffer);
+        QpidByteBuffer rv = _slicedBuffer.put(source, 0, source.length);
         assertEquals("Unexpected builder return value", _slicedBuffer, rv);
 
-        assertEquals("Unexpected position", _slicedBuffer.capacity(), _slicedBuffer.position());
-        assertEquals("Unexpected remaining", 0, _slicedBuffer.remaining());
-
-        assertEquals("Unexpected remaining in source ByteBuffer", 0, sourceByteBuffer.remaining());
-
         _slicedBuffer.flip();
+        byte[] target = new byte[_slicedBuffer.remaining()];
+        rv = _slicedBuffer.get(target, 0, target.length);
+        assertEquals("Unexpected builder return value", _slicedBuffer, rv);
 
-        ByteBuffer destinationByteBuffer =  ByteBuffer.allocate(source.length);
-        _slicedBuffer.get(destinationByteBuffer);
-
-
-        assertEquals("Unexpected remaining", 0, _slicedBuffer.remaining());
-
-        assertEquals("Unexpected remaining in destination ByteBuffer", 0, destinationByteBuffer.remaining());
-        assertEquals("Unexpected position in destination ByteBuffer", source.length, destinationByteBuffer.position());
+        Assert.assertArrayEquals("Unexpected bulk put/get result", source, target);
 
-        Assert.assertArrayEquals("Unexpected ByteBuffer put/get result", source, destinationByteBuffer.array());
 
         _slicedBuffer.clear();
         _slicedBuffer.position(1);
 
-        sourceByteBuffer.clear();
         try
         {
-            _slicedBuffer.put(sourceByteBuffer);
-            fail("Exception should be thrown");
+            _slicedBuffer.put(source, 0, source.length);
+            fail("Exception not thrown");
         }
-        catch(BufferOverflowException e)
+        catch (BufferOverflowException e)
         {
             // pass
         }
 
-        assertEquals("Position should not be changed after failed put", 1, _slicedBuffer.position());
-        assertEquals("Source position should not changed after failed put", source.length, sourceByteBuffer.remaining());
-
-        _slicedBuffer.clear();
-        destinationByteBuffer.position(1);
+        assertEquals("Position should be unchanged after failed put", 1, _slicedBuffer.position());
 
         try
         {
-            _slicedBuffer.get(destinationByteBuffer);
-            fail("Exception should be thrown");
+            _slicedBuffer.get(target, 0, target.length);
+            fail("Exception not thrown");
         }
-        catch(BufferUnderflowException e )
+        catch (BufferUnderflowException e)
         {
             // pass
         }
-    }
-
-    public void testQpidByteBufferPutGet()
-    {
-        _slicedBuffer = createSlice();
-        final byte[] source = getTestBytes(_slicedBuffer.remaining());
-
-        QpidByteBuffer sourceQpidByteBuffer = QpidByteBuffer.wrap(source);
 
-        QpidByteBuffer rv = _slicedBuffer.put(sourceQpidByteBuffer);
-        assertEquals("Unexpected builder return value", _slicedBuffer, rv);
-
-        assertEquals("Unexpected position", _slicedBuffer.capacity(), _slicedBuffer.position());
-        assertEquals("Unexpected remaining", 0, _slicedBuffer.remaining());
-
-        assertEquals("Unexpected remaining in source QpidByteBuffer", 0, sourceQpidByteBuffer.remaining());
-
-        _slicedBuffer.flip();
-
-        ByteBuffer destinationByteBuffer =  ByteBuffer.allocate(source.length);
-        _slicedBuffer.get(destinationByteBuffer);
-
-        assertEquals("Unexpected remaining", 0, _slicedBuffer.remaining());
-
-        assertEquals("Unexpected remaining in destination ByteBuffer", 0, destinationByteBuffer.remaining());
-        assertEquals("Unexpected position in destination ByteBuffer", source.length, destinationByteBuffer.position());
-
-        Assert.assertArrayEquals("Unexpected ByteBuffer put/get result", source, destinationByteBuffer.array());
-
-        _slicedBuffer.clear();
-        _slicedBuffer.position(1);
+        assertEquals("Position should be unchanged after failed get", 1, _slicedBuffer.position());
 
-        sourceQpidByteBuffer.clear();
-        try
-        {
-            _slicedBuffer.put(sourceQpidByteBuffer);
-            fail("Exception should be thrown");
-        }
-        catch(BufferOverflowException e)
-        {
-            // pass
-        }
 
-        assertEquals("Position should not be changed after failed put", 1, _slicedBuffer.position());
-        assertEquals("Source position should not changed after failed put", source.length, sourceQpidByteBuffer.remaining());
     }
 
     public void testDuplicate()
@@ -293,8 +264,7 @@ public class QpidByteBufferTest extends QpidTestCase
         int originalLimit = _slicedBuffer.limit();
         _slicedBuffer.limit(originalLimit - 1);
 
-        QpidByteBuffer duplicate = _slicedBuffer.duplicate();
-        try
+        try (QpidByteBuffer duplicate = _slicedBuffer.duplicate())
         {
             assertEquals("Unexpected position", _slicedBuffer.position(), duplicate.position() );
             assertEquals("Unexpected limit", _slicedBuffer.limit(), duplicate.limit() );
@@ -306,10 +276,6 @@ public class QpidByteBufferTest extends QpidTestCase
             assertEquals("Unexpected position in the original", 1, _slicedBuffer.position());
             assertEquals("Unexpected limit in the original", originalLimit -1, _slicedBuffer.limit());
         }
-        finally
-        {
-            duplicate.dispose();
-        }
     }
 
     public void testCopyToByteBuffer()
@@ -400,8 +366,8 @@ public class QpidByteBufferTest extends QpidTestCase
         _slicedBuffer.limit(_slicedBuffer.limit() - 1);
 
         int remaining = _slicedBuffer.remaining();
-        QpidByteBuffer newSlice = _slicedBuffer.slice();
-        try
+
+        try (QpidByteBuffer newSlice = _slicedBuffer.slice())
         {
             assertEquals("Unexpected position in original", 1, _slicedBuffer.position());
             assertEquals("Unexpected limit in original", source.length - 1, _slicedBuffer.limit());
@@ -416,10 +382,6 @@ public class QpidByteBufferTest extends QpidTestCase
             System.arraycopy(source, 1, expected, 0, expected.length);
             Assert.assertArrayEquals("Unexpected slice result", expected, destination);
         }
-        finally
-        {
-            newSlice.dispose();
-        }
     }
 
     public void testViewOfSlice()
@@ -431,8 +393,7 @@ public class QpidByteBufferTest extends QpidTestCase
         _slicedBuffer.position(1);
         _slicedBuffer.limit(_slicedBuffer.limit() - 1);
 
-        QpidByteBuffer view = _slicedBuffer.view(0, _slicedBuffer.remaining());
-        try
+        try (QpidByteBuffer view = _slicedBuffer.view(0, _slicedBuffer.remaining()))
         {
             assertEquals("Unexpected position in original", 1, _slicedBuffer.position());
             assertEquals("Unexpected limit in original", source.length - 1, _slicedBuffer.limit());
@@ -448,13 +409,8 @@ public class QpidByteBufferTest extends QpidTestCase
             System.arraycopy(source, 1, expected, 0, expected.length);
             Assert.assertArrayEquals("Unexpected view result", expected, destination);
         }
-        finally
-        {
-            view.dispose();
-        }
 
-        view = _slicedBuffer.view(1, _slicedBuffer.remaining() - 2);
-        try
+        try (QpidByteBuffer view = _slicedBuffer.view(1, _slicedBuffer.remaining() - 2))
         {
             assertEquals("Unexpected position in original", 1, _slicedBuffer.position());
             assertEquals("Unexpected limit in original", source.length - 1, _slicedBuffer.limit());
@@ -470,10 +426,6 @@ public class QpidByteBufferTest extends QpidTestCase
             System.arraycopy(source, 2, expected, 0, expected.length);
             Assert.assertArrayEquals("Unexpected view result", expected, destination);
         }
-        finally
-        {
-            view.dispose();
-        }
     }
 
     public void testAsInputStream() throws Exception
@@ -496,40 +448,6 @@ public class QpidByteBufferTest extends QpidTestCase
         Assert.assertArrayEquals("Unexpected view result", expected, destination.toByteArray());
     }
 
-    public void testAsByteBuffer() throws Exception
-    {
-        _slicedBuffer = createSlice();
-
-        _slicedBuffer.position(1);
-        _slicedBuffer.limit(_slicedBuffer.limit() - 1);
-
-        _slicedBuffer.mark();
-        int remaining = _slicedBuffer.remaining();
-        byte[] source = getTestBytes(remaining);
-        _slicedBuffer.put(source);
-        _slicedBuffer.reset();
-
-        ByteBuffer buffer = _slicedBuffer.asByteBuffer();
-        assertEquals("Unexpected remaining", remaining, buffer.remaining());
-
-        byte[] target = new byte[remaining];
-        buffer.get(target);
-        Assert.assertArrayEquals("Unexpected asByteBuffer result", source, target);
-    }
-
-    public void testDecode()
-    {
-        _slicedBuffer = createSlice();
-        final String input = "ABC";
-        _slicedBuffer.put(input.getBytes());
-        _slicedBuffer.flip();
-
-        final CharBuffer charBuffer = _slicedBuffer.decode(StandardCharsets.US_ASCII);
-        final char[] destination = new char[charBuffer.remaining()];
-        charBuffer.get(destination);
-        Assert.assertArrayEquals("Unexpected char buffer", input.toCharArray(), destination);
-    }
-
     private byte[] getTestBytes(final int length)
     {
         final byte[] source = new byte[length];
@@ -598,6 +516,8 @@ public class QpidByteBufferTest extends QpidTestCase
         {
             // pass
         }
+        _slicedBuffer.dispose();
+        _slicedBuffer = null;
     }
 
     private void testPutGetByIndex(final Class<?> primitiveTargetClass, Object value) throws Exception
@@ -659,6 +579,8 @@ public class QpidByteBufferTest extends QpidTestCase
         {
             // pass
         }
+        _slicedBuffer.dispose();
+        _slicedBuffer = null;
     }
 
     private void invokeMethod(final Method method, final Object... value)
@@ -734,41 +656,49 @@ public class QpidByteBufferTest extends QpidTestCase
 
     public void testPooledBufferIsZeroedLoan() throws Exception
     {
-        QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(BUFFER_SIZE);
-
-        buffer.put((byte) 0xFF);
-        buffer.dispose();
+        try (QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(BUFFER_SIZE))
+        {
+            buffer.put((byte) 0xFF);
+        }
 
-        buffer = QpidByteBuffer.allocateDirect(BUFFER_SIZE);
-        buffer.limit(1);
-        assertEquals("Pooled QpidByteBuffer is not zeroed.", (byte) 0x0, buffer.get());
+        try (QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(BUFFER_SIZE))
+        {
+            buffer.limit(1);
+            assertEquals("Pooled QpidByteBuffer is not zeroed.", (byte) 0x0, buffer.get());
+        }
     }
 
     public void testAllocateDirectOfSameSize() throws Exception
     {
         int bufferSize = BUFFER_SIZE;
-        QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(bufferSize);
-        assertEquals("Unexpected buffer size", bufferSize, buffer.capacity());
-        assertEquals("Unexpected position on newly created buffer", 0, buffer.position());
-        assertEquals("Unexpected limit on newly created buffer", bufferSize, buffer.limit());
+        try (QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(bufferSize))
+        {
+            assertEquals("Unexpected buffer size", bufferSize, buffer.capacity());
+            assertEquals("Unexpected position on newly created buffer", 0, buffer.position());
+            assertEquals("Unexpected limit on newly created buffer", bufferSize, buffer.limit());
+        }
     }
 
     public void testAllocateDirectOfSmallerSize() throws Exception
     {
         int bufferSize = BUFFER_SIZE - 1;
-        QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(bufferSize);
-        assertEquals("Unexpected buffer size", bufferSize, buffer.capacity());
-        assertEquals("Unexpected position on newly created buffer", 0, buffer.position());
-        assertEquals("Unexpected limit on newly created buffer", bufferSize, buffer.limit());
+        try (QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(bufferSize))
+        {
+            assertEquals("Unexpected buffer size", bufferSize, buffer.capacity());
+            assertEquals("Unexpected position on newly created buffer", 0, buffer.position());
+            assertEquals("Unexpected limit on newly created buffer", bufferSize, buffer.limit());
+        }
     }
 
     public void testAllocateDirectOfLargerSize() throws Exception
     {
         int bufferSize = BUFFER_SIZE + 1;
-        QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(bufferSize);
-        assertEquals("Unexpected buffer size", bufferSize, buffer.capacity());
-        assertEquals("Unexpected position on newly created buffer", 0, buffer.position());
-        assertEquals("Unexpected limit on newly created buffer", bufferSize, buffer.limit());
+        try (QpidByteBuffer buffer = QpidByteBuffer.allocateDirect(bufferSize))
+        {
+            assertEquals("Unexpected buffer size", bufferSize, buffer.capacity());
+            assertEquals("Unexpected position on newly created buffer", 0, buffer.position());
+            assertEquals("Unexpected limit on newly created buffer", bufferSize, buffer.limit());
+        }
     }
 
     public void testAllocateDirectWithNegativeSize() throws Exception
@@ -800,37 +730,34 @@ public class QpidByteBufferTest extends QpidTestCase
     public void testDeflateInflateDirect() throws Exception
     {
         byte[] input = "aaabbbcccddddeeeffff".getBytes();
-        Collection<QpidByteBuffer> inputBufs = QpidByteBuffer.allocateDirectCollection(input.length);
-
-        int offset = 0;
-        for (QpidByteBuffer buf : inputBufs)
+        try (QpidByteBuffer inputBuf = QpidByteBuffer.allocateDirect(input.length))
         {
-            int len = buf.remaining();
-            buf.put(input, offset, len);
-            buf.flip();
-            offset += len;
-        }
-        assertEquals(input.length, ByteBufferUtils.remaining(inputBufs));
+            inputBuf.put(input);
+            inputBuf.flip();
+
+            assertEquals(input.length, inputBuf.remaining());
 
-        doDeflateInflate(input, inputBufs, true);
+            doDeflateInflate(input, inputBuf, true);
+        }
     }
 
     public void testDeflateInflateHeap() throws Exception
     {
         byte[] input = "aaabbbcccddddeeeffff".getBytes();
-        Collection<QpidByteBuffer> inputBufs = Collections.singleton(QpidByteBuffer.wrap(input));
 
-        doDeflateInflate(input, inputBufs, false);
+        try (QpidByteBuffer buffer = QpidByteBuffer.wrap(input))
+        {
+            doDeflateInflate(input, buffer, false);
+        }
     }
 
     public void testInflatingUncompressedBytes_ThrowsZipException() throws Exception
     {
         byte[] input = "not_a_compressed_stream".getBytes();
-        QpidByteBuffer original = QpidByteBuffer.wrap(input);
 
-        try
+        try (QpidByteBuffer original = QpidByteBuffer.wrap(input))
         {
-            QpidByteBuffer.inflate(Collections.singleton(original));
+            QpidByteBuffer.inflate(original);
             fail("Exception not thrown");
         }
         catch(java.util.zip.ZipException ze)
@@ -841,109 +768,127 @@ public class QpidByteBufferTest extends QpidTestCase
 
     public void testSlice() throws Exception
     {
-        QpidByteBuffer directBuffer = QpidByteBuffer.allocate(true, 6);
-        directBuffer.position(2);
-        directBuffer.limit(5);
-        QpidByteBuffer directSlice = directBuffer.slice();
-
-        assertTrue("Direct slice should be direct too", directSlice.isDirect());
-        assertEquals("Unexpected capacity", 3, directSlice.capacity());
-        assertEquals("Unexpected limit", 3, directSlice.limit());
-        assertEquals("Unexpected position", 0, directSlice.position());
-
-        directBuffer.dispose();
-        directSlice.dispose();
+        try (QpidByteBuffer directBuffer = QpidByteBuffer.allocate(true, 6))
+        {
+            directBuffer.position(2);
+            directBuffer.limit(5);
+            try (QpidByteBuffer directSlice = directBuffer.slice())
+            {
+                assertTrue("Direct slice should be direct too", directSlice.isDirect());
+                assertEquals("Unexpected capacity", 3, directSlice.capacity());
+                assertEquals("Unexpected limit", 3, directSlice.limit());
+                assertEquals("Unexpected position", 0, directSlice.position());
+            }
+        }
     }
 
     public void testView() throws Exception
     {
         byte[] content = "ABCDEF".getBytes();
-        QpidByteBuffer buffer = QpidByteBuffer.allocate(true, content.length);
-        buffer.put(content);
-        buffer.position(2);
-        buffer.limit(5);
-
-        QpidByteBuffer view = buffer.view(0, buffer.remaining());
-
-        assertTrue("Unexpected view direct", view.isDirect());
-
-        assertEquals("Unexpected capacity", 3, view.capacity());
-        assertEquals("Unexpected limit", 3, view.limit());
-        assertEquals("Unexpected position", 0, view.position());
-
-        byte[] destination = new byte[view.remaining()];
-        view.get(destination);
-
-        Assert.assertArrayEquals("CDE".getBytes(), destination);
-
-        QpidByteBuffer viewWithOffset = buffer.view(1, 1);
-        destination = new byte[viewWithOffset.remaining()];
-        viewWithOffset.get(destination);
+        try (QpidByteBuffer buffer = QpidByteBuffer.allocate(true, content.length))
+        {
+            buffer.put(content);
+            buffer.position(2);
+            buffer.limit(5);
 
-        Assert.assertArrayEquals("D".getBytes(), destination);
+            try (QpidByteBuffer view = buffer.view(0, buffer.remaining()))
+            {
+                assertTrue("Unexpected view direct", view.isDirect());
+                assertEquals("Unexpected capacity", 3, view.capacity());
+                assertEquals("Unexpected limit", 3, view.limit());
+                assertEquals("Unexpected position", 0, view.position());
+
+                final byte[] destination = new byte[view.remaining()];
+                view.get(destination);
+                Assert.assertArrayEquals("CDE".getBytes(), destination);
+            }
 
-        buffer.dispose();
-        view.dispose();
-        viewWithOffset.dispose();
+            try (QpidByteBuffer viewWithOffset = buffer.view(1, 1))
+            {
+                final byte[] destination = new byte[viewWithOffset.remaining()];
+                viewWithOffset.get(destination);
+                Assert.assertArrayEquals("D".getBytes(), destination);
+            }
+        }
     }
 
     public void testSparsity()
     {
         assertFalse("Unexpected sparsity after creation", _parent.isSparse());
-        QpidByteBuffer child = _parent.view(0, 6);
+        QpidByteBuffer child = _parent.view(0, 8);
         QpidByteBuffer grandChild = child.view(0, 2);
 
         assertFalse("Unexpected sparsity after child creation", _parent.isSparse());
         _parent.dispose();
+        _parent = null;
 
         assertFalse("Unexpected sparsity after parent disposal", child.isSparse());
 
         child.dispose();
         assertTrue("Buffer should be sparse", grandChild.isSparse());
+        grandChild.dispose();
     }
 
     public void testAsQpidByteBuffers() throws IOException
     {
         byte[] dataForTwoBufs = "01234567890".getBytes(StandardCharsets.US_ASCII);
-        Collection<QpidByteBuffer> qpidByteBuffers = QpidByteBuffer.asQpidByteBuffers(new ByteArrayInputStream(dataForTwoBufs));
-        assertEquals("Unexpected number of bufs", 2, qpidByteBuffers.size());
-        Iterator<QpidByteBuffer> itr = qpidByteBuffers.iterator();
-        assertEquals("Unexpected remaining in first buf", 10, itr.next().remaining());
-        assertEquals("Unexpected remaining in second buf", 1, itr.next().remaining());
+        try (QpidByteBuffer qpidByteBuffer = QpidByteBuffer.asQpidByteBuffer(new ByteArrayInputStream(dataForTwoBufs)))
+        {
+            assertEquals("Unexpected remaining in buf", 11, qpidByteBuffer.remaining());
+        }
+
+        try (QpidByteBuffer bufsForEmptyBytes = QpidByteBuffer.asQpidByteBuffer(new ByteArrayInputStream(new byte[]{})))
+        {
+            assertEquals("Unexpected remaining in buf for empty buffer", 0, bufsForEmptyBytes.remaining());
+        }
+    }
+
+    public void testConcatenate() throws Exception
+    {
+        try (QpidByteBuffer buffer1 = QpidByteBuffer.allocateDirect(10);
+             QpidByteBuffer buffer2 = QpidByteBuffer.allocateDirect(10))
+        {
+            final short buffer1Value = (short) (1 << 15);
+            buffer1.putShort(buffer1Value);
+            buffer1.flip();
+            final char buffer2Value = 'x';
+            buffer2.putChar(2, buffer2Value);
+            buffer2.position(4);
+            buffer2.flip();
 
-        Collection<QpidByteBuffer> bufsForEmptyBytes = QpidByteBuffer.asQpidByteBuffers(new ByteArrayInputStream(new byte[]{}));
-        assertEquals("Unexpected number of bufs for empty buffer", 0, bufsForEmptyBytes.size());
+            try (QpidByteBuffer concatenate = QpidByteBuffer.concatenate(buffer1, buffer2))
+            {
+                assertEquals("Unexpected capacity", 6, concatenate.capacity());
+                assertEquals("Unexpected position", 0, concatenate.position());
+                assertEquals("Unexpected limit", 6, concatenate.limit());
+                assertEquals("Unexpected value 1", buffer1Value, concatenate.getShort());
+                assertEquals("Unexpected value 2", buffer2Value, concatenate.getChar(4));
+            }
+        }
     }
 
     private void doDeflateInflate(byte[] input,
-                                  Collection<QpidByteBuffer> inputBufs,
+                                  QpidByteBuffer inputBuf,
                                   boolean direct) throws IOException
     {
-        Collection<QpidByteBuffer> deflatedBufs = QpidByteBuffer.deflate(inputBufs);
-        assertNotNull(deflatedBufs);
+        try (QpidByteBuffer deflatedBuf = QpidByteBuffer.deflate(inputBuf))
+        {
+            assertNotNull(deflatedBuf);
 
-        Collection<QpidByteBuffer> inflatedBufs = QpidByteBuffer.inflate(deflatedBufs);
-        assertNotNull(inflatedBufs);
-        assertTrue("Expected at least on buffer", inflatedBufs.size() >= 1);
+            try (QpidByteBuffer inflatedBuf = QpidByteBuffer.inflate(deflatedBuf))
+            {
+                assertNotNull(inflatedBuf);
 
-        int bufNum = 1;
-        int inputOffset = 0;
-        int inflatedBytesTotal = 0;
-        for(QpidByteBuffer inflatedBuf : inflatedBufs)
-        {
-            int inflatedBytesCount = inflatedBuf.remaining();
-            inflatedBytesTotal += inflatedBytesCount;
+                int inflatedBytesCount = inflatedBuf.remaining();
 
-            byte[] inflatedBytes = new byte[inflatedBytesCount];
-            inflatedBuf.get(inflatedBytes);
-            byte[] expectedBytes = Arrays.copyOfRange(input, inputOffset, inputOffset + inflatedBytes.length);
-            Assert.assertArrayEquals("Inflated buf" + bufNum + " has unexpected content", expectedBytes, inflatedBytes);
+                byte[] inflatedBytes = new byte[inflatedBytesCount];
+                inflatedBuf.get(inflatedBytes);
+                byte[] expectedBytes = Arrays.copyOfRange(input, 0, inflatedBytes.length);
+                Assert.assertArrayEquals("Inflated buf has unexpected content", expectedBytes, inflatedBytes);
 
-            inputOffset += inflatedBytes.length;
-            bufNum++;
+                assertEquals("Unexpected number of inflated bytes", input.length, inflatedBytesCount);
+            }
         }
-
-        assertEquals("Unexpected number of inflated bytes", input.length, inflatedBytesTotal);
     }
 
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/test/java/org/apache/qpid/server/protocol/v0_8/FieldTableTest.java
----------------------------------------------------------------------
diff --git a/broker-core/src/test/java/org/apache/qpid/server/protocol/v0_8/FieldTableTest.java b/broker-core/src/test/java/org/apache/qpid/server/protocol/v0_8/FieldTableTest.java
index 8a85614..40241c9 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/protocol/v0_8/FieldTableTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/protocol/v0_8/FieldTableTest.java
@@ -598,11 +598,11 @@ public class FieldTableTest extends QpidTestCase
         buf.flip();
 
         long length = buf.getInt() & 0xFFFFFFFFL;
-        buf = buf.slice();
-        buf.limit((int)length);
+        QpidByteBuffer bufSlice = buf.slice();
+        bufSlice.limit((int)length);
 
 
-        FieldTable table2 = new FieldTable(buf);
+        FieldTable table2 = new FieldTable(bufSlice);
 
         Assert.assertEquals((Boolean) true, table2.getBoolean("bool"));
         Assert.assertEquals((Byte) Byte.MAX_VALUE, table2.getByte("byte"));
@@ -615,6 +615,10 @@ public class FieldTableTest extends QpidTestCase
         Assert.assertEquals(Short.valueOf(Short.MAX_VALUE), table2.getShort("short"));
         Assert.assertEquals("hello", table2.getString("string"));
         Assert.assertNull(table2.getString("null-string"));
+        buf.dispose();
+        bufSlice.dispose();
+        table.dispose();
+        table2.dispose();
     }
 
     public void testEncodingSize()

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/test/java/org/apache/qpid/server/security/TrustStoreMessageSourceTest.java
----------------------------------------------------------------------
diff --git a/broker-core/src/test/java/org/apache/qpid/server/security/TrustStoreMessageSourceTest.java b/broker-core/src/test/java/org/apache/qpid/server/security/TrustStoreMessageSourceTest.java
index 19c16e4..978008e 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/security/TrustStoreMessageSourceTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/security/TrustStoreMessageSourceTest.java
@@ -19,10 +19,8 @@
 package org.apache.qpid.server.security;
 
 import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertNotNull;
 import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import java.io.ByteArrayInputStream;
@@ -31,19 +29,18 @@ import java.io.ObjectInputStream;
 import java.security.cert.Certificate;
 import java.security.cert.CertificateEncodingException;
 import java.util.ArrayList;
-import java.util.Collection;
 import java.util.EnumSet;
 import java.util.List;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.consumer.ConsumerOption;
 import org.apache.qpid.server.consumer.ConsumerTarget;
+import org.apache.qpid.server.message.MessageContainer;
 import org.apache.qpid.server.message.MessageInstanceConsumer;
 import org.apache.qpid.server.message.ServerMessage;
 import org.apache.qpid.server.model.State;
 import org.apache.qpid.server.model.TrustStore;
 import org.apache.qpid.server.model.VirtualHost;
-import org.apache.qpid.server.message.MessageContainer;
 import org.apache.qpid.server.store.MessageStore;
 import org.apache.qpid.server.store.TestMemoryMessageStore;
 import org.apache.qpid.test.utils.QpidTestCase;
@@ -96,19 +93,16 @@ public class TrustStoreMessageSourceTest extends QpidTestCase
     {
         final int bodySize = (int) message.getSize();
         byte[] msgContent = new byte[bodySize];
-        final Collection<QpidByteBuffer> allData = message.getStoredMessage().getContent(0, bodySize);
-        int total = 0;
-        for(QpidByteBuffer b : allData)
+        final List<String> certificates;
+        final ByteArrayInputStream bytesIn;
+        try (QpidByteBuffer allData = message.getStoredMessage().getContent(0, bodySize))
         {
-            int len = b.remaining();
-            b.get(msgContent, total, len);
-            b.dispose();
-            total += len;
+            assertEquals("Unexpected message size was retrieved", bodySize, allData.remaining());
+            allData.get(msgContent);
         }
-        assertEquals("Unexpected message size was retrieved", bodySize, total);
 
-        List<String> certificates = new ArrayList<>();
-        ByteArrayInputStream bytesIn = new ByteArrayInputStream(msgContent);
+        certificates = new ArrayList<>();
+        bytesIn = new ByteArrayInputStream(msgContent);
         try (ObjectInputStream is = new ObjectInputStream(bytesIn))
         {
             ArrayList<byte[]> encodedCertificates = (ArrayList<byte[]>) is.readObject();

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/test/java/org/apache/qpid/server/store/MessageStoreTestCase.java
----------------------------------------------------------------------
diff --git a/broker-core/src/test/java/org/apache/qpid/server/store/MessageStoreTestCase.java b/broker-core/src/test/java/org/apache/qpid/server/store/MessageStoreTestCase.java
index f2750f4..7f7f16a 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/store/MessageStoreTestCase.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/store/MessageStoreTestCase.java
@@ -366,18 +366,6 @@ public abstract class MessageStoreTestCase extends QpidTestCase
         assertTrue("Message with id " + messageId3 + " is not found", enqueuedIds.contains(messageId3));
     }
 
-    public void testStoreIgnoresTransientMessage() throws Exception
-    {
-        long messageId = 1;
-        int contentSize = 0;
-        final StoredMessage<TestMessageMetaData> message = _store.addMessage(new TestMessageMetaData(messageId, contentSize, false)).allContentAdded();
-
-        MessageHandler handler = mock(MessageHandler.class);
-        _storeReader.visitMessages(handler);
-
-        verify(handler, times(0)).handle(argThat(new MessageMetaDataMatcher(messageId)));
-    }
-
     public void testAddAndRemoveMessageWithoutContent() throws Exception
     {
         long messageId = 1;

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/test/java/org/apache/qpid/server/store/TestMessageMetaDataFactory.java
----------------------------------------------------------------------
diff --git a/broker-core/src/test/java/org/apache/qpid/server/store/TestMessageMetaDataFactory.java b/broker-core/src/test/java/org/apache/qpid/server/store/TestMessageMetaDataFactory.java
index ee67dd2..1abf0c0 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/store/TestMessageMetaDataFactory.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/store/TestMessageMetaDataFactory.java
@@ -20,19 +20,16 @@
  */
 package org.apache.qpid.server.store;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.plugin.MessageMetaDataType;
 
 public class TestMessageMetaDataFactory implements MessageMetaDataType.Factory<TestMessageMetaData>
 {
     @Override
-    public TestMessageMetaData createMetaData(List<QpidByteBuffer> bufs)
+    public TestMessageMetaData createMetaData(QpidByteBuffer buf)
     {
-        long id = QpidByteBufferUtils.getLong(bufs);
-        int size = QpidByteBufferUtils.getInt(bufs);
+        long id = buf.getLong();
+        int size = buf.getInt();
 
         return new TestMessageMetaData(id, size);
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/test/java/org/apache/qpid/server/store/TestMessageMetaDataType.java
----------------------------------------------------------------------
diff --git a/broker-core/src/test/java/org/apache/qpid/server/store/TestMessageMetaDataType.java b/broker-core/src/test/java/org/apache/qpid/server/store/TestMessageMetaDataType.java
index 50d9428..231dd35 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/store/TestMessageMetaDataType.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/store/TestMessageMetaDataType.java
@@ -20,9 +20,6 @@
  */
 package org.apache.qpid.server.store;
 
-import java.util.Collection;
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.AMQMessageHeader;
 import org.apache.qpid.server.message.MessageReference;
@@ -42,9 +39,9 @@ public class TestMessageMetaDataType implements MessageMetaDataType<TestMessageM
     }
 
     @Override
-    public TestMessageMetaData createMetaData(List<QpidByteBuffer> bufs)
+    public TestMessageMetaData createMetaData(QpidByteBuffer buf)
     {
-        return TestMessageMetaData.FACTORY.createMetaData(bufs);
+        return TestMessageMetaData.FACTORY.createMetaData(buf);
     }
 
     @Override
@@ -108,7 +105,13 @@ public class TestMessageMetaDataType implements MessageMetaDataType<TestMessageM
         }
 
         @Override
-        public Collection<QpidByteBuffer> getContent(int offset, int length)
+        public QpidByteBuffer getContent()
+        {
+            return null;
+        }
+
+        @Override
+        public QpidByteBuffer getContent(int offset, int length)
         {
             return null;
         }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java
----------------------------------------------------------------------
diff --git a/broker-core/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java b/broker-core/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java
index da61a64..3ccc94b 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/txn/MockServerMessage.java
@@ -20,8 +20,6 @@
  */
 package org.apache.qpid.server.txn;
 
-import java.util.Collection;
-
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.AMQMessageHeader;
@@ -127,7 +125,13 @@ class MockServerMessage implements ServerMessage
     }
 
     @Override
-    public Collection<QpidByteBuffer> getContent(int offset, int length)
+    public QpidByteBuffer getContent()
+    {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public QpidByteBuffer getContent(int offset, int length)
     {
         throw new UnsupportedOperationException();
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostPropertiesNodeTest.java
----------------------------------------------------------------------
diff --git a/broker-core/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostPropertiesNodeTest.java b/broker-core/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostPropertiesNodeTest.java
index d5e184d..9af3300 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostPropertiesNodeTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/virtualhost/VirtualHostPropertiesNodeTest.java
@@ -58,5 +58,9 @@ public class VirtualHostPropertiesNodeTest extends QpidTestCase
         MessageInstanceConsumer consumer = _virtualHostPropertiesNode.addConsumer(target, null, ServerMessage.class, getTestName(), options, 0);
         final MessageContainer messageContainer = consumer.pullMessage();
         assertNotNull("Could not pull message from VirtualHostPropertyNode", messageContainer);
+        if (messageContainer.getMessageReference() != null)
+        {
+            messageContainer.getMessageReference().release();
+        }
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ConsumerTarget_0_10.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ConsumerTarget_0_10.java b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ConsumerTarget_0_10.java
index e342db7..ce5551f 100644
--- a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ConsumerTarget_0_10.java
+++ b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ConsumerTarget_0_10.java
@@ -21,10 +21,8 @@
 package org.apache.qpid.server.protocol.v0_10;
 
 import java.io.IOException;
-import java.util.Collection;
 import java.util.Map;
 import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicLong;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -39,16 +37,9 @@ import org.apache.qpid.server.message.MessageInstance.ConsumerAcquiredState;
 import org.apache.qpid.server.message.MessageInstance.EntryState;
 import org.apache.qpid.server.message.MessageInstanceConsumer;
 import org.apache.qpid.server.message.ServerMessage;
-import org.apache.qpid.server.model.Exchange;
 import org.apache.qpid.server.model.Queue;
 import org.apache.qpid.server.plugin.MessageConverter;
 import org.apache.qpid.server.protocol.MessageConverterRegistry;
-import org.apache.qpid.server.store.TransactionLogResource;
-import org.apache.qpid.server.txn.AutoCommitTransaction;
-import org.apache.qpid.server.txn.ServerTransaction;
-import org.apache.qpid.server.util.Action;
-import org.apache.qpid.server.util.ConnectionScopedRuntimeException;
-import org.apache.qpid.server.util.StateChangeListener;
 import org.apache.qpid.server.protocol.v0_10.transport.DeliveryProperties;
 import org.apache.qpid.server.protocol.v0_10.transport.Header;
 import org.apache.qpid.server.protocol.v0_10.transport.MessageAcceptMode;
@@ -59,8 +50,13 @@ import org.apache.qpid.server.protocol.v0_10.transport.MessageProperties;
 import org.apache.qpid.server.protocol.v0_10.transport.MessageTransfer;
 import org.apache.qpid.server.protocol.v0_10.transport.Method;
 import org.apache.qpid.server.protocol.v0_10.transport.Option;
-import org.apache.qpid.server.util.ByteBufferUtils;
+import org.apache.qpid.server.store.TransactionLogResource;
+import org.apache.qpid.server.txn.AutoCommitTransaction;
+import org.apache.qpid.server.txn.ServerTransaction;
+import org.apache.qpid.server.util.Action;
+import org.apache.qpid.server.util.ConnectionScopedRuntimeException;
 import org.apache.qpid.server.util.GZIPUtils;
+import org.apache.qpid.server.util.StateChangeListener;
 
 public class ConsumerTarget_0_10 extends AbstractConsumerTarget<ConsumerTarget_0_10>
 {
@@ -254,50 +250,41 @@ public class ConsumerTarget_0_10 extends AbstractConsumerTarget<ConsumerTarget_0
         boolean msgCompressed = messageProps != null && GZIPUtils.GZIP_CONTENT_ENCODING.equals(messageProps.getContentEncoding());
 
 
-        Collection<QpidByteBuffer> bodyBuffers = msg.getBody();
+        QpidByteBuffer bodyBuffer = msg.getBody();
 
         boolean compressionSupported = _session.getConnection().getConnectionDelegate().isCompressionSupported();
 
-        if(msgCompressed && !compressionSupported && bodyBuffers != null)
+        if(msgCompressed && !compressionSupported && bodyBuffer != null)
         {
-            Collection<QpidByteBuffer> uncompressedBuffers = inflateIfPossible(bodyBuffers);
+            QpidByteBuffer uncompressedBuffer = inflateIfPossible(bodyBuffer);
             messageProps.setContentEncoding(null);
-            for (QpidByteBuffer buf : bodyBuffers)
-            {
-                buf.dispose();
-            }
-            bodyBuffers = uncompressedBuffers;
+            bodyBuffer.dispose();
+            bodyBuffer = uncompressedBuffer;
         }
         else if(!msgCompressed
                 && compressionSupported
                 && (messageProps == null || messageProps.getContentEncoding() == null)
-                && bodyBuffers != null
-                && ByteBufferUtils.remaining(bodyBuffers) > _session.getConnection().getMessageCompressionThreshold())
+                && bodyBuffer != null
+                && bodyBuffer.remaining() > _session.getConnection().getMessageCompressionThreshold())
         {
-            Collection<QpidByteBuffer> compressedBuffers = deflateIfPossible(bodyBuffers);
+            QpidByteBuffer compressedBuffers = deflateIfPossible(bodyBuffer);
             if(messageProps == null)
             {
                 messageProps = new MessageProperties();
             }
             messageProps.setContentEncoding(GZIPUtils.GZIP_CONTENT_ENCODING);
-            for (QpidByteBuffer buf : bodyBuffers)
-            {
-                buf.dispose();
-            }
-            bodyBuffers = compressedBuffers;
+            bodyBuffer.dispose();
+            bodyBuffer = compressedBuffers;
         }
 
         Header header = new Header(deliveryProps, messageProps, msg.getHeader() == null ? null : msg.getHeader().getNonStandardProperties());
 
-        xfr = batch ? new MessageTransfer(_name,_acceptMode,_acquireMode,header, bodyBuffers, BATCHED)
-                    : new MessageTransfer(_name,_acceptMode,_acquireMode,header, bodyBuffers);
-        if (bodyBuffers != null)
+        xfr = batch ? new MessageTransfer(_name, _acceptMode, _acquireMode, header, bodyBuffer, BATCHED)
+                    : new MessageTransfer(_name, _acceptMode, _acquireMode, header, bodyBuffer);
+        if (bodyBuffer != null)
         {
-            for (QpidByteBuffer buf : bodyBuffers)
-            {
-                buf.dispose();
-            }
-            bodyBuffers = null;
+            bodyBuffer.dispose();
+            bodyBuffer = null;
         }
         if(_acceptMode == MessageAcceptMode.NONE && _acquireMode != MessageAcquireMode.PRE_ACQUIRED)
         {
@@ -612,11 +599,11 @@ public class ConsumerTarget_0_10 extends AbstractConsumerTarget<ConsumerTarget_0
     }
 
 
-    private Collection<QpidByteBuffer> deflateIfPossible(final Collection<QpidByteBuffer> buffers)
+    private QpidByteBuffer deflateIfPossible(final QpidByteBuffer buffer)
     {
         try
         {
-            return QpidByteBuffer.deflate(buffers);
+            return QpidByteBuffer.deflate(buffer);
         }
         catch (IOException e)
         {
@@ -625,11 +612,11 @@ public class ConsumerTarget_0_10 extends AbstractConsumerTarget<ConsumerTarget_0
         }
     }
 
-    private Collection<QpidByteBuffer> inflateIfPossible(final Collection<QpidByteBuffer> buffers)
+    private QpidByteBuffer inflateIfPossible(final QpidByteBuffer buffer)
     {
         try
         {
-            return QpidByteBuffer.inflate(buffers);
+            return QpidByteBuffer.inflate(buffer);
         }
         catch (IOException e)
         {

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_Internal_to_v0_10.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_Internal_to_v0_10.java b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_Internal_to_v0_10.java
index 4ffbd3f..114b0f2 100644
--- a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_Internal_to_v0_10.java
+++ b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_Internal_to_v0_10.java
@@ -22,8 +22,6 @@ package org.apache.qpid.server.protocol.v0_10;
 
 import static java.nio.charset.StandardCharsets.UTF_8;
 
-import java.util.Collection;
-import java.util.Collections;
 import java.util.UUID;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
@@ -107,9 +105,9 @@ public class MessageConverter_Internal_to_v0_10 implements MessageConverter<Inte
                     }
 
                     @Override
-                    public Collection<QpidByteBuffer> getContent(final int offset, final int length)
+                    public QpidByteBuffer getContent(final int offset, final int length)
                     {
-                        return Collections.singleton(QpidByteBuffer.wrap(messageContent, offset, length));
+                        return QpidByteBuffer.wrap(messageContent, offset, length);
                     }
 
                     @Override

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10.java b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10.java
index dfdbc9a..8c9db87 100644
--- a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10.java
+++ b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10.java
@@ -22,8 +22,6 @@ package org.apache.qpid.server.protocol.v0_10;
 
 import static java.nio.charset.StandardCharsets.UTF_8;
 
-import java.util.Collection;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.ServerMessage;
 import org.apache.qpid.server.model.NamedAddressSpace;
@@ -83,7 +81,7 @@ public class MessageConverter_v0_10 implements MessageConverter<ServerMessage, M
                     }
 
                     @Override
-                    public Collection<QpidByteBuffer> getContent(final int offset, final int length)
+                    public QpidByteBuffer getContent(final int offset, final int length)
                     {
                         return serverMsg.getContent(offset, length);
                     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10_to_Internal.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10_to_Internal.java b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10_to_Internal.java
index 0610d09..8121dd6 100644
--- a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10_to_Internal.java
+++ b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_v0_10_to_Internal.java
@@ -67,13 +67,9 @@ public class MessageConverter_v0_10_to_Internal implements MessageConverter<Mess
     {
         final String mimeType = serverMessage.getMessageHeader().getMimeType();
         byte[] data = new byte[(int) serverMessage.getSize()];
-        int total = 0;
-        for(QpidByteBuffer b : serverMessage.getContent(0, (int) serverMessage.getSize()))
+        try (QpidByteBuffer content = serverMessage.getContent())
         {
-            int len = b.remaining();
-            b.get(data, total, len);
-            b.dispose();
-            total += len;
+            content.get(data);
         }
 
         String encoding = serverMessage.getMessageHeader().getEncoding();

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageFormat_0_10.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageFormat_0_10.java b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageFormat_0_10.java
index f74e291..de9afcc 100644
--- a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageFormat_0_10.java
+++ b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageFormat_0_10.java
@@ -27,14 +27,14 @@ import java.util.List;
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.plugin.MessageFormat;
 import org.apache.qpid.server.plugin.PluggableService;
-import org.apache.qpid.server.store.MessageHandle;
-import org.apache.qpid.server.store.MessageStore;
-import org.apache.qpid.server.store.StoredMessage;
-import org.apache.qpid.server.util.ConnectionScopedRuntimeException;
 import org.apache.qpid.server.protocol.v0_10.transport.DeliveryProperties;
 import org.apache.qpid.server.protocol.v0_10.transport.Header;
 import org.apache.qpid.server.protocol.v0_10.transport.MessageProperties;
 import org.apache.qpid.server.protocol.v0_10.transport.Struct;
+import org.apache.qpid.server.store.MessageHandle;
+import org.apache.qpid.server.store.MessageStore;
+import org.apache.qpid.server.store.StoredMessage;
+import org.apache.qpid.server.util.ConnectionScopedRuntimeException;
 
 @PluggableService
 public class MessageFormat_0_10 implements MessageFormat<MessageTransferMessage>
@@ -63,7 +63,7 @@ public class MessageFormat_0_10 implements MessageFormat<MessageTransferMessage>
     // format: <int header count> <headers> <body>
 
     @Override
-    public List<QpidByteBuffer> convertToMessageFormat(final MessageTransferMessage message)
+    public QpidByteBuffer convertToMessageFormat(final MessageTransferMessage message)
     {
         ServerEncoder encoder = new ServerEncoder(4096, true);
         Struct[] structs = message.getHeader().getStructs();
@@ -72,22 +72,21 @@ public class MessageFormat_0_10 implements MessageFormat<MessageTransferMessage>
         {
             encoder.writeStruct32(struct);
         }
-        final QpidByteBuffer headerBuf = encoder.getBuffer();
-        List<QpidByteBuffer> bufs = new ArrayList<>();
-        bufs.add(headerBuf);
-        bufs.addAll(message.getContent(0, (int) message.getSize()));
-
-        return bufs;
+        try (QpidByteBuffer headerBuf = encoder.getBuffer();
+             QpidByteBuffer content = message.getContent())
+        {
+            return QpidByteBuffer.concatenate(headerBuf, content);
+        }
     }
 
     @Override
-    public MessageTransferMessage createMessage(final List<QpidByteBuffer> buf,
+    public MessageTransferMessage createMessage(final QpidByteBuffer payload,
                                                 final MessageStore store,
                                                 final Object connectionReference)
     {
         try
         {
-            ServerDecoder serverDecoder = new ServerDecoder(buf);
+            ServerDecoder serverDecoder = new ServerDecoder(payload);
             int headerCount = serverDecoder.readInt32();
             DeliveryProperties deliveryProperties = null;
             MessageProperties messageProperties = null;
@@ -113,20 +112,11 @@ public class MessageFormat_0_10 implements MessageFormat<MessageTransferMessage>
                 }
             }
             Header header = new Header(deliveryProperties, messageProperties, nonStandard);
-            int bodySize = 0;
-            for(QpidByteBuffer content : buf)
-            {
-                bodySize += content.remaining();
-            }
-            MessageMetaData_0_10 metaData = new MessageMetaData_0_10(header, bodySize, System.currentTimeMillis());
+            MessageMetaData_0_10 metaData = new MessageMetaData_0_10(header,
+                                                                     payload.remaining(),
+                                                                     System.currentTimeMillis());
             final MessageHandle<MessageMetaData_0_10> handle = store.addMessage(metaData);
-            for (QpidByteBuffer content : buf)
-            {
-                if (content.hasRemaining())
-                {
-                    handle.addContent(content);
-                }
-            }
+            handle.addContent(payload);
             final StoredMessage<MessageMetaData_0_10> storedMessage = handle.allContentAdded();
             return new MessageTransferMessage(storedMessage, connectionReference);
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaDataType_0_10.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaDataType_0_10.java b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaDataType_0_10.java
index 2dcb5f5..bc3cbed 100644
--- a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaDataType_0_10.java
+++ b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaDataType_0_10.java
@@ -20,8 +20,6 @@
  */
 package org.apache.qpid.server.protocol.v0_10;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.ServerMessage;
 import org.apache.qpid.server.plugin.MessageMetaDataType;
@@ -42,9 +40,9 @@ public class MessageMetaDataType_0_10 implements MessageMetaDataType<MessageMeta
     }
 
     @Override
-    public MessageMetaData_0_10 createMetaData(List<QpidByteBuffer> bufs)
+    public MessageMetaData_0_10 createMetaData(QpidByteBuffer buf)
     {
-        return MessageMetaData_0_10.FACTORY.createMetaData(bufs);
+        return MessageMetaData_0_10.FACTORY.createMetaData(buf);
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaData_0_10.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaData_0_10.java b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaData_0_10.java
index 2861cc2..d51b158 100755
--- a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaData_0_10.java
+++ b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageMetaData_0_10.java
@@ -263,7 +263,7 @@ public class MessageMetaData_0_10 implements StorableMessageMetaData
     private static class MetaDataFactory implements MessageMetaDataType.Factory<MessageMetaData_0_10>
     {
         @Override
-        public MessageMetaData_0_10 createMetaData(List<QpidByteBuffer> buf)
+        public MessageMetaData_0_10 createMetaData(QpidByteBuffer buf)
         {
             ServerDecoder decoder = new ServerDecoder(buf);
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferMessage.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferMessage.java b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferMessage.java
index e6b2c8d..ba35c01 100644
--- a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferMessage.java
+++ b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/MessageTransferMessage.java
@@ -20,14 +20,12 @@
  */
 package org.apache.qpid.server.protocol.v0_10;
 
-import java.util.Collection;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.AMQMessageHeader;
 import org.apache.qpid.server.message.AbstractServerMessageImpl;
+import org.apache.qpid.server.protocol.v0_10.transport.Header;
 import org.apache.qpid.server.store.StoredMessage;
 import org.apache.qpid.server.store.TransactionLogResource;
-import org.apache.qpid.server.protocol.v0_10.transport.Header;
 
 
 public class MessageTransferMessage extends AbstractServerMessageImpl<MessageTransferMessage, MessageMetaData_0_10>
@@ -102,8 +100,8 @@ public class MessageTransferMessage extends AbstractServerMessageImpl<MessageTra
         return getMetaData().getHeader();
     }
 
-    public Collection<QpidByteBuffer> getBody()
+    public QpidByteBuffer getBody()
     {
-        return  getContent(0, (int) getSize());
+        return  getContent();
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerAssembler.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerAssembler.java b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerAssembler.java
index f3dde0d..abe0842 100644
--- a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerAssembler.java
+++ b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerAssembler.java
@@ -26,9 +26,7 @@ import java.security.AccessControlContext;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 
@@ -39,6 +37,7 @@ import org.slf4j.LoggerFactory;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v0_10.transport.DeliveryProperties;
+import org.apache.qpid.server.protocol.v0_10.transport.Frame;
 import org.apache.qpid.server.protocol.v0_10.transport.Header;
 import org.apache.qpid.server.protocol.v0_10.transport.MessageProperties;
 import org.apache.qpid.server.protocol.v0_10.transport.Method;
@@ -46,7 +45,6 @@ import org.apache.qpid.server.protocol.v0_10.transport.ProtocolError;
 import org.apache.qpid.server.protocol.v0_10.transport.ProtocolEvent;
 import org.apache.qpid.server.protocol.v0_10.transport.ProtocolHeader;
 import org.apache.qpid.server.protocol.v0_10.transport.Struct;
-import org.apache.qpid.server.protocol.v0_10.transport.Frame;
 
 public class ServerAssembler
 {
@@ -77,35 +75,54 @@ public class ServerAssembler
         {
             PeekingIterator<ServerFrame> itr = Iterators.peekingIterator(frames.iterator());
 
-            while(itr.hasNext())
+            boolean cleanExit = false;
+            try
             {
-                final ServerFrame frame = itr.next();
-                final int frameChannel = frame.getChannel();
-
-                ServerSession channel = _connection.getSession(frameChannel);
-                if (channel != null)
+                while(itr.hasNext())
                 {
-                    final AccessControlContext context = channel.getAccessControllerContext();
-                    AccessController.doPrivileged((PrivilegedAction<Void>) () ->
+                    final ServerFrame frame = itr.next();
+                    final int frameChannel = frame.getChannel();
+
+                    ServerSession channel = _connection.getSession(frameChannel);
+                    if (channel != null)
                     {
-                        ServerFrame channelFrame = frame;
-                        boolean nextIsSameChannel;
-                        do
+                        final AccessControlContext context = channel.getAccessControllerContext();
+                        AccessController.doPrivileged((PrivilegedAction<Void>) () ->
                         {
-                            received(channelFrame);
-                            nextIsSameChannel = itr.hasNext() && frameChannel == itr.peek().getChannel();
-                            if (nextIsSameChannel)
+                            ServerFrame channelFrame = frame;
+                            boolean nextIsSameChannel;
+                            do
                             {
-                                channelFrame = itr.next();
+                                received(channelFrame);
+                                nextIsSameChannel = itr.hasNext() && frameChannel == itr.peek().getChannel();
+                                if (nextIsSameChannel)
+                                {
+                                    channelFrame = itr.next();
+                                }
                             }
-                        }
-                        while (nextIsSameChannel);
-                        return null;
-                    }, context);
+                            while (nextIsSameChannel);
+                            return null;
+                        }, context);
+                    }
+                    else
+                    {
+                        received(frame);
+                    }
                 }
-                else
+                cleanExit = true;
+            }
+            finally
+            {
+                if (!cleanExit)
                 {
-                    received(frame);
+                    while (itr.hasNext())
+                    {
+                        final QpidByteBuffer body = itr.next().getBody();
+                        if (body != null)
+                        {
+                            body.dispose();
+                        }
+                    }
                 }
             }
         }
@@ -183,11 +200,9 @@ public class ServerAssembler
 
     public void frame(ServerFrame frame)
     {
-        List<QpidByteBuffer> frameBuffers;
         if (frame.isFirstFrame() && frame.isLastFrame())
         {
-            frameBuffers = Collections.singletonList(frame.getBody());
-            assemble(frame, frameBuffers);
+            assemble(frame, frame.getBody());
         }
         else
         {
@@ -207,98 +222,103 @@ public class ServerAssembler
             if (frame.isLastFrame())
             {
                 clearSegment(frame);
-                frameBuffers = new ArrayList<>(frames.size());
+                List<QpidByteBuffer> frameBuffers = new ArrayList<>(frames.size());
                 for (ServerFrame f : frames)
                 {
-
                     frameBuffers.add(f.getBody());
                 }
-                assemble(frame, frameBuffers);
+                QpidByteBuffer combined = QpidByteBuffer.concatenate(frameBuffers);
+                for (QpidByteBuffer buffer : frameBuffers)
+                {
+                    buffer.dispose();
+                }
+                assemble(frame, combined);
             }
         }
 
     }
 
-    private void assemble(ServerFrame frame, List<QpidByteBuffer> frameBuffers)
+    private void assemble(ServerFrame frame, QpidByteBuffer frameBuffer)
     {
-        ServerDecoder dec = new ServerDecoder(frameBuffers);
+        try
+        {
+            ServerDecoder dec = new ServerDecoder(frameBuffer);
 
-        int channel = frame.getChannel();
-        Method command;
+            int channel = frame.getChannel();
+            Method command;
 
-        switch (frame.getType())
-        {
-            case CONTROL:
-                int controlType = dec.readUint16();
-                Method control = Method.create(controlType);
-                control.read(dec);
-                emit(channel, control);
-                break;
-            case COMMAND:
-                int commandType = dec.readUint16();
-                // read in the session header, right now we don't use it
-                int hdr = dec.readUint16();
-                command = Method.create(commandType);
-                command.setSync((0x0001 & hdr) != 0);
-                command.read(dec);
-                if (command.hasPayload() && !frame.isLastSegment())
-                {
-                    setIncompleteCommand(channel, command);
-                }
-                else
-                {
-                    emit(channel, command);
-                }
-                break;
-            case HEADER:
-                command = getIncompleteCommand(channel);
-                List<Struct> structs = null;
-                DeliveryProperties deliveryProps = null;
-                MessageProperties messageProps = null;
-
-                while (dec.hasRemaining())
-                {
-                    Struct struct = dec.readStruct32();
-                    if(struct instanceof  DeliveryProperties && deliveryProps == null)
+            switch (frame.getType())
+            {
+                case CONTROL:
+                    int controlType = dec.readUint16();
+                    Method control = Method.create(controlType);
+                    control.read(dec);
+                    emit(channel, control);
+                    break;
+                case COMMAND:
+                    int commandType = dec.readUint16();
+                    // read in the session header, right now we don't use it
+                    int hdr = dec.readUint16();
+                    command = Method.create(commandType);
+                    command.setSync((0x0001 & hdr) != 0);
+                    command.read(dec);
+                    if (command.hasPayload() && !frame.isLastSegment())
                     {
-                        deliveryProps = (DeliveryProperties) struct;
+                        setIncompleteCommand(channel, command);
                     }
-                    else if(struct instanceof MessageProperties && messageProps == null)
+                    else
                     {
-                        messageProps = (MessageProperties) struct;
+                        emit(channel, command);
                     }
-                    else
+                    break;
+                case HEADER:
+                    command = getIncompleteCommand(channel);
+                    List<Struct> structs = null;
+                    DeliveryProperties deliveryProps = null;
+                    MessageProperties messageProps = null;
+
+                    while (dec.hasRemaining())
                     {
-                        if(structs == null)
+                        Struct struct = dec.readStruct32();
+                        if (struct instanceof DeliveryProperties && deliveryProps == null)
+                        {
+                            deliveryProps = (DeliveryProperties) struct;
+                        }
+                        else if (struct instanceof MessageProperties && messageProps == null)
+                        {
+                            messageProps = (MessageProperties) struct;
+                        }
+                        else
                         {
-                            structs = new ArrayList<>(2);
+                            if (structs == null)
+                            {
+                                structs = new ArrayList<>(2);
+                            }
+                            structs.add(struct);
                         }
-                        structs.add(struct);
                     }
+                    command.setHeader(new Header(deliveryProps, messageProps, structs));
 
-                }
-                command.setHeader(new Header(deliveryProps,messageProps,structs));
-
-                if (frame.isLastSegment())
-                {
+                    if (frame.isLastSegment())
+                    {
+                        setIncompleteCommand(channel, null);
+                        emit(channel, command);
+                    }
+                    break;
+                case BODY:
+                    command = getIncompleteCommand(channel);
+                    command.setBody(frameBuffer);
                     setIncompleteCommand(channel, null);
                     emit(channel, command);
-                }
-                break;
-            case BODY:
-                command = getIncompleteCommand(channel);
-                command.setBody(frameBuffers);
-                setIncompleteCommand(channel, null);
-                emit(channel, command);
-
-                break;
-            default:
-                throw new IllegalStateException("unknown frame type: " + frame.getType());
-        }
 
-        for(QpidByteBuffer buf : frameBuffers)
+                    break;
+                default:
+                    throw new IllegalStateException("unknown frame type: " + frame.getType());
+            }
+        }
+        finally
         {
-            buf.dispose();
+            frameBuffer.dispose();
         }
     }
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnection.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnection.java b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnection.java
index 11e2ab5..8032b35 100644
--- a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnection.java
+++ b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerConnection.java
@@ -61,13 +61,15 @@ import org.apache.qpid.server.protocol.v0_10.transport.ConnectionCloseOk;
 import org.apache.qpid.server.protocol.v0_10.transport.ConnectionException;
 import org.apache.qpid.server.protocol.v0_10.transport.ExecutionErrorCode;
 import org.apache.qpid.server.protocol.v0_10.transport.ExecutionException;
+import org.apache.qpid.server.protocol.v0_10.transport.MessageTransfer;
 import org.apache.qpid.server.protocol.v0_10.transport.Method;
 import org.apache.qpid.server.protocol.v0_10.transport.Option;
 import org.apache.qpid.server.protocol.v0_10.transport.ProtocolEvent;
 import org.apache.qpid.server.protocol.v0_10.transport.SessionDetachCode;
 import org.apache.qpid.server.protocol.v0_10.transport.SessionDetached;
 import org.apache.qpid.server.session.AMQPSession;
-import org.apache.qpid.server.transport.*;
+import org.apache.qpid.server.transport.AMQPConnection;
+import org.apache.qpid.server.transport.ServerNetworkConnection;
 import org.apache.qpid.server.transport.network.NetworkConnection;
 import org.apache.qpid.server.util.Action;
 import org.apache.qpid.server.util.ServerScopedRuntimeException;
@@ -276,6 +278,13 @@ public class ServerConnection extends ConnectionInvoker
             }
             event.delegate(this, delegate);
         }
+        else
+        {
+            if (event instanceof MessageTransfer)
+            {
+                ((MessageTransfer) event).dispose();
+            }
+        }
     }
 
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerDecoder.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerDecoder.java b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerDecoder.java
index 04819f0..5d26d59 100644
--- a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerDecoder.java
+++ b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerDecoder.java
@@ -20,137 +20,58 @@
  */
 package org.apache.qpid.server.protocol.v0_10;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v0_10.transport.AbstractDecoder;
 
 final class ServerDecoder extends AbstractDecoder
 {
-    private final List<QpidByteBuffer> _underlying;
-    private int _bufferIndex;
+    private final QpidByteBuffer _underlying;
 
-    ServerDecoder(List<QpidByteBuffer> in)
+    ServerDecoder(QpidByteBuffer in)
     {
         _underlying = in;
-        _bufferIndex = 0;
-    }
-
-    private void advanceIfNecessary()
-    {
-        while(!getCurrentBuffer().hasRemaining() && _bufferIndex != _underlying.size()-1)
-        {
-            _bufferIndex++;
-        }
-    }
-
-    private QpidByteBuffer getBuffer(int size)
-    {
-        advanceIfNecessary();
-        final QpidByteBuffer currentBuffer = getCurrentBuffer();
-        if(currentBuffer.remaining()>= size)
-        {
-            return currentBuffer;
-        }
-        else
-        {
-            return readAsQpidByteBuffer(size);
-        }
-    }
-
-    private QpidByteBuffer readAsQpidByteBuffer(int len)
-    {
-        QpidByteBuffer currentBuffer = getCurrentBuffer();
-        if(currentBuffer.remaining()>=len)
-        {
-            QpidByteBuffer buf = currentBuffer.slice();
-            buf.limit(len);
-            currentBuffer.position(currentBuffer.position()+len);
-            return buf;
-        }
-        else
-        {
-            QpidByteBuffer dest = QpidByteBuffer.allocate(len);
-            while(dest.hasRemaining() && available()>0)
-            {
-                advanceIfNecessary();
-                currentBuffer = getCurrentBuffer();
-                final int remaining = dest.remaining();
-                if(currentBuffer.remaining()>= remaining)
-                {
-                    QpidByteBuffer buf = currentBuffer.slice();
-                    buf.limit(remaining);
-                    currentBuffer.position(currentBuffer.position()+remaining);
-                    dest.put(buf);
-                    buf.dispose();
-                }
-                else
-                {
-                    dest.put(currentBuffer);
-                }
-            }
-
-            dest.flip();
-            return dest;
-        }
-    }
-
-    private int available()
-    {
-        int remaining = 0;
-        for(int i = _bufferIndex; i < _underlying.size(); i++)
-        {
-            remaining += _underlying.get(i).remaining();
-        }
-        return remaining;
-    }
-
-
-    private QpidByteBuffer getCurrentBuffer()
-    {
-        return _underlying.get(_bufferIndex);
     }
 
     @Override
     protected byte doGet()
     {
-        return getBuffer(1).get();
+        return _underlying.get();
     }
 
     @Override
     protected void doGet(byte[] bytes)
     {
-        getBuffer(bytes.length).get(bytes);
+        _underlying.get(bytes);
     }
 
     @Override
     public boolean hasRemaining()
     {
-        return available() != 0;
+        return _underlying.remaining() != 0;
     }
 
     @Override
     public short readUint8()
     {
-        return (short) (0xFF & getBuffer(1).get());
+        return _underlying.getUnsignedByte();
     }
 
     @Override
     public int readUint16()
     {
-        return 0xFFFF & getBuffer(2).getShort();
+        return _underlying.getUnsignedShort();
     }
 
     @Override
     public long readUint32()
     {
-        return 0xFFFFFFFFL & getBuffer(4).getInt();
+        return _underlying.getUnsignedInt();
     }
 
     @Override
     public long readUint64()
     {
-        return getBuffer(8).getLong();
+        return _underlying.getLong();
     }
 
 	@Override
@@ -172,44 +93,44 @@ final class ServerDecoder extends AbstractDecoder
 	@Override
     public double readDouble()
 	{
-		return getBuffer(8).getDouble();
+        return _underlying.getDouble();
 	}
 
 	@Override
     public float readFloat()
 	{
-		return getBuffer(4).getFloat();
+        return _underlying.getFloat();
 	}
 
 	@Override
     public short readInt16()
 	{
-		return getBuffer(2).getShort();
+        return _underlying.getShort();
 	}
 
 	@Override
     public int readInt32()
 	{
-		return getBuffer(4).getInt();
+        return _underlying.getInt();
 	}
 
 	@Override
     public byte readInt8()
 	{
-		return getBuffer(1).get();
+        return _underlying.get();
 	}
 
 	@Override
     public byte[] readRemainingBytes()
 	{
-      byte[] result = new byte[available()];
-      get(result);
-      return result;		
-	}
+        byte[] result = new byte[_underlying.remaining()];
+        get(result);
+        return result;
+    }
 
 	@Override
     public long readInt64()
 	{
-		return getBuffer(8).getLong();
+        return _underlying.getLong();
 	}
 }


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[08/10] qpid-broker-j git commit: QPID-7832: [Java Broker] Refactor store/protocol API using Collection

Posted by lq...@apache.org.
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/configuration/updater/TaskExecutorImpl.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/configuration/updater/TaskExecutorImpl.java b/broker-core/src/main/java/org/apache/qpid/server/configuration/updater/TaskExecutorImpl.java
index dbab00f..c7280c0 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/configuration/updater/TaskExecutorImpl.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/configuration/updater/TaskExecutorImpl.java
@@ -33,6 +33,7 @@ import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Future;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.RunnableFuture;
+import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicReference;
@@ -46,7 +47,7 @@ import com.google.common.util.concurrent.MoreExecutors;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import org.apache.qpid.server.pool.QpidByteBufferDisposingThreadPoolExecutor;
+import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.util.FutureHelper;
 
 public class TaskExecutorImpl implements TaskExecutor
@@ -84,20 +85,22 @@ public class TaskExecutorImpl implements TaskExecutor
         if (_running.compareAndSet(false, true))
         {
             LOGGER.debug("Starting task executor {}", _name);
-            _executor = MoreExecutors.listeningDecorator(new QpidByteBufferDisposingThreadPoolExecutor(1,
-                                                                                                       1,
-                                                                                                       0L,
-                                                                                                       TimeUnit.MILLISECONDS,
-                                                                                                       new LinkedBlockingQueue<>(),
-                                                                                                       r ->
-                                                                                                       {
-                                                                                                           _taskThread =
-                                                                                                                   new TaskThread(
-                                                                                                                           r,
-                                                                                                                           _name,
-                                                                                                                           TaskExecutorImpl.this);
-                                                                                                           return _taskThread;
-                                                                                                       }));
+            final java.util.concurrent.BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
+            final java.util.concurrent.ThreadFactory factory = r ->
+            {
+                _taskThread =
+                        new TaskThread(
+                                r,
+                                _name,
+                                TaskExecutorImpl.this);
+                return _taskThread;
+            };
+            _executor = MoreExecutors.listeningDecorator(new ThreadPoolExecutor(1,
+                                                                                1,
+                                                                                0L,
+                                                                                TimeUnit.MILLISECONDS,
+                                                                                workQueue,
+                                                                                QpidByteBuffer.createQpidByteBufferTrackingThreadFactory(factory)));
             LOGGER.debug("Task executor is started");
         }
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/message/AbstractServerMessageImpl.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/message/AbstractServerMessageImpl.java b/broker-core/src/main/java/org/apache/qpid/server/message/AbstractServerMessageImpl.java
index b4ae71c..3c36dce 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/message/AbstractServerMessageImpl.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/message/AbstractServerMessageImpl.java
@@ -176,7 +176,13 @@ public abstract class AbstractServerMessageImpl<X extends AbstractServerMessageI
     }
 
     @Override
-    public Collection<QpidByteBuffer> getContent(int offset, int length)
+    public QpidByteBuffer getContent()
+    {
+        return getContent(0, (int) getSize());
+    }
+
+    @Override
+    public QpidByteBuffer getContent(int offset, int length)
     {
         StoredMessage<T> storedMessage = getStoredMessage();
         boolean wasInMemory = storedMessage.isInMemory();

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/message/MessageContentSource.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/message/MessageContentSource.java b/broker-core/src/main/java/org/apache/qpid/server/message/MessageContentSource.java
index e3fd85b..79b41b5 100755
--- a/broker-core/src/main/java/org/apache/qpid/server/message/MessageContentSource.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/message/MessageContentSource.java
@@ -21,13 +21,12 @@
 
 package org.apache.qpid.server.message;
 
-import java.util.Collection;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 
 public interface MessageContentSource
 {
-    Collection<QpidByteBuffer> getContent(int offset, int length);
+    QpidByteBuffer getContent();
+    QpidByteBuffer getContent(int offset, int length);
 
     long getSize();
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/message/internal/InternalMessage.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/message/internal/InternalMessage.java b/broker-core/src/main/java/org/apache/qpid/server/message/internal/InternalMessage.java
index 29ffba6..75f56de 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/message/internal/InternalMessage.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/message/internal/InternalMessage.java
@@ -26,8 +26,6 @@ import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
 import java.io.Serializable;
 import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
@@ -40,8 +38,6 @@ import org.apache.qpid.server.store.MessageHandle;
 import org.apache.qpid.server.store.MessageStore;
 import org.apache.qpid.server.store.StoredMessage;
 import org.apache.qpid.server.store.TransactionLogResource;
-import org.apache.qpid.server.util.ByteBufferInputStream;
-import org.apache.qpid.server.util.ByteBufferUtils;
 import org.apache.qpid.server.util.ConnectionScopedRuntimeException;
 
 public class InternalMessage extends AbstractServerMessageImpl<InternalMessage, InternalMessageMetaData>
@@ -73,9 +69,8 @@ public class InternalMessage extends AbstractServerMessageImpl<InternalMessage,
         long contentSize = getSize();
         if (contentSize > 0)
         {
-            Collection<QpidByteBuffer> bufs = msg.getContent(0, (int) contentSize);
-
-            try (ObjectInputStream is = new ObjectInputStream(new ByteBufferInputStream(ByteBufferUtils.combine(bufs))))
+            try (QpidByteBuffer buf = msg.getContent(0, (int) contentSize);
+                 ObjectInputStream is = new ObjectInputStream(buf.asInputStream()))
             {
                 _messageBody = is.readObject();
             }
@@ -168,8 +163,12 @@ public class InternalMessage extends AbstractServerMessageImpl<InternalMessage,
 
             final InternalMessageMetaData metaData = InternalMessageMetaData.create(persistent, internalHeader, bytes.length);
             MessageHandle<InternalMessageMetaData> handle = store.addMessage(metaData);
-            handle.addContent(QpidByteBuffer.wrap(bytes));
-            StoredMessage<InternalMessageMetaData> storedMessage = handle.allContentAdded();
+            final StoredMessage<InternalMessageMetaData> storedMessage;
+            try (QpidByteBuffer wrap = QpidByteBuffer.wrap(bytes))
+            {
+                handle.addContent(wrap);
+            }
+            storedMessage = handle.allContentAdded();
             return new InternalMessage(storedMessage, internalHeader, bodyObject, destinationName);
         }
         catch (IOException e)
@@ -258,9 +257,9 @@ public class InternalMessage extends AbstractServerMessageImpl<InternalMessage,
                     }
 
                     @Override
-                    public Collection<QpidByteBuffer> getContent(final int offset, final int length)
+                    public QpidByteBuffer getContent(final int offset, final int length)
                     {
-                        return Collections.singleton(QpidByteBuffer.wrap(bytes, offset, length));
+                        return QpidByteBuffer.wrap(bytes, offset, length);
                     }
 
                     @Override

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/message/internal/InternalMessageMetaDataType.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/message/internal/InternalMessageMetaDataType.java b/broker-core/src/main/java/org/apache/qpid/server/message/internal/InternalMessageMetaDataType.java
index f174497..7fd78fd 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/message/internal/InternalMessageMetaDataType.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/message/internal/InternalMessageMetaDataType.java
@@ -22,10 +22,8 @@ package org.apache.qpid.server.message.internal;
 
 import java.io.IOException;
 import java.io.ObjectInputStream;
-import java.util.List;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferInputStream;
 import org.apache.qpid.server.message.ServerMessage;
 import org.apache.qpid.server.plugin.MessageMetaDataType;
 import org.apache.qpid.server.plugin.PluggableService;
@@ -45,9 +43,9 @@ public class InternalMessageMetaDataType implements MessageMetaDataType<Internal
     }
 
     @Override
-    public InternalMessageMetaData createMetaData(final List<QpidByteBuffer> bufs)
+    public InternalMessageMetaData createMetaData(final QpidByteBuffer buf)
     {
-        try(ObjectInputStream is = new ObjectInputStream(new QpidByteBufferInputStream(bufs)))
+        try (ObjectInputStream is = new ObjectInputStream(buf.asInputStream()))
         {
             int contentSize = is.readInt();
             InternalMessageHeader header = (InternalMessageHeader) is.readObject();

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/plugin/MessageFormat.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/plugin/MessageFormat.java b/broker-core/src/main/java/org/apache/qpid/server/plugin/MessageFormat.java
index 7836604..2ce9756 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/plugin/MessageFormat.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/plugin/MessageFormat.java
@@ -20,8 +20,6 @@
  */
 package org.apache.qpid.server.plugin;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.ServerMessage;
 import org.apache.qpid.server.store.MessageStore;
@@ -30,6 +28,6 @@ public interface MessageFormat<M extends ServerMessage<?>> extends Pluggable
 {
     int getSupportedFormat();
     Class<M> getMessageClass();
-    List<QpidByteBuffer> convertToMessageFormat(M message);
-    M createMessage(List<QpidByteBuffer> buf, MessageStore store, final Object connectionReference);
+    QpidByteBuffer convertToMessageFormat(M message);
+    M createMessage(QpidByteBuffer payload, MessageStore store, final Object connectionReference);
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/plugin/MessageMetaDataType.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/plugin/MessageMetaDataType.java b/broker-core/src/main/java/org/apache/qpid/server/plugin/MessageMetaDataType.java
index 4821914..b65e4b9 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/plugin/MessageMetaDataType.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/plugin/MessageMetaDataType.java
@@ -20,8 +20,6 @@
  */
 package org.apache.qpid.server.plugin;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.ServerMessage;
 import org.apache.qpid.server.store.StorableMessageMetaData;
@@ -32,12 +30,12 @@ public interface MessageMetaDataType<M extends StorableMessageMetaData> extends
 
     interface Factory<M extends StorableMessageMetaData>
     {
-        M createMetaData(List<QpidByteBuffer> buf);
+        M createMetaData(QpidByteBuffer buf);
     }
 
     int ordinal();
 
-    M createMetaData(List<QpidByteBuffer> bufs);
+    M createMetaData(QpidByteBuffer buf);
 
     ServerMessage<M> createMessage(StoredMessage<M> msg);
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/pool/QpidByteBufferDisposingThreadPoolExecutor.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/pool/QpidByteBufferDisposingThreadPoolExecutor.java b/broker-core/src/main/java/org/apache/qpid/server/pool/QpidByteBufferDisposingThreadPoolExecutor.java
deleted file mode 100644
index 6a87aa0..0000000
--- a/broker-core/src/main/java/org/apache/qpid/server/pool/QpidByteBufferDisposingThreadPoolExecutor.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-
-package org.apache.qpid.server.pool;
-
-import java.util.Map;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-
-public class QpidByteBufferDisposingThreadPoolExecutor extends ThreadPoolExecutor
-{
-    private final Map<Thread, QpidByteBuffer> _cachedBufferMap = new ConcurrentHashMap<>();
-
-    public QpidByteBufferDisposingThreadPoolExecutor(final int corePoolSize,
-                                                     final int maximumPoolSize,
-                                                     final long keepAliveTime,
-                                                     final TimeUnit unit,
-                                                     final BlockingQueue<Runnable> workQueue)
-    {
-        this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, Executors.defaultThreadFactory());
-    }
-
-    public QpidByteBufferDisposingThreadPoolExecutor(final int corePoolSize,
-                                                     final int maximumPoolSize,
-                                                     final long keepAliveTime,
-                                                     final TimeUnit unit,
-                                                     final BlockingQueue<Runnable> workQueue,
-                                                     final ThreadFactory factory)
-    {
-        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, factory);
-    }
-
-    @Override
-    protected void afterExecute(final Runnable r, final Throwable t)
-    {
-        super.afterExecute(r, t);
-        final QpidByteBuffer cachedThreadLocalBuffer = QpidByteBuffer.getCachedThreadLocalBuffer();
-        if (cachedThreadLocalBuffer != null)
-        {
-            _cachedBufferMap.put(Thread.currentThread(), cachedThreadLocalBuffer);
-        }
-        else
-        {
-            _cachedBufferMap.remove(Thread.currentThread());
-        }
-    }
-
-    @Override
-    protected void terminated()
-    {
-        super.terminated();
-        for (QpidByteBuffer qpidByteBuffer : _cachedBufferMap.values())
-        {
-            qpidByteBuffer.dispose();
-        }
-        _cachedBufferMap.clear();
-    }
-}

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQShortString.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQShortString.java b/broker-core/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQShortString.java
index 3e51b20..928e309 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQShortString.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQShortString.java
@@ -125,7 +125,7 @@ public final class AMQShortString implements Comparable<AMQShortString>
 
     public static AMQShortString readAMQShortString(QpidByteBuffer buffer)
     {
-        int length = ((int) buffer.get()) & 0xff;
+        int length = buffer.getUnsignedByte();
         if(length == 0)
         {
             return null;

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/protocol/v0_8/FieldArray.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/protocol/v0_8/FieldArray.java b/broker-core/src/main/java/org/apache/qpid/server/protocol/v0_8/FieldArray.java
index 2055529..9e5222b 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/protocol/v0_8/FieldArray.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/protocol/v0_8/FieldArray.java
@@ -117,13 +117,14 @@ public class FieldArray<T> extends AbstractCollection<T>
     {
         ArrayList<Object> result = new ArrayList<>();
         int size = buffer.getInt();
-        QpidByteBuffer slicedBuffer = buffer.view(0,size);
-        buffer.position(buffer.position()+size);
-        while(slicedBuffer.hasRemaining())
+        try (QpidByteBuffer slicedBuffer = buffer.view(0, size))
         {
-            result.add(AMQTypedValue.readFromBuffer(slicedBuffer).getValue());
+            buffer.position(buffer.position() + size);
+            while (slicedBuffer.hasRemaining())
+            {
+                result.add(AMQTypedValue.readFromBuffer(slicedBuffer).getValue());
+            }
         }
-        slicedBuffer.dispose();
         return new FieldArray<>(result);
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/queue/AbstractQueue.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/queue/AbstractQueue.java b/broker-core/src/main/java/org/apache/qpid/server/queue/AbstractQueue.java
index bb5b6fd..5bebdb2 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/queue/AbstractQueue.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/queue/AbstractQueue.java
@@ -63,7 +63,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferInputStream;
 import org.apache.qpid.server.configuration.IllegalConfigurationException;
 import org.apache.qpid.server.configuration.updater.Task;
 import org.apache.qpid.server.connection.SessionPrincipal;
@@ -2489,24 +2488,29 @@ public abstract class AbstractQueue<X extends AbstractQueue<X>>
             ServerMessage message = _messageReference.getMessage();
 
             int length = (int) ((_limit == UNLIMITED || _decompressBeforeLimiting) ? message.getSize() : _limit);
-            InputStream inputStream = new QpidByteBufferInputStream(message.getContent(0, length));
-
-            if (_limit != UNLIMITED && _decompressBeforeLimiting)
+            try (QpidByteBuffer content = message.getContent(0, length))
             {
-                inputStream = new GZIPInputStream(inputStream);
-                inputStream = ByteStreams.limit(inputStream, _limit);
-                outputStream = new GZIPOutputStream(outputStream);
-            }
+                InputStream inputStream = content.asInputStream();
+                if (_limit != UNLIMITED && _decompressBeforeLimiting)
+                {
+                    inputStream = new GZIPInputStream(inputStream);
+                    inputStream = ByteStreams.limit(inputStream, _limit);
+                    outputStream = new GZIPOutputStream(outputStream, true);
+                }
 
-            try
-            {
-                ByteStreams.copy(inputStream, outputStream);
-            }
-            finally
-            {
-                outputStream.close();
-                inputStream.close();
+                try
+                {
+                    ByteStreams.copy(inputStream, outputStream);
+                }
+                finally
+                {
+                    inputStream.close();
+                    // Seems weird to close the outputStream here but otherwise the GZIPOutputStream will be in an
+                    // invalid state. Calling flush() did not solve the problem.
+                    outputStream.close();
+                }
             }
+
         }
     }
 
@@ -3276,15 +3280,26 @@ public abstract class AbstractQueue<X extends AbstractQueue<X>>
                         MessageConverterRegistry.getConverter(message.getClass(), InternalMessage.class);
                 if (messageConverter != null)
                 {
-                    return new JsonMessageContent(messageReference,
-                                                  (InternalMessage) messageConverter.convert(message, getVirtualHost()),
-                                                  limit);
+                    InternalMessage convertedMessage = null;
+                    try
+                    {
+                        convertedMessage = (InternalMessage) messageConverter.convert(message, getVirtualHost());
+                        return new JsonMessageContent(messageReference, convertedMessage, limit);
+                    }
+                    finally
+                    {
+                        if (convertedMessage != null)
+                        {
+                            messageConverter.dispose(convertedMessage);
+                        }
+                    }
                 }
                 else
                 {
                     throw new IllegalArgumentException(String.format("Unable to convert message %d on queue '%s' to JSON",
                                                                      message.getMessageNumber(), getName()));
                 }
+
             }
         }
         else

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java b/broker-core/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java
index 80f53cf..bf62f43 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/store/MemoryMessageStore.java
@@ -75,12 +75,6 @@ public class MemoryMessageStore implements MessageStore
         @Override
         public MessageEnqueueRecord enqueueMessage(TransactionLogResource queue, EnqueueableMessage message)
         {
-
-            if(message.getStoredMessage() instanceof StoredMemoryMessage)
-            {
-                _messages.putIfAbsent(message.getMessageNumber(), (StoredMemoryMessage) message.getStoredMessage());
-            }
-
             Set<Long> messageIds = _localEnqueueMap.get(queue.getId());
             if (messageIds == null)
             {
@@ -328,6 +322,7 @@ public class MemoryMessageStore implements MessageStore
                 }
             }
         };
+        _messages.put(storedMemoryMessage.getMessageNumber(), storedMemoryMessage);
         _inMemorySize.addAndGet(metaData.getStorableSize());
 
         return storedMemoryMessage;
@@ -493,7 +488,7 @@ public class MemoryMessageStore implements MessageStore
         {
             for (StoredMemoryMessage message : _messages.values())
             {
-                if(!handler.handle(message))
+                if (!handler.handle(message))
                 {
                     break;
                 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/store/StoredMemoryMessage.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/store/StoredMemoryMessage.java b/broker-core/src/main/java/org/apache/qpid/server/store/StoredMemoryMessage.java
index 90114ec..f4de0d0 100755
--- a/broker-core/src/main/java/org/apache/qpid/server/store/StoredMemoryMessage.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/store/StoredMemoryMessage.java
@@ -22,11 +22,9 @@
 package org.apache.qpid.server.store;
 
 import java.util.ArrayList;
-import java.util.Collection;
 import java.util.Iterator;
 import java.util.LinkedList;
 import java.util.List;
-import java.util.Queue;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 
@@ -35,7 +33,7 @@ public class StoredMemoryMessage<T extends StorableMessageMetaData> implements S
     private final long _messageNumber;
     private final int _contentSize;
     private final int _metadataSize;
-    private final Queue<QpidByteBuffer> _content = new LinkedList<>();
+    private QpidByteBuffer _content = null;
     private volatile T _metaData;
 
     public StoredMemoryMessage(long messageNumber, T metaData)
@@ -55,7 +53,17 @@ public class StoredMemoryMessage<T extends StorableMessageMetaData> implements S
     @Override
     public synchronized void addContent(QpidByteBuffer src)
     {
-        _content.add(src.slice());
+        try (QpidByteBuffer content = _content)
+        {
+            if (content == null)
+            {
+                _content = src.slice();
+            }
+            else
+            {
+                _content = QpidByteBuffer.concatenate(content, src);
+            }
+        }
     }
 
     @Override
@@ -66,46 +74,17 @@ public class StoredMemoryMessage<T extends StorableMessageMetaData> implements S
 
 
     @Override
-    public synchronized Collection<QpidByteBuffer> getContent(int offset, int length)
+    public synchronized QpidByteBuffer getContent(int offset, int length)
     {
-        Collection<QpidByteBuffer> content = new ArrayList<>(_content.size());
-        int pos = 0;
-        for (QpidByteBuffer buf : _content)
+        if (_content == null)
         {
-            if (length > 0)
-            {
-                int bufRemaining = buf.remaining();
-                if (pos + bufRemaining <= offset)
-                {
-                    pos += bufRemaining;
-                }
-                else if (pos >= offset)
-                {
-                    buf = buf.duplicate();
-                    if (bufRemaining <= length)
-                    {
-                        length -= bufRemaining;
-                    }
-                    else
-                    {
-                        buf.limit(length);
-                        length = 0;
-                    }
-                    content.add(buf);
-                    pos += buf.remaining();
-                }
-                else
-                {
-                    int offsetInBuf = offset - pos;
-                    int limit = length < bufRemaining - offsetInBuf ? length : bufRemaining - offsetInBuf;
-                    final QpidByteBuffer bufView = buf.view(offsetInBuf, limit);
-                    content.add(bufView);
-                    length -= limit;
-                    pos += limit + offsetInBuf;
-                }
-            }
+            return QpidByteBuffer.emptyQpidByteBuffer();
+        }
+
+        try (QpidByteBuffer combined = QpidByteBuffer.concatenate(_content))
+        {
+            return combined.view(offset, length);
         }
-        return content;
     }
 
     @Override
@@ -133,11 +112,8 @@ public class StoredMemoryMessage<T extends StorableMessageMetaData> implements S
         _metaData = null;
         if (_content != null)
         {
-            for (QpidByteBuffer content : _content)
-            {
-                content.dispose();
-            }
-            _content.clear();
+            _content.dispose();
+            _content = null;
         }
     }
 
@@ -157,14 +133,7 @@ public class StoredMemoryMessage<T extends StorableMessageMetaData> implements S
     public synchronized void reallocate()
     {
         _metaData.reallocate();
-        List<QpidByteBuffer> newContent = new ArrayList<>(_content.size());
-        for (Iterator<QpidByteBuffer> iterator = _content.iterator(); iterator.hasNext(); )
-        {
-            final QpidByteBuffer buffer = iterator.next();
-            newContent.add(QpidByteBuffer.reallocateIfNecessary(buffer));
-            iterator.remove();
-        }
-        _content.addAll(newContent);
+        _content = QpidByteBuffer.reallocateIfNecessary(_content);
     }
 
     public void clear()

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/store/StoredMessage.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/store/StoredMessage.java b/broker-core/src/main/java/org/apache/qpid/server/store/StoredMessage.java
index 309be7b..98b54bd 100755
--- a/broker-core/src/main/java/org/apache/qpid/server/store/StoredMessage.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/store/StoredMessage.java
@@ -20,8 +20,6 @@
 */
 package org.apache.qpid.server.store;
 
-import java.util.Collection;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 
 public interface StoredMessage<M extends StorableMessageMetaData>
@@ -30,7 +28,7 @@ public interface StoredMessage<M extends StorableMessageMetaData>
 
     long getMessageNumber();
 
-    Collection<QpidByteBuffer> getContent(int offset, int length);
+    QpidByteBuffer getContent(int offset, int length);
 
     int getContentSize();
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/store/serializer/v1/Deserializer.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/store/serializer/v1/Deserializer.java b/broker-core/src/main/java/org/apache/qpid/server/store/serializer/v1/Deserializer.java
index eab7156..93bca03 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/store/serializer/v1/Deserializer.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/store/serializer/v1/Deserializer.java
@@ -82,31 +82,32 @@ class Deserializer
     long readLong() throws IOException
     {
         byte[] data = readBytes(8);
-        QpidByteBuffer buf = QpidByteBuffer.wrap(data);
-        long val = buf.getLong();
-        buf.dispose();
-        return val;
+        try (QpidByteBuffer buf = QpidByteBuffer.wrap(data))
+        {
+            return buf.getLong();
+        }
     }
 
 
     int readInt() throws IOException
     {
         byte[] data = readBytes(4);
-        QpidByteBuffer buf = QpidByteBuffer.wrap(data);
-        int val = buf.getInt();
-        buf.dispose();
-        return val;
+        try (QpidByteBuffer buf = QpidByteBuffer.wrap(data))
+        {
+            return buf.getInt();
+        }
     }
 
 
     UUID readUUID() throws IOException
     {
         byte[] data = readBytes(16);
-        QpidByteBuffer buf = QpidByteBuffer.wrap(data);
-        long msb = buf.getLong();
-        long lsb = buf.getLong();
-        buf.dispose();
-        return new UUID(msb, lsb);
+        try (QpidByteBuffer buf = QpidByteBuffer.wrap(data))
+        {
+            long msb = buf.getLong();
+            long lsb = buf.getLong();
+            return new UUID(msb, lsb);
+        }
     }
 
     Record validateDigest() throws IOException

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/store/serializer/v1/MessageRecord.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/store/serializer/v1/MessageRecord.java b/broker-core/src/main/java/org/apache/qpid/server/store/serializer/v1/MessageRecord.java
index eb8e73e..92c6ebe 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/store/serializer/v1/MessageRecord.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/store/serializer/v1/MessageRecord.java
@@ -36,22 +36,17 @@ class MessageRecord implements Record
     {
         _messageNumber = storedMessage.getMessageNumber();
         _metaData = new byte[1 + storedMessage.getMetadataSize()];
-        QpidByteBuffer buf = QpidByteBuffer.wrap(_metaData);
-        buf.put((byte)storedMessage.getMetaData().getType().ordinal());
-        storedMessage.getMetaData().writeToBuffer(buf);
-        buf.dispose();
-
+        try (QpidByteBuffer buf = QpidByteBuffer.wrap(_metaData))
+        {
+            buf.put((byte) storedMessage.getMetaData().getType().ordinal());
+            storedMessage.getMetaData().writeToBuffer(buf);
+        }
 
         _content = new byte[storedMessage.getContentSize()];
-        buf = QpidByteBuffer.wrap(_content);
-        for(QpidByteBuffer content : storedMessage.getContent(0, storedMessage.getContentSize()))
+        try (QpidByteBuffer content = storedMessage.getContent(0, storedMessage.getContentSize()))
         {
-            buf.put(content);
-            content.dispose();
+            content.get(_content);
         }
-        buf.dispose();
-
-
     }
 
     MessageRecord(long messageNumber, byte[] metaData, byte[] content)

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/store/serializer/v1/MessageStoreSerializer_v1.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/store/serializer/v1/MessageStoreSerializer_v1.java b/broker-core/src/main/java/org/apache/qpid/server/store/serializer/v1/MessageStoreSerializer_v1.java
index c75b930..ec87654 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/store/serializer/v1/MessageStoreSerializer_v1.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/store/serializer/v1/MessageStoreSerializer_v1.java
@@ -24,7 +24,6 @@ package org.apache.qpid.server.store.serializer.v1;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
-import java.util.Collections;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.UUID;
@@ -305,30 +304,28 @@ public class MessageStoreSerializer_v1 implements MessageStoreSerializer
             MessageRecord messageRecord = (MessageRecord) record;
             long originalMessageNumber = messageRecord.getMessageNumber();
             byte[] metaData = messageRecord.getMetaData();
-            final MessageMetaDataType metaDataType =
-                    MessageMetaDataTypeRegistry.fromOrdinal(metaData[0] & 0xff);
-            QpidByteBuffer buf = QpidByteBuffer.wrap(metaData, 1, metaData.length - 1);
-            final StorableMessageMetaData storableMessageMetaData;
-            try
+            final MessageMetaDataType metaDataType = MessageMetaDataTypeRegistry.fromOrdinal(metaData[0] & 0xff);
+            final MessageHandle<StorableMessageMetaData> handle;
+            try (QpidByteBuffer buf = QpidByteBuffer.wrap(metaData, 1, metaData.length - 1))
             {
-                storableMessageMetaData = metaDataType.createMetaData(Collections.singletonList(buf));
+                try
+                {
+                    StorableMessageMetaData storableMessageMetaData = metaDataType.createMetaData(buf);
+                    handle = store.addMessage(storableMessageMetaData);
+                }
+                catch (ConnectionScopedRuntimeException e)
+                {
+                    throw new IllegalArgumentException("Could not deserialize message metadata", e);
+                }
             }
-            catch (ConnectionScopedRuntimeException e)
+
+            try (QpidByteBuffer buf = QpidByteBuffer.wrap(messageRecord.getContent()))
             {
-                throw new IllegalArgumentException("Could not deserialize message metadata", e);
+                handle.addContent(buf);
             }
-            buf.dispose();
-            final MessageHandle<StorableMessageMetaData> handle =
-                    store.addMessage(storableMessageMetaData);
-
-            buf = QpidByteBuffer.wrap(messageRecord.getContent());
-            handle.addContent(buf);
-            final StoredMessage<StorableMessageMetaData> storedMessage =
-                    handle.allContentAdded();
+            final StoredMessage<StorableMessageMetaData> storedMessage = handle.allContentAdded();
             messageNumberMap.put(originalMessageNumber, storedMessage);
             storedMessage.flowToDisk();
-            buf.dispose();
-
 
             record = deserializer.readRecord();
         }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/transport/MultiVersionProtocolEngine.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/transport/MultiVersionProtocolEngine.java b/broker-core/src/main/java/org/apache/qpid/server/transport/MultiVersionProtocolEngine.java
index 2e5f4b9..1655909 100755
--- a/broker-core/src/main/java/org/apache/qpid/server/transport/MultiVersionProtocolEngine.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/transport/MultiVersionProtocolEngine.java
@@ -45,8 +45,8 @@ import org.apache.qpid.server.model.Transport;
 import org.apache.qpid.server.model.port.AmqpPort;
 import org.apache.qpid.server.plugin.ProtocolEngineCreator;
 import org.apache.qpid.server.security.ManagedPeerCertificateTrustStore;
-import org.apache.qpid.server.util.Action;
 import org.apache.qpid.server.transport.network.Ticker;
+import org.apache.qpid.server.util.Action;
 
 public class MultiVersionProtocolEngine implements ProtocolEngine
 {
@@ -386,22 +386,20 @@ public class MultiVersionProtocolEngine implements ProtocolEngine
         public void received(QpidByteBuffer msg)
         {
             _lastReadTime = System.currentTimeMillis();
-            QpidByteBuffer msgheader = msg.slice();
-
-            if(_header.remaining() > msgheader.limit())
-            {
-                msgheader.dispose();
-                return;
-            }
-            else
+            try (QpidByteBuffer msgheader = msg.slice())
             {
-                msgheader.limit(_header.remaining());
-                msg.position(msg.position()+_header.remaining());
-            }
-
-            _header.put(msgheader);
+                if (_header.remaining() > msgheader.limit())
+                {
+                    return;
+                }
+                else
+                {
+                    msgheader.limit(_header.remaining());
+                    msg.position(msg.position() + _header.remaining());
+                }
 
-            msgheader.dispose();
+                _header.put(msgheader);
+            }
 
             if(!_header.hasRemaining())
             {
@@ -466,16 +464,18 @@ public class MultiVersionProtocolEngine implements ProtocolEngine
                     _broker.getEventLogger().message(new PortLogSubject(_port),
                                                      PortMessages.UNSUPPORTED_PROTOCOL_HEADER(supportedReplyVersion.toString()));
 
-                    final QpidByteBuffer supportedReplyBuf = QpidByteBuffer.allocateDirect(supportedReplyBytes.length);
-                    supportedReplyBuf.put(supportedReplyBytes);
-                    supportedReplyBuf.flip();
-                    _sender.send(supportedReplyBuf);
+                    try (QpidByteBuffer supportedReplyBuf = QpidByteBuffer.allocateDirect(supportedReplyBytes.length))
+                    {
+                        supportedReplyBuf.put(supportedReplyBytes);
+                        supportedReplyBuf.flip();
+                        _sender.send(supportedReplyBuf);
+                    }
                     _sender.flush();
 
                     _delegate = new ClosedDelegateProtocolEngine();
 
+                    _header.dispose();
                     _network.close();
-
                 }
                 else
                 {
@@ -489,6 +489,7 @@ public class MultiVersionProtocolEngine implements ProtocolEngine
                     _delegate.setWorkListener(_workListener.get());
                     _header.flip();
                     _delegate.received(_header);
+                    _header.dispose();
 
                     Certificate peerCertificate = _network.getPeerCertificate();
                     if(peerCertificate != null && _port.getClientCertRecorder() != null)

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/transport/NetworkConnectionScheduler.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/transport/NetworkConnectionScheduler.java b/broker-core/src/main/java/org/apache/qpid/server/transport/NetworkConnectionScheduler.java
index da0efc7..6d0cc37 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/transport/NetworkConnectionScheduler.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/transport/NetworkConnectionScheduler.java
@@ -22,8 +22,6 @@ package org.apache.qpid.server.transport;
 
 import java.io.IOException;
 import java.nio.channels.ServerSocketChannel;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.Executors;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.ThreadFactory;
@@ -35,7 +33,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.pool.QpidByteBufferDisposingThreadPoolExecutor;
 
 public class NetworkConnectionScheduler
 {
@@ -102,9 +99,17 @@ public class NetworkConnectionScheduler
         try
         {
             _selectorThread = new SelectorThread(this, _numberOfSelectors);
-            _executor = new QpidByteBufferDisposingThreadPoolExecutor(_poolSize, _poolSize,
-                                                                      _threadKeepAliveTimeout, TimeUnit.MINUTES,
-                                                                      new LinkedBlockingQueue<>(), _factory);
+            final int corePoolSize = _poolSize;
+            final int maximumPoolSize = _poolSize;
+            final long keepAliveTime = _threadKeepAliveTimeout;
+            final java.util.concurrent.BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>();
+            final ThreadFactory factory = _factory;
+            _executor = new ThreadPoolExecutor(corePoolSize,
+                                               maximumPoolSize,
+                                               keepAliveTime,
+                                               TimeUnit.MINUTES,
+                                               workQueue,
+                                               QpidByteBuffer.createQpidByteBufferTrackingThreadFactory(factory));
             _executor.prestartAllCoreThreads();
             _executor.allowCoreThreadTimeOut(true);
             for(int i = 0 ; i < _poolSize; i++)

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnection.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnection.java b/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnection.java
index 8826dd8..32e8fdb 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnection.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnection.java
@@ -41,9 +41,9 @@ import org.slf4j.LoggerFactory;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.model.port.AmqpPort;
+import org.apache.qpid.server.transport.network.TransportEncryption;
 import org.apache.qpid.server.util.Action;
 import org.apache.qpid.server.util.ConnectionScopedRuntimeException;
-import org.apache.qpid.server.transport.network.TransportEncryption;
 import org.apache.qpid.server.util.SystemUtils;
 
 public class NonBlockingConnection implements ServerNetworkConnection, ByteBufferSender
@@ -431,21 +431,34 @@ public class NonBlockingConnection implements ServerNetworkConnection, ByteBuffe
 
     private void shutdownOutput()
     {
-        if(!SystemUtils.isWindows())
+        try
         {
-            try
-            {
-                _socketChannel.shutdownOutput();
-            }
-            catch (IOException e)
+
+            if(!SystemUtils.isWindows())
             {
-                LOGGER.info("Exception closing socket '{}': {}", _remoteSocketAddress, e.getMessage());
+                try
+                {
+                    _socketChannel.shutdownOutput();
+                }
+                catch (IOException e)
+                {
+                    LOGGER.info("Exception closing socket '{}': {}", _remoteSocketAddress, e.getMessage());
+                }
+                finally
+                {
+                    _delegate.shutdownOutput();
+                }
             }
-            finally
+        }
+        finally
+        {
+            while (!_buffers.isEmpty())
             {
-                _delegate.shutdownOutput();
+                final QpidByteBuffer buffer = _buffers.poll();
+                buffer.dispose();
             }
         }
+
     }
 
     private void shutdownInput()
@@ -476,7 +489,7 @@ public class NonBlockingConnection implements ServerNetworkConnection, ByteBuffe
         _partialRead = false;
         if(!_closed.get() && _delegate.readyForRead())
         {
-            int readData = readFromNetwork();
+            long readData = readFromNetwork();
 
             if (readData > 0)
             {
@@ -521,11 +534,11 @@ public class NonBlockingConnection implements ServerNetworkConnection, ByteBuffe
         return _fullyWritten;
     }
 
-    protected int readFromNetwork() throws IOException
+    protected long readFromNetwork() throws IOException
     {
         QpidByteBuffer buffer = _delegate.getNetInputBuffer();
 
-        int read = buffer.read(_socketChannel);
+        long read = buffer.read(_socketChannel);
         if (read == -1)
         {
             _closed.set(true);
@@ -608,12 +621,15 @@ public class NonBlockingConnection implements ServerNetworkConnection, ByteBuffe
             default:
                 throw new IllegalArgumentException("unknown TransportEncryption " + transportEncryption);
         }
-        if(oldDelegate != null)
+        if (oldDelegate != null)
         {
-            QpidByteBuffer src = oldDelegate.getNetInputBuffer().duplicate();
-            src.flip();
-            _delegate.getNetInputBuffer().put(src);
-            src.dispose();
+            try (QpidByteBuffer src = oldDelegate.getNetInputBuffer().duplicate())
+            {
+                src.flip();
+                _delegate.getNetInputBuffer().put(src);
+            }
+            oldDelegate.shutdownInput();
+            oldDelegate.shutdownOutput();
         }
         LOGGER.debug("Identified transport encryption as " + transportEncryption);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionDelegate.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionDelegate.java b/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionDelegate.java
index ee81856..f827768 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionDelegate.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionDelegate.java
@@ -49,7 +49,8 @@ interface NonBlockingConnectionDelegate
             return _bytesConsumed;
         }
     }
-    WriteResult doWrite(Collection<QpidByteBuffer> bufferArray) throws IOException;
+
+    WriteResult doWrite(Collection<QpidByteBuffer> buffers) throws IOException;
 
     boolean readyForRead();
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionPlainDelegate.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionPlainDelegate.java b/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionPlainDelegate.java
index 30acb2f..d355f4b 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionPlainDelegate.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionPlainDelegate.java
@@ -64,12 +64,13 @@ public class NonBlockingConnectionPlainDelegate implements NonBlockingConnection
 
     protected void restoreApplicationBufferForWrite()
     {
-        QpidByteBuffer oldNetInputBuffer = _netInputBuffer;
-        int unprocessedDataLength = _netInputBuffer.remaining();
-        _netInputBuffer.limit(_netInputBuffer.capacity());
-        _netInputBuffer = oldNetInputBuffer.slice();
-        _netInputBuffer.limit(unprocessedDataLength);
-        oldNetInputBuffer.dispose();
+        try (QpidByteBuffer oldNetInputBuffer = _netInputBuffer)
+        {
+            int unprocessedDataLength = _netInputBuffer.remaining();
+            _netInputBuffer.limit(_netInputBuffer.capacity());
+            _netInputBuffer = oldNetInputBuffer.slice();
+            _netInputBuffer.limit(unprocessedDataLength);
+        }
         if (_netInputBuffer.limit() != _netInputBuffer.capacity())
         {
             _netInputBuffer.position(_netInputBuffer.limit());
@@ -77,34 +78,35 @@ public class NonBlockingConnectionPlainDelegate implements NonBlockingConnection
         }
         else
         {
-            QpidByteBuffer currentBuffer = _netInputBuffer;
-            int newBufSize;
-
-            if (currentBuffer.capacity() < _networkBufferSize)
+            try (QpidByteBuffer currentBuffer = _netInputBuffer)
             {
-                newBufSize = _networkBufferSize;
+                int newBufSize;
+
+                if (currentBuffer.capacity() < _networkBufferSize)
+                {
+                    newBufSize = _networkBufferSize;
+                }
+                else
+                {
+                    newBufSize = currentBuffer.capacity() + _networkBufferSize;
+                    _parent.reportUnexpectedByteBufferSizeUsage();
+                }
+
+                _netInputBuffer = QpidByteBuffer.allocateDirect(newBufSize);
+                _netInputBuffer.put(currentBuffer);
             }
-            else
-            {
-                newBufSize = currentBuffer.capacity() + _networkBufferSize;
-                _parent.reportUnexpectedByteBufferSizeUsage();
-            }
-
-            _netInputBuffer = QpidByteBuffer.allocateDirect(newBufSize);
-            _netInputBuffer.put(currentBuffer);
-            currentBuffer.dispose();
         }
 
     }
 
 
     @Override
-    public WriteResult doWrite(Collection<QpidByteBuffer> bufferArray) throws IOException
+    public WriteResult doWrite(Collection<QpidByteBuffer> buffers) throws IOException
     {
         long bytesToWrite = 0L;
-        if(!bufferArray.isEmpty())
+        if(!buffers.isEmpty())
         {
-            for (QpidByteBuffer buf : bufferArray)
+            for (QpidByteBuffer buf : buffers)
             {
                 bytesToWrite += buf.remaining();
             }
@@ -116,7 +118,7 @@ public class NonBlockingConnectionPlainDelegate implements NonBlockingConnection
         else
         {
 
-            long bytesWritten = _parent.writeToTransport(bufferArray);
+            long bytesWritten = _parent.writeToTransport(buffers);
             return new WriteResult(bytesWritten >= bytesToWrite, bytesWritten);
         }
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionTLSDelegate.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionTLSDelegate.java b/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionTLSDelegate.java
index c6f29e7..772d028 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionTLSDelegate.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionTLSDelegate.java
@@ -40,8 +40,8 @@ import org.slf4j.LoggerFactory;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.model.port.AmqpPort;
-import org.apache.qpid.server.util.ServerScopedRuntimeException;
 import org.apache.qpid.server.transport.network.security.ssl.SSLUtil;
+import org.apache.qpid.server.util.ServerScopedRuntimeException;
 
 public class NonBlockingConnectionTLSDelegate implements NonBlockingConnectionDelegate
 {
@@ -90,8 +90,7 @@ public class NonBlockingConnectionTLSDelegate implements NonBlockingConnectionDe
     {
         if(!_hostChecked)
         {
-            QpidByteBuffer buffer = _netInputBuffer.duplicate();
-            try
+            try (QpidByteBuffer buffer = _netInputBuffer.duplicate())
             {
                 buffer.flip();
                 if (SSLUtil.isSufficientToDetermineClientSNIHost(buffer))
@@ -108,10 +107,6 @@ public class NonBlockingConnectionTLSDelegate implements NonBlockingConnectionDe
                     return false;
                 }
             }
-            finally
-            {
-                buffer.dispose();;
-            }
         }
         _netInputBuffer.flip();
         boolean readData = false;
@@ -157,14 +152,14 @@ public class NonBlockingConnectionTLSDelegate implements NonBlockingConnectionDe
     }
 
     @Override
-    public WriteResult doWrite(Collection<QpidByteBuffer> bufferArray) throws IOException
+    public WriteResult doWrite(Collection<QpidByteBuffer> buffers) throws IOException
     {
-        final int bufCount = bufferArray.size();
+        final int bufCount = buffers.size();
 
-        int totalConsumed = wrapBufferArray(bufferArray);
+        int totalConsumed = wrapBufferArray(buffers);
 
         boolean bufsSent = true;
-        final Iterator<QpidByteBuffer> itr = bufferArray.iterator();
+        final Iterator<QpidByteBuffer> itr = buffers.iterator();
         int bufIndex = 0;
         while(itr.hasNext() && bufsSent && bufIndex++ < bufCount)
         {
@@ -196,12 +191,13 @@ public class NonBlockingConnectionTLSDelegate implements NonBlockingConnectionDe
 
     protected void restoreApplicationBufferForWrite()
     {
-        QpidByteBuffer oldApplicationBuffer = _applicationBuffer;
-        int unprocessedDataLength = _applicationBuffer.remaining();
-        _applicationBuffer.limit(_applicationBuffer.capacity());
-        _applicationBuffer = _applicationBuffer.slice();
-        _applicationBuffer.limit(unprocessedDataLength);
-        oldApplicationBuffer.dispose();
+        try (QpidByteBuffer oldApplicationBuffer = _applicationBuffer)
+        {
+            int unprocessedDataLength = _applicationBuffer.remaining();
+            _applicationBuffer.limit(_applicationBuffer.capacity());
+            _applicationBuffer = _applicationBuffer.slice();
+            _applicationBuffer.limit(unprocessedDataLength);
+        }
         if (_applicationBuffer.limit() <= _applicationBuffer.capacity() - _sslEngine.getSession().getApplicationBufferSize())
         {
             _applicationBuffer.position(_applicationBuffer.limit());
@@ -209,26 +205,27 @@ public class NonBlockingConnectionTLSDelegate implements NonBlockingConnectionDe
         }
         else
         {
-            QpidByteBuffer currentBuffer = _applicationBuffer;
-            int newBufSize;
-            if (currentBuffer.capacity() < _networkBufferSize)
-            {
-                newBufSize = _networkBufferSize;
-            }
-            else
+            try (QpidByteBuffer currentBuffer = _applicationBuffer)
             {
-                newBufSize = currentBuffer.capacity() + _networkBufferSize;
-                _parent.reportUnexpectedByteBufferSizeUsage();
-            }
+                int newBufSize;
+                if (currentBuffer.capacity() < _networkBufferSize)
+                {
+                    newBufSize = _networkBufferSize;
+                }
+                else
+                {
+                    newBufSize = currentBuffer.capacity() + _networkBufferSize;
+                    _parent.reportUnexpectedByteBufferSizeUsage();
+                }
 
-            _applicationBuffer = QpidByteBuffer.allocateDirect(newBufSize);
-            _applicationBuffer.put(currentBuffer);
-            currentBuffer.dispose();
+                _applicationBuffer = QpidByteBuffer.allocateDirect(newBufSize);
+                _applicationBuffer.put(currentBuffer);
+            }
         }
 
     }
 
-    private int wrapBufferArray(Collection<QpidByteBuffer> bufferArray) throws SSLException
+    private int wrapBufferArray(Collection<QpidByteBuffer> buffers) throws SSLException
     {
         int totalConsumed = 0;
         boolean encrypted;
@@ -250,7 +247,7 @@ public class NonBlockingConnectionTLSDelegate implements NonBlockingConnectionDe
                     _netOutputBuffer = QpidByteBuffer.allocateDirect(_networkBufferSize);
                 }
 
-                _status = QpidByteBuffer.encryptSSL(_sslEngine, bufferArray, _netOutputBuffer);
+                _status = QpidByteBuffer.encryptSSL(_sslEngine, buffers, _netOutputBuffer);
                 encrypted = _status.bytesProduced() > 0;
                 totalConsumed += _status.bytesConsumed();
                 runSSLEngineTasks(_status);

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionUndecidedDelegate.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionUndecidedDelegate.java b/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionUndecidedDelegate.java
index 90c66c8..1b0a459 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionUndecidedDelegate.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/transport/NonBlockingConnectionUndecidedDelegate.java
@@ -50,27 +50,26 @@ public class NonBlockingConnectionUndecidedDelegate implements NonBlockingConnec
     @Override
     public boolean processData() throws IOException
     {
-        QpidByteBuffer buffer = _netInputBuffer.duplicate();
-        buffer.flip();
-        final boolean hasSufficientData = buffer.remaining() >= NUMBER_OF_BYTES_FOR_TLS_CHECK;
-        if (hasSufficientData)
+        try (QpidByteBuffer buffer = _netInputBuffer.duplicate())
         {
-            final byte[] headerBytes = new byte[NUMBER_OF_BYTES_FOR_TLS_CHECK];
-            buffer.get(headerBytes);
-
-            if (looksLikeSSL(headerBytes))
-            {
-                _parent.setTransportEncryption(TransportEncryption.TLS);
-            }
-            else
+            buffer.flip();
+            final boolean hasSufficientData = buffer.remaining() >= NUMBER_OF_BYTES_FOR_TLS_CHECK;
+            if (hasSufficientData)
             {
-                _parent.setTransportEncryption(TransportEncryption.NONE);
+                final byte[] headerBytes = new byte[NUMBER_OF_BYTES_FOR_TLS_CHECK];
+                buffer.get(headerBytes);
+
+                if (looksLikeSSL(headerBytes))
+                {
+                    _parent.setTransportEncryption(TransportEncryption.TLS);
+                }
+                else
+                {
+                    _parent.setTransportEncryption(TransportEncryption.NONE);
+                }
             }
-
-
+            return hasSufficientData;
         }
-        buffer.dispose();
-        return hasSufficientData;
     }
 
     @Override
@@ -132,6 +131,11 @@ public class NonBlockingConnectionUndecidedDelegate implements NonBlockingConnec
     @Override
     public void shutdownInput()
     {
+        if (_netInputBuffer != null)
+        {
+            _netInputBuffer.dispose();
+            _netInputBuffer = null;
+        }
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/transport/network/security/ssl/SSLUtil.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/transport/network/security/ssl/SSLUtil.java b/broker-core/src/main/java/org/apache/qpid/server/transport/network/security/ssl/SSLUtil.java
index 38451f2..4eadb92 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/transport/network/security/ssl/SSLUtil.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/transport/network/security/ssl/SSLUtil.java
@@ -656,9 +656,7 @@ public class SSLUtil
 
     public final static String getServerNameFromTLSClientHello(QpidByteBuffer source)
     {
-
-        QpidByteBuffer input = source.duplicate();
-        try
+        try (QpidByteBuffer input = source.duplicate())
         {
 
             // Do we have a complete header?
@@ -680,7 +678,7 @@ public class SSLUtil
                 int recordLength = input.getUnsignedShort();
                 int messageType = input.get();
                 // 24-bit length field
-                int length = ((input.get() & 0xFF) << 16) | ((input.get() & 0xFF) << 8) | (input.get() & 0xFF);
+                int length = (input.getUnsignedByte() << 16) | (input.getUnsignedByte() << 8) | input.getUnsignedByte();
                 if(input.remaining() < length)
                 {
                     return null;
@@ -761,11 +759,6 @@ public class SSLUtil
 
             }
             return null;
-
-        }
-        finally
-        {
-            input.dispose();
         }
     }
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/transport/util/Functions.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/transport/util/Functions.java b/broker-core/src/main/java/org/apache/qpid/server/transport/util/Functions.java
index 80f1fea..e8e41da 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/transport/util/Functions.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/transport/util/Functions.java
@@ -23,10 +23,8 @@ package org.apache.qpid.server.transport.util;
 import static java.lang.Math.min;
 
 import java.nio.ByteBuffer;
-import java.util.Collection;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.util.ByteBufferUtils;
 
 
 /**
@@ -85,17 +83,6 @@ public final class Functions
         return str(buf, limit, buf.position());
     }
 
-    public static final String str(Collection<QpidByteBuffer> buf, int limit, int start)
-    {
-        return str(ByteBufferUtils.combine(buf),limit,start);
-    }
-
-
-    public static final String str(Collection<QpidByteBuffer> buf, int limit)
-    {
-        return str(buf, limit, 0);
-    }
-
     public static final String str(QpidByteBuffer buf, int limit, int start)
     {
         StringBuilder str = new StringBuilder();

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/util/ByteBufferUtils.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/util/ByteBufferUtils.java b/broker-core/src/main/java/org/apache/qpid/server/util/ByteBufferUtils.java
deleted file mode 100644
index d83ca84..0000000
--- a/broker-core/src/main/java/org/apache/qpid/server/util/ByteBufferUtils.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- *
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *   http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied.  See the License for the
- * specific language governing permissions and limitations
- * under the License.
- *
- */
-package org.apache.qpid.server.util;
-
-import java.nio.ByteBuffer;
-import java.util.Collection;
-
-import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-
-public class ByteBufferUtils
-{
-    private static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.allocate(0);
-
-    public static ByteBuffer combine(Collection<QpidByteBuffer> bufs)
-    {
-        if(bufs == null || bufs.isEmpty())
-        {
-            return EMPTY_BYTE_BUFFER;
-        }
-        else
-        {
-            int size = 0;
-            boolean isDirect = false;
-            for(QpidByteBuffer buf : bufs)
-            {
-                size += buf.remaining();
-                isDirect = isDirect || buf.isDirect();
-            }
-            ByteBuffer combined = isDirect ? ByteBuffer.allocateDirect(size) : ByteBuffer.allocate(size);
-
-            for(QpidByteBuffer buf : bufs)
-            {
-                buf.copyTo(combined);
-            }
-            combined.flip();
-            return combined;
-        }
-    }
-
-    public static int remaining(Collection<QpidByteBuffer> bufs)
-    {
-        int size = 0;
-        if (bufs != null && !bufs.isEmpty())
-        {
-            for (QpidByteBuffer buf : bufs)
-            {
-                size += buf.remaining();
-            }
-
-        }
-        return size;
-    }
-}

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/util/HousekeepingExecutor.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/util/HousekeepingExecutor.java b/broker-core/src/main/java/org/apache/qpid/server/util/HousekeepingExecutor.java
index 58d6975..3ca0255 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/util/HousekeepingExecutor.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/util/HousekeepingExecutor.java
@@ -20,9 +20,7 @@
  */
 package org.apache.qpid.server.util;
 
-import java.util.Map;
 import java.util.concurrent.CancellationException;
-import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Future;
 import java.util.concurrent.ScheduledThreadPoolExecutor;
@@ -40,11 +38,10 @@ public class HousekeepingExecutor extends ScheduledThreadPoolExecutor
 {
 
     private static final Logger LOGGER = LoggerFactory.getLogger(HousekeepingExecutor.class);
-    private final Map<Thread, QpidByteBuffer> _cachedBufferMap = new ConcurrentHashMap<>();
 
     public HousekeepingExecutor(final String threadPrefix, final int threadCount, final Subject subject)
     {
-        super(threadCount, createThreadFactory(threadPrefix, threadCount, subject));
+        super(threadCount, QpidByteBuffer.createQpidByteBufferTrackingThreadFactory(createThreadFactory(threadPrefix, threadCount, subject)));
 
     }
 
@@ -58,16 +55,6 @@ public class HousekeepingExecutor extends ScheduledThreadPoolExecutor
     {
         super.afterExecute(r, t);
 
-        final QpidByteBuffer cachedThreadLocalBuffer = QpidByteBuffer.getCachedThreadLocalBuffer();
-        if (cachedThreadLocalBuffer != null)
-        {
-            _cachedBufferMap.put(Thread.currentThread(), cachedThreadLocalBuffer);
-        }
-        else
-        {
-            _cachedBufferMap.remove(Thread.currentThread());
-        }
-
         if (t == null && r instanceof Future<?>)
         {
             Future future = (Future<?>) r;
@@ -111,15 +98,4 @@ public class HousekeepingExecutor extends ScheduledThreadPoolExecutor
             }
         }
     }
-
-    @Override
-    protected void terminated()
-    {
-        super.terminated();
-        for (QpidByteBuffer qpidByteBuffer : _cachedBufferMap.values())
-        {
-            qpidByteBuffer.dispose();
-        }
-        _cachedBufferMap.clear();
-    }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/virtualhost/AsynchronousMessageStoreRecoverer.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/virtualhost/AsynchronousMessageStoreRecoverer.java b/broker-core/src/main/java/org/apache/qpid/server/virtualhost/AsynchronousMessageStoreRecoverer.java
index 675c31f..280f786 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/virtualhost/AsynchronousMessageStoreRecoverer.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/virtualhost/AsynchronousMessageStoreRecoverer.java
@@ -27,7 +27,9 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.CopyOnWriteArraySet;
+import java.util.concurrent.Executors;
 import java.util.concurrent.SynchronousQueue;
+import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 
@@ -38,6 +40,7 @@ import com.google.common.util.concurrent.MoreExecutors;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.logging.EventLogger;
 import org.apache.qpid.server.logging.messages.TransactionLogMessages;
 import org.apache.qpid.server.logging.subjects.MessageStoreLogSubject;
@@ -45,7 +48,6 @@ import org.apache.qpid.server.message.MessageReference;
 import org.apache.qpid.server.message.ServerMessage;
 import org.apache.qpid.server.model.Queue;
 import org.apache.qpid.server.plugin.MessageMetaDataType;
-import org.apache.qpid.server.pool.QpidByteBufferDisposingThreadPoolExecutor;
 import org.apache.qpid.server.queue.QueueEntry;
 import org.apache.qpid.server.store.MessageEnqueueRecord;
 import org.apache.qpid.server.store.MessageStore;
@@ -98,9 +100,12 @@ public class AsynchronousMessageStoreRecoverer implements MessageStoreRecoverer
         private final AtomicBoolean _recoveryComplete = new AtomicBoolean();
         private final Map<Long, MessageReference<? extends ServerMessage<?>>> _recoveredMessages = new HashMap<>();
         private final ListeningExecutorService _queueRecoveryExecutor =
-                MoreExecutors.listeningDecorator(new QpidByteBufferDisposingThreadPoolExecutor(0, Integer.MAX_VALUE,
-                                                                                               60L, TimeUnit.SECONDS,
-                                                                                               new SynchronousQueue<Runnable>()));
+                MoreExecutors.listeningDecorator(new ThreadPoolExecutor(0,
+                                                                        Integer.MAX_VALUE,
+                                                                        60L,
+                                                                        TimeUnit.SECONDS,
+                                                                        new SynchronousQueue<Runnable>(),
+                                                                        QpidByteBuffer.createQpidByteBufferTrackingThreadFactory(Executors.defaultThreadFactory())));
 
         private final MessageStore.MessageStoreReader _storeReader;
         private AtomicBoolean _continueRecovery = new AtomicBoolean(true);

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferOutputStreamTest.java
----------------------------------------------------------------------
diff --git a/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferOutputStreamTest.java b/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferOutputStreamTest.java
index 522d032..f723524 100644
--- a/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferOutputStreamTest.java
+++ b/broker-core/src/test/java/org/apache/qpid/server/bytebuffer/QpidByteBufferOutputStreamTest.java
@@ -21,94 +21,93 @@
 
 package org.apache.qpid.server.bytebuffer;
 
-import java.util.Collection;
-import java.util.Iterator;
+import java.nio.charset.StandardCharsets;
 
-import junit.framework.TestCase;
 import org.junit.Assert;
 
-public class QpidByteBufferOutputStreamTest extends TestCase
+import org.apache.qpid.test.utils.QpidTestCase;
+
+public class QpidByteBufferOutputStreamTest extends QpidTestCase
 {
-    public void testWriteByteByByte() throws Exception
-    {
-        boolean direct = false;
-        QpidByteBufferOutputStream stream = new QpidByteBufferOutputStream(direct, 3);
-        stream.write('a');
-        stream.write('b');
+    private static final int BUFFER_SIZE = 10;
+    private static final int POOL_SIZE = 20;
+    private static final double SPARSITY_FRACTION = 0.5;
 
-        Collection<QpidByteBuffer> bufs = stream.fetchAccumulatedBuffers();
-        assertEquals("Unexpected number of buffers", 2, bufs.size());
-        Iterator<QpidByteBuffer> bufItr = bufs.iterator();
+    @Override
+    protected void setUp() throws Exception
+    {
+        super.setUp();
+        QpidByteBuffer.deinitialisePool();
+        QpidByteBuffer.initialisePool(BUFFER_SIZE, POOL_SIZE, SPARSITY_FRACTION);
+    }
 
-        QpidByteBuffer buf1 = bufItr.next();
-        assertBufferContent("1st buffer", buf1, "a".getBytes(), direct);
+    @Override
+    public void tearDown() throws Exception
+    {
+        try
+        {
+            super.tearDown();
+        }
+        finally
+        {
+            QpidByteBuffer.deinitialisePool();
+        }
+    }
 
+    public void testWriteByteByByte() throws Exception
+    {
+        boolean direct = false;
+        try (QpidByteBufferOutputStream stream = new QpidByteBufferOutputStream(direct, 3))
+        {
+            stream.write('a');
+            stream.write('b');
 
-        QpidByteBuffer buf2 = bufItr.next();
-        assertBufferContent("2nd buffer", buf2, "b".getBytes(), direct);
+            assertBufferContent(false, "ab".getBytes(StandardCharsets.UTF_8), stream.fetchAccumulatedBuffer());
+        }
     }
 
     public void testWriteByteArrays() throws Exception
     {
         boolean direct = false;
-        QpidByteBufferOutputStream stream = new QpidByteBufferOutputStream(direct, 8);
-        stream.write("abcd".getBytes(), 0, 4);
-        stream.write("_ef_".getBytes(), 1, 2);
-
-        Collection<QpidByteBuffer> bufs = stream.fetchAccumulatedBuffers();
-        assertEquals("Unexpected number of buffers", 2, bufs.size());
-        Iterator<QpidByteBuffer> bufItr = bufs.iterator();
+        try (QpidByteBufferOutputStream stream = new QpidByteBufferOutputStream(direct, 8))
+        {
+            stream.write("abcd".getBytes(), 0, 4);
+            stream.write("_ef_".getBytes(), 1, 2);
 
-        QpidByteBuffer buf1 = bufItr.next();
-        assertBufferContent("1st buffer", buf1, "abcd".getBytes(), direct);
-
-        QpidByteBuffer buf2 = bufItr.next();
-        assertBufferContent("2nd buffer", buf2, "ef".getBytes(), direct);
+            assertBufferContent(direct, "abcdef".getBytes(StandardCharsets.UTF_8), stream.fetchAccumulatedBuffer());
+        }
     }
 
     public void testWriteMixed() throws Exception
     {
         boolean direct = true;
-        QpidByteBufferOutputStream stream = new QpidByteBufferOutputStream(direct, 3);
-        stream.write('a');
-        stream.write("bcd".getBytes());
-
-        Collection<QpidByteBuffer> bufs = stream.fetchAccumulatedBuffers();
-        assertEquals("Unexpected number of buffers", 2, bufs.size());
-        Iterator<QpidByteBuffer> bufItr = bufs.iterator();
+        try (QpidByteBufferOutputStream stream = new QpidByteBufferOutputStream(direct, 3))
+        {
+            stream.write('a');
+            stream.write("bcd".getBytes());
 
-        QpidByteBuffer buf1 = bufItr.next();
-        assertBufferContent("1st buffer", buf1, "a".getBytes(), direct);
-
-        QpidByteBuffer buf2 = bufItr.next();
-        assertBufferContent("2nd buffer", buf2, "bcd".getBytes(), direct);
+            assertBufferContent(direct, "abcd".getBytes(StandardCharsets.UTF_8), stream.fetchAccumulatedBuffer());
+        }
     }
 
 
     public void testWriteByteArrays_ArrayTooLargeForSingleBuffer() throws Exception
     {
         boolean direct = false;
-        QpidByteBufferOutputStream stream = new QpidByteBufferOutputStream(direct, 8);
-        stream.write("abcdefghi".getBytes());
-
-        Collection<QpidByteBuffer> bufs = stream.fetchAccumulatedBuffers();
-        assertEquals("Unexpected number of buffers", 2, bufs.size());
-        Iterator<QpidByteBuffer> bufItr = bufs.iterator();
+        try (QpidByteBufferOutputStream stream = new QpidByteBufferOutputStream(direct, 8))
+        {
+            stream.write("abcdefghi".getBytes());
 
-        QpidByteBuffer buf1 = bufItr.next();
-        assertBufferContent("1st buffer", buf1, "abcdefgh".getBytes(), direct);
-
-        QpidByteBuffer buf2 = bufItr.next();
-        assertBufferContent("2nd buffer", buf2, "i".getBytes(), direct);
+            assertBufferContent(direct, "abcdefghi".getBytes(StandardCharsets.UTF_8), stream.fetchAccumulatedBuffer());
+        }
     }
 
-    private void assertBufferContent(String bufName, QpidByteBuffer buf, byte[] expectedBytes, final boolean direct)
+    private void assertBufferContent(final boolean isDirect, final byte[] expected, final QpidByteBuffer buffer)
     {
-        assertEquals(bufName + " has unexpected number of bytes", expectedBytes.length, buf.remaining());
-        byte[] copy = new byte[buf.remaining()];
-        buf.get(copy);
-        Assert.assertArrayEquals(bufName + " has unexpected content", expectedBytes, copy);
-        assertEquals(bufName + " has unexpected type", direct, buf.isDirect());
+        assertEquals("Unexpected buffer type", isDirect, buffer.isDirect());
+        byte[] buf = new byte[buffer.remaining()];
+        buffer.get(buf);
+        buffer.dispose();
+        Assert.assertArrayEquals("Unexpected buffer content", expected, buf);
     }
-
-}
\ No newline at end of file
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[03/10] qpid-broker-j git commit: QPID-7832: [Java Broker] Refactor store/protocol API using Collection

Posted by lq...@apache.org.
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/AmqpValueSectionConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/AmqpValueSectionConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/AmqpValueSectionConstructor.java
index a8e51bc..dea8b76 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/AmqpValueSectionConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/AmqpValueSectionConstructor.java
@@ -23,10 +23,7 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructor;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructorRegistry;
 import org.apache.qpid.server.protocol.v1_0.codec.TypeConstructor;
@@ -58,36 +55,36 @@ public class AmqpValueSectionConstructor implements DescribedTypeConstructor<Amq
 
     @Override
     public TypeConstructor<AmqpValueSection> construct(final Object descriptor,
-                                                        final List<QpidByteBuffer> in,
-                                                        final int[] originalPositions,
+                                                        final QpidByteBuffer in,
+                                                        final int originalPosition,
                                                         final ValueHandler valueHandler)
             throws AmqpErrorException
     {
-        return new LazyConstructor(originalPositions);
+        return new LazyConstructor(originalPosition);
     }
 
 
     private class LazyConstructor extends AbstractLazyConstructor<AmqpValueSection>
     {
-        LazyConstructor(final int[] originalPositions)
+        LazyConstructor(final int originalPosition)
         {
-            super(originalPositions);
+            super(originalPosition);
         }
 
         @Override
-        protected AmqpValueSection createObject(final List<QpidByteBuffer> encoding, final ValueHandler handler)
+        protected AmqpValueSection createObject(final QpidByteBuffer encoding, final ValueHandler handler)
         {
             return new AmqpValueSection(encoding);
         }
 
         @Override
-        protected void skipValue(final List<QpidByteBuffer> in) throws AmqpErrorException
+        protected void skipValue(final QpidByteBuffer in) throws AmqpErrorException
         {
-            if (!QpidByteBufferUtils.hasRemaining(in))
+            if (!in.hasRemaining())
             {
                 throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Insufficient data to decode AMQP value section.");
             }
-            byte formatCode = QpidByteBufferUtils.get(in);
+            byte formatCode = in.get();
 
             if (formatCode == ValueHandler.DESCRIBED_TYPE)
             {
@@ -122,32 +119,32 @@ public class AmqpValueSectionConstructor implements DescribedTypeConstructor<Amq
                     case 0x0a:
                     case 0x0c:
                     case 0x0e:
-                        if (!QpidByteBufferUtils.hasRemaining(in))
+                        if (!in.hasRemaining())
                         {
                             throw new AmqpErrorException(AmqpError.DECODE_ERROR,
                                                          "Insufficient data to decode AMQP value section.");
                         }
-                        skipLength = ((int) QpidByteBufferUtils.get(in)) & 0xFF;
+                        skipLength = in.getUnsignedByte();
                         break;
                     case 0x0b:
                     case 0x0d:
                     case 0x0f:
-                        if (!QpidByteBufferUtils.hasRemaining(in, 4))
+                        if (!in.hasRemaining(4))
                         {
                             throw new AmqpErrorException(AmqpError.DECODE_ERROR,
                                                          "Insufficient data to decode AMQP value section.");
                         }
-                        skipLength = QpidByteBufferUtils.getInt(in);
+                        skipLength = in.getInt();
                         break;
                     default:
                         throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Unknown type");
                 }
-                if (!QpidByteBufferUtils.hasRemaining(in, skipLength))
+                if (!in.hasRemaining(skipLength))
                 {
                     throw new AmqpErrorException(AmqpError.DECODE_ERROR,
                                                  "Insufficient data to decode AMQP value section.");
                 }
-                QpidByteBufferUtils.skip(in,skipLength);
+                in.position(in.position() + skipLength);
             }
         }
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/ApplicationPropertiesSectionConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/ApplicationPropertiesSectionConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/ApplicationPropertiesSectionConstructor.java
index a40efcd..2c99841 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/ApplicationPropertiesSectionConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/ApplicationPropertiesSectionConstructor.java
@@ -23,8 +23,6 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructorRegistry;
 import org.apache.qpid.server.protocol.v1_0.type.Symbol;
@@ -50,7 +48,7 @@ public class ApplicationPropertiesSectionConstructor extends DescribedMapSection
 
     @Override
     protected ApplicationPropertiesSection createObject(final DescribedTypeConstructorRegistry describedTypeRegistry,
-                                                        final List<QpidByteBuffer> encodedForm)
+                                                        final QpidByteBuffer encodedForm)
     {
         return new ApplicationPropertiesSection(encodedForm);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DataSectionConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DataSectionConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DataSectionConstructor.java
index e27c878..101c60d 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DataSectionConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DataSectionConstructor.java
@@ -23,12 +23,9 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructor;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructorRegistry;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.codec.TypeConstructor;
 import org.apache.qpid.server.protocol.v1_0.codec.ValueHandler;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
@@ -59,16 +56,16 @@ public class DataSectionConstructor implements DescribedTypeConstructor<DataSect
 
     @Override
     public TypeConstructor<DataSection> construct(final Object descriptor,
-                                                        final List<QpidByteBuffer> in,
-                                                        final int[] originalPositions,
+                                                        final QpidByteBuffer in,
+                                                        final int originalPosition,
                                                         final ValueHandler valueHandler)
             throws AmqpErrorException
     {
-        if (!QpidByteBufferUtils.hasRemaining(in))
+        if (!in.hasRemaining())
         {
             throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Insufficient data to decode data section.");
         }
-        int constructorByte = QpidByteBufferUtils.get(in) & 0xff;
+        int constructorByte = in.getUnsignedByte();
         int sizeBytes;
         switch(constructorByte)
         {
@@ -83,7 +80,7 @@ public class DataSectionConstructor implements DescribedTypeConstructor<DataSect
                                              "The described section must always be binary");
         }
 
-        return new LazyConstructor(sizeBytes, originalPositions);
+        return new LazyConstructor(sizeBytes, originalPosition);
     }
 
 
@@ -91,22 +88,22 @@ public class DataSectionConstructor implements DescribedTypeConstructor<DataSect
     {
         private final int _sizeBytes;
 
-        public LazyConstructor(final int sizeBytes, final int[] originalPositions)
+        public LazyConstructor(final int sizeBytes, final int originalPosition)
         {
-            super(originalPositions);
+            super(originalPosition);
             _sizeBytes = sizeBytes;
         }
 
         @Override
-        protected DataSection createObject(final List<QpidByteBuffer> encoding, final ValueHandler handler)
+        protected DataSection createObject(final QpidByteBuffer encoding, final ValueHandler handler)
         {
             return new DataSection(encoding);
         }
 
         @Override
-        protected void skipValue(final List<QpidByteBuffer> in) throws AmqpErrorException
+        protected void skipValue(final QpidByteBuffer in) throws AmqpErrorException
         {
-            if (!QpidByteBufferUtils.hasRemaining(in, _sizeBytes))
+            if (!in.hasRemaining(_sizeBytes))
             {
                 throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Insufficient data to decode data section.");
             }
@@ -114,19 +111,19 @@ public class DataSectionConstructor implements DescribedTypeConstructor<DataSect
             switch(_sizeBytes)
             {
                 case 1:
-                    size = QpidByteBufferUtils.get(in) & 0xff;
+                    size = in.getUnsignedByte();
                     break;
                 case 4:
-                    size = QpidByteBufferUtils.getInt(in);
+                    size = in.getInt();
                     break;
                 default:
                     throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Unexpected constructor type, can only be 1 or 4");
             }
-            if (!QpidByteBufferUtils.hasRemaining(in, size))
+            if (!in.hasRemaining(size))
             {
                 throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Insufficient data to decode data section.");
             }
-            QpidByteBufferUtils.skip(in, size);
+            in.position(in.position() + size);
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DeliveryAnnotationsSectionConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DeliveryAnnotationsSectionConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DeliveryAnnotationsSectionConstructor.java
index eed18b9..cde1d28 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DeliveryAnnotationsSectionConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DeliveryAnnotationsSectionConstructor.java
@@ -23,8 +23,6 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructorRegistry;
 import org.apache.qpid.server.protocol.v1_0.type.Symbol;
@@ -50,7 +48,7 @@ public class DeliveryAnnotationsSectionConstructor extends DescribedMapSectionCo
 
     @Override
     protected DeliveryAnnotationsSection createObject(final DescribedTypeConstructorRegistry describedTypeRegistry,
-                                                      final List<QpidByteBuffer> encodedForm)
+                                                      final QpidByteBuffer encodedForm)
     {
         return new DeliveryAnnotationsSection(encodedForm);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DescribedListSectionConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DescribedListSectionConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DescribedListSectionConstructor.java
index 061521b..31f9f15 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DescribedListSectionConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DescribedListSectionConstructor.java
@@ -23,11 +23,8 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructor;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.codec.TypeConstructor;
 import org.apache.qpid.server.protocol.v1_0.codec.ValueHandler;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
@@ -39,16 +36,16 @@ public abstract class DescribedListSectionConstructor<S extends AbstractSection>
 
     @Override
     public TypeConstructor<S> construct(final Object descriptor,
-                                                        final List<QpidByteBuffer> in,
-                                                        final int[] originalPositions,
-                                                        final ValueHandler valueHandler)
+                                        final QpidByteBuffer in,
+                                        final int originalPosition,
+                                        final ValueHandler valueHandler)
             throws AmqpErrorException
     {
-        if (!QpidByteBufferUtils.hasRemaining(in))
+        if (!in.hasRemaining())
         {
             throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Insufficient data to decode section.");
         }
-        int constructorByte = QpidByteBufferUtils.get(in) & 0xff;
+        int constructorByte = in.getUnsignedByte();
         int sizeBytes;
         switch(constructorByte)
         {
@@ -66,7 +63,7 @@ public abstract class DescribedListSectionConstructor<S extends AbstractSection>
                                              "The described section must always be a list");
         }
 
-        return new LazyConstructor(sizeBytes, originalPositions);
+        return new LazyConstructor(sizeBytes, originalPosition);
     }
 
 
@@ -74,22 +71,22 @@ public abstract class DescribedListSectionConstructor<S extends AbstractSection>
     {
         private final int _sizeBytes;
 
-        LazyConstructor(final int sizeBytes, final int[] originalPositions)
+        LazyConstructor(final int sizeBytes, final int originalPosition)
         {
-            super(originalPositions);
+            super(originalPosition);
             _sizeBytes = sizeBytes;
         }
 
         @Override
-        protected S createObject(final List<QpidByteBuffer> encoding, final ValueHandler handler)
+        protected S createObject(final QpidByteBuffer encoding, final ValueHandler handler)
         {
             return DescribedListSectionConstructor.this.createObject(encoding);
         }
 
         @Override
-        protected void skipValue(final List<QpidByteBuffer> in) throws AmqpErrorException
+        protected void skipValue(final QpidByteBuffer in) throws AmqpErrorException
         {
-            if (!QpidByteBufferUtils.hasRemaining(in, _sizeBytes))
+            if (!in.hasRemaining(_sizeBytes))
             {
                 throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Insufficient data to decode section.");
             }
@@ -100,21 +97,21 @@ public abstract class DescribedListSectionConstructor<S extends AbstractSection>
                     size = 0;
                     break;
                 case 1:
-                    size = QpidByteBufferUtils.get(in) & 0xFF;
+                    size = in.getUnsignedByte();
                     break;
                 case 4:
-                    size = QpidByteBufferUtils.getInt(in);
+                    size = in.getInt();
                     break;
                 default:
                     throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Unexpected constructor type, can only be 0,1 or 4");
             }
-            if (!QpidByteBufferUtils.hasRemaining(in, size))
+            if (!in.hasRemaining(size))
             {
                 throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Insufficient data to decode section.");
             }
-            QpidByteBufferUtils.skip(in, size);
+            in.position(in.position() + size);
         }
     }
 
-    protected abstract S createObject(final List<QpidByteBuffer> encodedForm);
+    protected abstract S createObject(final QpidByteBuffer encodedForm);
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DescribedMapSectionConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DescribedMapSectionConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DescribedMapSectionConstructor.java
index c7793b5..a06078c 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DescribedMapSectionConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/DescribedMapSectionConstructor.java
@@ -23,10 +23,7 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructor;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructorRegistry;
 import org.apache.qpid.server.protocol.v1_0.codec.SectionDecoderRegistry;
@@ -42,16 +39,16 @@ public abstract class DescribedMapSectionConstructor<S extends AbstractSection>
 
     @Override
     public TypeConstructor<S> construct(final Object descriptor,
-                                                        final List<QpidByteBuffer> in,
-                                                        final int[] originalPositions,
-                                                        final ValueHandler valueHandler)
+                                        final QpidByteBuffer in,
+                                        final int originalPosition,
+                                        final ValueHandler valueHandler)
             throws AmqpErrorException
     {
-        if (!QpidByteBufferUtils.hasRemaining(in))
+        if (!in.hasRemaining())
         {
             throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Insufficient data to decode section.");
         }
-        int constructorByte = QpidByteBufferUtils.get(in) & 0xff;
+        int constructorByte = in.getUnsignedByte();
         int sizeBytes;
         switch(constructorByte)
         {
@@ -66,7 +63,7 @@ public abstract class DescribedMapSectionConstructor<S extends AbstractSection>
                                              "The described section must always be a map");
         }
 
-        return new LazyConstructor(sizeBytes, originalPositions);
+        return new LazyConstructor(sizeBytes, originalPosition);
     }
 
 
@@ -74,23 +71,23 @@ public abstract class DescribedMapSectionConstructor<S extends AbstractSection>
     {
         private final int _sizeBytes;
 
-        LazyConstructor(final int sizeBytes, final int[] originalPositions)
+        LazyConstructor(final int sizeBytes, final int originalPosition)
         {
-            super(originalPositions);
+            super(originalPosition);
             _sizeBytes = sizeBytes;
         }
 
         @Override
-        protected S createObject(final List<QpidByteBuffer> encoding, final ValueHandler handler)
+        protected S createObject(final QpidByteBuffer encoding, final ValueHandler handler)
         {
             return DescribedMapSectionConstructor.this.createObject(((SectionDecoderRegistry) handler.getDescribedTypeRegistry())
                                                                             .getUnderlyingRegistry(), encoding);
         }
 
         @Override
-        protected void skipValue(final List<QpidByteBuffer> in) throws AmqpErrorException
+        protected void skipValue(final QpidByteBuffer in) throws AmqpErrorException
         {
-            if (!QpidByteBufferUtils.hasRemaining(in, _sizeBytes))
+            if (!in.hasRemaining(_sizeBytes))
             {
                 throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Insufficient data to decode section.");
             }
@@ -98,22 +95,22 @@ public abstract class DescribedMapSectionConstructor<S extends AbstractSection>
             switch(_sizeBytes)
             {
                 case 1:
-                    size = QpidByteBufferUtils.get(in) & 0xff;
+                    size = in.getUnsignedByte();
                     break;
                 case 4:
-                    size = QpidByteBufferUtils.getInt(in);
+                    size = in.getInt();
                     break;
                 default:
                     throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Unexpected constructor type, can only be 1 or 4");
             }
-            if (!QpidByteBufferUtils.hasRemaining(in, size))
+            if (!in.hasRemaining(size))
             {
                 throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Insufficient data to decode section.");
             }
-            QpidByteBufferUtils.skip(in, size);
+            in.position(in.position() + size);
         }
     }
 
     protected abstract S createObject(final DescribedTypeConstructorRegistry describedTypeRegistry,
-                                      final List<QpidByteBuffer> encodedForm);
+                                      final QpidByteBuffer encodedForm);
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/EncodingRetaining.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/EncodingRetaining.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/EncodingRetaining.java
index d35a875..de38511 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/EncodingRetaining.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/EncodingRetaining.java
@@ -20,15 +20,13 @@
  */
 package org.apache.qpid.server.protocol.v1_0.type.messaging.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 
 public interface EncodingRetaining
 {
     void writeTo(QpidByteBuffer dest);
     long getEncodedSize();
-    List<QpidByteBuffer> getEncodedForm();
+    QpidByteBuffer getEncodedForm();
     void clearEncodedForm();
     EncodingRetaining copy();
     void reallocate();

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/FooterSectionConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/FooterSectionConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/FooterSectionConstructor.java
index a2f9e93..43d87d3 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/FooterSectionConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/FooterSectionConstructor.java
@@ -23,8 +23,6 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructorRegistry;
 import org.apache.qpid.server.protocol.v1_0.type.Symbol;
@@ -50,7 +48,7 @@ public class FooterSectionConstructor extends DescribedMapSectionConstructor<Foo
 
     @Override
     protected FooterSection createObject(final DescribedTypeConstructorRegistry describedTypeRegistry,
-                                         final List<QpidByteBuffer> encodedForm)
+                                         final QpidByteBuffer encodedForm)
     {
         return new FooterSection(encodedForm);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/HeaderSectionConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/HeaderSectionConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/HeaderSectionConstructor.java
index 205290e..362f2f5 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/HeaderSectionConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/HeaderSectionConstructor.java
@@ -23,8 +23,6 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructorRegistry;
 import org.apache.qpid.server.protocol.v1_0.type.Symbol;
@@ -49,7 +47,7 @@ public class HeaderSectionConstructor extends DescribedListSectionConstructor<He
     }
 
     @Override
-    protected HeaderSection createObject(final List<QpidByteBuffer> encodedForm)
+    protected HeaderSection createObject(final QpidByteBuffer encodedForm)
     {
         return new HeaderSection(encodedForm);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/MessageAnnotationsSectionConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/MessageAnnotationsSectionConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/MessageAnnotationsSectionConstructor.java
index 4504c12..c61b025 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/MessageAnnotationsSectionConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/MessageAnnotationsSectionConstructor.java
@@ -23,8 +23,6 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructorRegistry;
 import org.apache.qpid.server.protocol.v1_0.type.Symbol;
@@ -50,7 +48,7 @@ public class MessageAnnotationsSectionConstructor extends DescribedMapSectionCon
 
     @Override
     protected MessageAnnotationsSection createObject(final DescribedTypeConstructorRegistry describedTypeRegistry,
-                                                     final List<QpidByteBuffer> encodedForm)
+                                                     final QpidByteBuffer encodedForm)
     {
         return new MessageAnnotationsSection(encodedForm);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/PropertiesSectionConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/PropertiesSectionConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/PropertiesSectionConstructor.java
index 4e40362..331d172 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/PropertiesSectionConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/PropertiesSectionConstructor.java
@@ -23,8 +23,6 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructorRegistry;
 import org.apache.qpid.server.protocol.v1_0.type.Symbol;
@@ -49,7 +47,7 @@ public class PropertiesSectionConstructor extends DescribedListSectionConstructo
     }
 
     @Override
-    protected PropertiesSection createObject(final List<QpidByteBuffer> encodedForm)
+    protected PropertiesSection createObject(final QpidByteBuffer encodedForm)
     {
         return new PropertiesSection(encodedForm);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/transport/Transfer.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/transport/Transfer.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/transport/Transfer.java
index d757cb7..e4d3231 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/transport/Transfer.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/transport/Transfer.java
@@ -23,14 +23,11 @@
 package org.apache.qpid.server.protocol.v1_0.type.transport;
 
 
-import java.util.ArrayList;
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.protocol.v1_0.ConnectionHandler;
-import org.apache.qpid.server.protocol.v1_0.type.Binary;
 import org.apache.qpid.server.protocol.v1_0.CompositeType;
 import org.apache.qpid.server.protocol.v1_0.CompositeTypeField;
+import org.apache.qpid.server.protocol.v1_0.ConnectionHandler;
+import org.apache.qpid.server.protocol.v1_0.type.Binary;
 import org.apache.qpid.server.protocol.v1_0.type.DeliveryState;
 import org.apache.qpid.server.protocol.v1_0.type.FrameBody;
 import org.apache.qpid.server.protocol.v1_0.type.UnsignedInteger;
@@ -38,7 +35,7 @@ import org.apache.qpid.server.protocol.v1_0.type.UnsignedInteger;
 @CompositeType( symbolicDescriptor = "amqp:transfer:list", numericDescriptor = 0x0000000000000014L)
 public class Transfer implements FrameBody
 {
-    private volatile List<QpidByteBuffer> _payload;
+    private volatile QpidByteBuffer _payload;
 
     @CompositeTypeField(index = 0, mandatory = true)
     private UnsignedInteger _handle;
@@ -298,7 +295,7 @@ public class Transfer implements FrameBody
         conn.receiveTransfer(channel, this);
     }
 
-    public List<QpidByteBuffer> getPayload()
+    public QpidByteBuffer getPayload()
     {
         if (_payload == null)
         {
@@ -306,16 +303,11 @@ public class Transfer implements FrameBody
         }
         else
         {
-            List<QpidByteBuffer> payloadDup = new ArrayList<>(_payload.size());
-            for (QpidByteBuffer buf : _payload)
-            {
-                payloadDup.add(buf.duplicate());
-            }
-            return payloadDup;
+            return _payload.duplicate();
         }
     }
 
-    public void setPayload(List<QpidByteBuffer> payload)
+    public void setPayload(QpidByteBuffer payload)
     {
         if (payload == null)
         {
@@ -323,11 +315,7 @@ public class Transfer implements FrameBody
         }
         else
         {
-            _payload = new ArrayList<>(payload.size());
-            for (QpidByteBuffer buf : payload)
-            {
-                _payload.add(buf.duplicate());
-            }
+            _payload = payload.duplicate();
         }
     }
 
@@ -335,10 +323,7 @@ public class Transfer implements FrameBody
     {
         if (_payload != null)
         {
-            for (QpidByteBuffer buf : _payload)
-            {
-                buf.dispose();
-            }
+            _payload.dispose();
             _payload = null;
         }
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/ConsumerTarget_1_0Test.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/ConsumerTarget_1_0Test.java b/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/ConsumerTarget_1_0Test.java
index 9d3ef53..42abcf9 100644
--- a/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/ConsumerTarget_1_0Test.java
+++ b/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/ConsumerTarget_1_0Test.java
@@ -22,19 +22,18 @@ package org.apache.qpid.server.protocol.v1_0;
 
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyBoolean;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import java.util.concurrent.atomic.AtomicReference;
 
-import junit.framework.TestCase;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.MessageInstance;
 import org.apache.qpid.server.message.MessageInstanceConsumer;
@@ -56,8 +55,9 @@ import org.apache.qpid.server.protocol.v1_0.type.messaging.MessageAnnotationsSec
 import org.apache.qpid.server.protocol.v1_0.type.messaging.Properties;
 import org.apache.qpid.server.protocol.v1_0.type.transport.Transfer;
 import org.apache.qpid.server.store.StoredMessage;
+import org.apache.qpid.test.utils.QpidTestCase;
 
-public class ConsumerTarget_1_0Test extends TestCase
+public class ConsumerTarget_1_0Test extends QpidTestCase
 {
     private final AMQPDescribedTypeRegistry _describedTypeRegistry = AMQPDescribedTypeRegistry.newInstance()
                                                                                               .registerTransportLayer()
@@ -98,20 +98,16 @@ public class ConsumerTarget_1_0Test extends TestCase
         final MessageInstance messageInstance = mock(MessageInstance.class);
         when(messageInstance.getMessage()).thenReturn(message);
 
-        AtomicReference<List<QpidByteBuffer>> payload = new AtomicReference<>();
+        AtomicReference<QpidByteBuffer> payloadRef = new AtomicReference<>();
         doAnswer(invocation ->
                  {
                      final Object[] args = invocation.getArguments();
                      Transfer transfer = (Transfer) args[0];
 
-                     List<QpidByteBuffer> transferPayload = transfer.getPayload();
+                     QpidByteBuffer transferPayload = transfer.getPayload();
 
-                     final List<QpidByteBuffer> payloadCopy = new ArrayList<>(transferPayload.size());
-                     for (QpidByteBuffer qpidByteBuffer : transferPayload)
-                     {
-                         payloadCopy.add(qpidByteBuffer.duplicate());
-                     }
-                     payload.set(payloadCopy);
+                     QpidByteBuffer payloadCopy = transferPayload.duplicate();
+                     payloadRef.set(payloadCopy);
                      return null;
                  }).when(_sendingLinkEndpoint).transfer(any(Transfer.class), anyBoolean());
 
@@ -119,11 +115,11 @@ public class ConsumerTarget_1_0Test extends TestCase
 
         verify(_sendingLinkEndpoint, times(1)).transfer(any(Transfer.class), anyBoolean());
 
-        List<QpidByteBuffer> fragments = payload.get();
-
-        final List<EncodingRetainingSection<?>> sections =
-                new SectionDecoderImpl(_describedTypeRegistry.getSectionDecoderRegistry()).parseAll(fragments);
-
+        final List<EncodingRetainingSection<?>> sections;
+        try (QpidByteBuffer payload = payloadRef.get())
+        {
+            sections = new SectionDecoderImpl(_describedTypeRegistry.getSectionDecoderRegistry()).parseAll(payload);
+        }
         Header sentHeader = null;
         for (EncodingRetainingSection<?> section : sections)
         {
@@ -133,11 +129,6 @@ public class ConsumerTarget_1_0Test extends TestCase
             }
         }
 
-        for (QpidByteBuffer fragment : fragments)
-        {
-            fragment.dispose();
-        }
-
         assertNotNull("Header is not found", sentHeader);
         assertNotNull("Ttl is not set", sentHeader.getTtl());
         assertTrue("Unexpected ttl", sentHeader.getTtl().longValue() <= 1000);
@@ -162,6 +153,7 @@ public class ConsumerTarget_1_0Test extends TestCase
                                                                0);
 
         final StoredMessage<MessageMetaData_1_0> storedMessage = mock(StoredMessage.class);
+        when(storedMessage.getContent(eq(0), anyInt())).thenReturn(QpidByteBuffer.emptyQpidByteBuffer());
         when(storedMessage.getMetaData()).thenReturn(metaData);
         return new Message_1_0(storedMessage);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_Internal_to_1_0Test.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_Internal_to_1_0Test.java b/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_Internal_to_1_0Test.java
index d29175c..9ee7c86 100644
--- a/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_Internal_to_1_0Test.java
+++ b/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_Internal_to_1_0Test.java
@@ -29,7 +29,6 @@ import java.io.ByteArrayOutputStream;
 import java.io.ObjectOutputStream;
 import java.io.Serializable;
 import java.util.ArrayList;
-import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
@@ -38,8 +37,6 @@ import java.util.UUID;
 
 import com.google.common.collect.Lists;
 import org.mockito.ArgumentCaptor;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.AMQMessageHeader;
@@ -281,12 +278,12 @@ public class MessageConverter_Internal_to_1_0Test extends QpidTestCase
         }
     }
 
-    private List<EncodingRetainingSection<?>> getEncodingRetainingSections(final Collection<QpidByteBuffer> content,
+    private List<EncodingRetainingSection<?>> getEncodingRetainingSections(final QpidByteBuffer content,
                                                                            final int expectedNumberOfSections)
             throws Exception
     {
         SectionDecoder sectionDecoder = new SectionDecoderImpl(_typeRegistry.getSectionDecoderRegistry());
-        final List<EncodingRetainingSection<?>> sections = sectionDecoder.parseAll(new ArrayList<>(content));
+        final List<EncodingRetainingSection<?>> sections = sectionDecoder.parseAll(content);
         assertEquals("Unexpected number of sections", expectedNumberOfSections, sections.size());
         return sections;
     }
@@ -324,15 +321,8 @@ public class MessageConverter_Internal_to_1_0Test extends QpidTestCase
         final ArgumentCaptor<Integer> sizeCaptor = ArgumentCaptor.forClass(Integer.class);
 
         when(_handle.getContent(offsetCaptor.capture(),
-                                sizeCaptor.capture())).then(new Answer<Collection<QpidByteBuffer>>()
-        {
-            @Override
-            public Collection<QpidByteBuffer> answer(final InvocationOnMock invocation) throws Throwable
-            {
-                final QpidByteBuffer view = combined.view(offsetCaptor.getValue(), sizeCaptor.getValue());
-                return Collections.singleton(view);
-            }
-        });
+                                sizeCaptor.capture())).then(invocation -> combined.view(offsetCaptor.getValue(),
+                                                                                        sizeCaptor.getValue()));
     }
 
     private Byte getJmsMessageTypeAnnotation(final Message_1_0 convertedMessage)
@@ -362,7 +352,7 @@ public class MessageConverter_Internal_to_1_0Test extends QpidTestCase
     {
         final InternalMessage sourceMessage = getAmqMessage(messageBytes, mimeType);
         final Message_1_0 convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent();
 
         List<EncodingRetainingSection<?>> sections = getEncodingRetainingSections(content, 1);
         EncodingRetainingSection<?> encodingRetainingSection = sections.get(0);

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_v1_0_to_InternalTest.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_v1_0_to_InternalTest.java b/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_v1_0_to_InternalTest.java
index 3b2ac14..21f9d69 100644
--- a/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_v1_0_to_InternalTest.java
+++ b/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_v1_0_to_InternalTest.java
@@ -57,7 +57,6 @@ import org.apache.qpid.server.protocol.v1_0.type.messaging.Header;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.MessageAnnotations;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.Properties;
 import org.apache.qpid.server.store.StoredMessage;
-import org.apache.qpid.server.util.ByteBufferUtils;
 import org.apache.qpid.test.utils.QpidTestCase;
 
 public class MessageConverter_v1_0_to_InternalTest extends QpidTestCase
@@ -117,8 +116,6 @@ public class MessageConverter_v1_0_to_InternalTest extends QpidTestCase
 
         final InternalMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
-
         assertEquals("Unexpected mime type",
                      "application/x-java-serialized-object",
                      convertedMessage.getMessageHeader().getMimeType());
@@ -133,8 +130,6 @@ public class MessageConverter_v1_0_to_InternalTest extends QpidTestCase
 
         final InternalMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
-
         assertEquals("Unexpected mime type", null, convertedMessage.getMessageHeader().getMimeType());
         assertNull("Unexpected content", convertedMessage.getMessageBody());
     }
@@ -218,7 +213,6 @@ public class MessageConverter_v1_0_to_InternalTest extends QpidTestCase
         final InternalMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "text/plain", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertEquals("Unexpected content", expected, convertedMessage.getMessageBody());
     }
 
@@ -611,17 +605,6 @@ public class MessageConverter_v1_0_to_InternalTest extends QpidTestCase
         assertEquals("Unexpected content", null, convertedMessage.getMessageBody());
     }
 
-    private byte[] getBytes(final Collection<QpidByteBuffer> content) throws Exception
-    {
-        ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        for (QpidByteBuffer buf : content)
-        {
-            ByteStreams.copy(buf.asInputStream(), bos);
-            buf.dispose();
-        }
-        return bos.toByteArray();
-    }
-
     private Message_1_0 createTestMessage(final EncodingRetainingSection encodingRetainingSection)
     {
         return createTestMessage(new Properties(), encodingRetainingSection);
@@ -684,19 +667,19 @@ public class MessageConverter_v1_0_to_InternalTest extends QpidTestCase
 
         if (section != null)
         {
-            final QpidByteBuffer combined = QpidByteBuffer.wrap(ByteBufferUtils.combine(section.getEncodedForm()));
+            // TODO this is leaking QBBs
+            final QpidByteBuffer combined = section.getEncodedForm();
             when(storedMessage.getContentSize()).thenReturn((int) section.getEncodedSize());
             final ArgumentCaptor<Integer> offsetCaptor = ArgumentCaptor.forClass(Integer.class);
             final ArgumentCaptor<Integer> sizeCaptor = ArgumentCaptor.forClass(Integer.class);
 
             when(storedMessage.getContent(offsetCaptor.capture(),
-                                          sizeCaptor.capture())).then(invocation ->
-                                                                      {
-                                                                          final QpidByteBuffer view = combined.view(
-                                                                                  offsetCaptor.getValue(),
-                                                                                  sizeCaptor.getValue());
-                                                                          return Collections.singleton(view);
-                                                                      });
+                                          sizeCaptor.capture())).then(invocation -> combined.view(offsetCaptor.getValue(),
+                                                                                                  sizeCaptor.getValue()));
+        }
+        else
+        {
+            when(storedMessage.getContent(0,0)).thenReturn(QpidByteBuffer.emptyQpidByteBuffer());
         }
         return new Message_1_0(storedMessage);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/PropertyConverter_v1_0_to_InternalTest.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/PropertyConverter_v1_0_to_InternalTest.java b/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/PropertyConverter_v1_0_to_InternalTest.java
index dea495a..cbb6dac 100644
--- a/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/PropertyConverter_v1_0_to_InternalTest.java
+++ b/broker-plugins/amqp-1-0-protocol/src/test/java/org/apache/qpid/server/protocol/v1_0/PropertyConverter_v1_0_to_InternalTest.java
@@ -28,12 +28,10 @@ import static org.mockito.Mockito.when;
 import java.util.Collections;
 import java.util.Date;
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
 import java.util.UUID;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.message.internal.InternalMessage;
 import org.apache.qpid.server.model.NamedAddressSpace;
 import org.apache.qpid.server.protocol.v1_0.type.Binary;
@@ -390,10 +388,15 @@ public class PropertyConverter_v1_0_to_InternalTest extends QpidTestCase
         {
             Binary binary = new Binary(content);
             DataSection dataSection = new Data(binary).createEncodingRetainingSection();
-            List<QpidByteBuffer> qbbList = dataSection.getEncodedForm();
-            int length = (int) QpidByteBufferUtils.remaining(qbbList);
+            QpidByteBuffer qbb = dataSection.getEncodedForm();
+            int length = qbb.remaining();
             when(storedMessage.getContentSize()).thenReturn(length);
-            when(storedMessage.getContent(0, length)).thenReturn(qbbList);
+            when(storedMessage.getContent(0, length)).thenReturn(qbb);
+        }
+        else
+        {
+            when(storedMessage.getContentSize()).thenReturn(0);
+            when(storedMessage.getContent(0, 0)).thenReturn(QpidByteBuffer.emptyQpidByteBuffer());
         }
         return new Message_1_0(storedMessage);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_1_0_to_v0_10.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_1_0_to_v0_10.java b/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_1_0_to_v0_10.java
index 3a36b58..50a9484 100644
--- a/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_1_0_to_v0_10.java
+++ b/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_1_0_to_v0_10.java
@@ -33,8 +33,6 @@ import static org.apache.qpid.server.protocol.v1_0.MessageConverter_from_1_0.get
 import static org.apache.qpid.server.protocol.v1_0.MessageConverter_from_1_0.getUserId;
 
 import java.nio.ByteBuffer;
-import java.util.Collection;
-import java.util.Collections;
 import java.util.Date;
 import java.util.LinkedHashMap;
 import java.util.Map;
@@ -127,9 +125,9 @@ public class MessageConverter_1_0_to_v0_10 implements MessageConverter<Message_1
             }
 
             @Override
-            public Collection<QpidByteBuffer> getContent(final int offset, final int length)
+            public QpidByteBuffer getContent(final int offset, final int length)
             {
-                return Collections.singleton(QpidByteBuffer.wrap(convertedContent, offset, length));
+                return QpidByteBuffer.wrap(convertedContent, offset, length);
             }
 
             @Override

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_0_10_to_1_0Test.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_0_10_to_1_0Test.java b/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_0_10_to_1_0Test.java
index 7cf43ce..21f17c4 100644
--- a/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_0_10_to_1_0Test.java
+++ b/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_0_10_to_1_0Test.java
@@ -29,8 +29,6 @@ import java.io.ByteArrayOutputStream;
 import java.io.ObjectOutputStream;
 import java.io.Serializable;
 import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
@@ -38,8 +36,6 @@ import java.util.UUID;
 
 import com.google.common.collect.Lists;
 import org.mockito.ArgumentCaptor;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.AMQMessageHeader;
@@ -342,12 +338,12 @@ public class MessageConverter_0_10_to_1_0Test extends QpidTestCase
         return expected;
     }
 
-    private List<EncodingRetainingSection<?>> getEncodingRetainingSections(final Collection<QpidByteBuffer> content,
+    private List<EncodingRetainingSection<?>> getEncodingRetainingSections(final QpidByteBuffer content,
                                                                            final int expectedNumberOfSections)
             throws Exception
     {
         SectionDecoder sectionDecoder = new SectionDecoderImpl(_typeRegistry.getSectionDecoderRegistry());
-        final List<EncodingRetainingSection<?>> sections = sectionDecoder.parseAll(new ArrayList<>(content));
+        final List<EncodingRetainingSection<?>> sections = sectionDecoder.parseAll(content);
         assertEquals("Unexpected number of sections", expectedNumberOfSections, sections.size());
         return sections;
     }
@@ -378,15 +374,8 @@ public class MessageConverter_0_10_to_1_0Test extends QpidTestCase
         final ArgumentCaptor<Integer> sizeCaptor = ArgumentCaptor.forClass(Integer.class);
 
         when(_handle.getContent(offsetCaptor.capture(),
-                                sizeCaptor.capture())).then(new Answer<Collection<QpidByteBuffer>>()
-        {
-            @Override
-            public Collection<QpidByteBuffer> answer(final InvocationOnMock invocation) throws Throwable
-            {
-                final QpidByteBuffer view = combined.view(offsetCaptor.getValue(), sizeCaptor.getValue());
-                return Collections.singleton(view);
-            }
-        });
+                                sizeCaptor.capture())).then(invocation -> combined.view(offsetCaptor.getValue(),
+                                                                                        sizeCaptor.getValue()));
     }
 
     private Byte getJmsMessageTypeAnnotation(final Message_1_0 convertedMessage)
@@ -468,7 +457,7 @@ public class MessageConverter_0_10_to_1_0Test extends QpidTestCase
     {
         final MessageTransferMessage sourceMessage = getAmqMessage(messageBytes, mimeType);
         final Message_1_0 convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         List<EncodingRetainingSection<?>> sections = getEncodingRetainingSections(content, 1);
         EncodingRetainingSection<?> encodingRetainingSection = sections.get(0);

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_1_0_to_v0_10Test.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_1_0_to_v0_10Test.java b/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_1_0_to_v0_10Test.java
index 3e83f73..8bbc6a7 100644
--- a/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_1_0_to_v0_10Test.java
+++ b/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/MessageConverter_1_0_to_v0_10Test.java
@@ -27,9 +27,9 @@ import static org.mockito.Mockito.when;
 
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.io.ObjectOutputStream;
 import java.util.ArrayList;
-import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.LinkedHashMap;
@@ -67,7 +67,6 @@ import org.apache.qpid.server.typedmessage.mimecontentconverter.JmsMapMessageToM
 import org.apache.qpid.server.typedmessage.mimecontentconverter.JmsStreamMessageToList;
 import org.apache.qpid.server.typedmessage.mimecontentconverter.ListToJmsStreamMessage;
 import org.apache.qpid.server.typedmessage.mimecontentconverter.MapToJmsMapMessage;
-import org.apache.qpid.server.util.ByteBufferUtils;
 import org.apache.qpid.test.utils.QpidTestCase;
 
 public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
@@ -127,7 +126,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
 
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         assertEquals("Unexpected mime type",
                      "application/java-object-stream",
@@ -143,7 +142,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
 
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType());
         assertArrayEquals("Unexpected content size",
@@ -235,7 +234,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
 
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType());
 
@@ -268,7 +267,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "text/plain", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertEquals("Unexpected content", expected, new String(getBytes(content), UTF_8));
     }
 
@@ -282,7 +281,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "text/plain", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertEquals("Unexpected content", expected, new String(getBytes(content), UTF_8));
     }
 
@@ -298,7 +297,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         Map<String, Object> convertedMap = new JmsMapMessageToMap().toObject(getBytes(content));
         assertEquals("Unexpected size", originalMap.size(), convertedMap.size());
@@ -319,7 +318,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "amqp/map", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         Map<String, Object> convertedMap = new AmqpMapToMapConverter().toObject(getBytes(content));
         assertEquals("Unexpected size", originalMap.size(), convertedMap.size());
@@ -355,7 +354,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "jms/stream-message", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         List<Object> convertedList = new JmsStreamMessageToList().toObject(getBytes(content));
         assertEquals("Unexpected size", originalList.size(), convertedList.size());
@@ -374,7 +373,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "amqp/list", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         List<Object> convertedList = new AmqpListToListConverter().toObject(getBytes(content));
         assertEquals("Unexpected size", originalList.size(), convertedList.size());
@@ -427,7 +426,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "jms/stream-message", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertEquals("Unexpected content", expected, new JmsStreamMessageToList().toObject(getBytes(content)));
     }
 
@@ -440,7 +439,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "amqp/list", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         List<Object> convertedList = new AmqpListToListConverter().toObject(getBytes(content));
         assertEquals("Unexpected size", originalList.size(), convertedList.size());
@@ -500,7 +499,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
 
         assertEquals("Unexpected mime type",
                      expectedMimeType, convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", data, getBytes(content));
     }
 
@@ -520,7 +519,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
 
         assertEquals("Unexpected mime type",
                      expectedMimeType, convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", data, getBytes(content));
     }
 
@@ -553,7 +552,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
 
         assertEquals("Unexpected mime type",
                      expectedMimeType, convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", data, getBytes(content));
     }
 
@@ -573,7 +572,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
 
         assertEquals("Unexpected mime type",
                      expectedMimeType, convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", data, getBytes(content));
     }
 
@@ -643,7 +642,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "amqp/map", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", bytes, getBytes(content));
     }
 
@@ -660,7 +659,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", bytes, getBytes(content));
     }
 
@@ -677,7 +676,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "amqp/list", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", bytes, getBytes(content));
     }
 
@@ -694,7 +693,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "jms/stream-message", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", bytes, getBytes(content));
     }
 
@@ -711,7 +710,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
         assertEquals("Unexpected mime type",
                      "application/java-object-stream",
                      convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", expected, getBytes(content));
     }
 
@@ -729,7 +728,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
         assertEquals("Unexpected mime type",
                      "application/java-object-stream",
                      convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", expected, getBytes(content));
     }
 
@@ -746,7 +745,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
         assertEquals("Unexpected mime type",
                      "application/octet-stream",
                      convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", expected, getBytes(content));
     }
 
@@ -761,7 +760,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
         assertEquals("Unexpected mime type",
                      "application/octet-stream",
                      convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", expected, getBytes(content));
     }
 
@@ -781,7 +780,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
 
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         assertEquals("Unexpected mime type",
                      "application/java-object-stream",
@@ -795,7 +794,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
 
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType());
         assertArrayEquals("Unexpected content size",
@@ -894,7 +893,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
 
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType());
 
@@ -929,21 +928,21 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
 
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertEquals("Unexpected content", expected, new String(getBytes(content), UTF_8));
 
         assertEquals("Unexpected mime type", "text/plain", convertedMessage.getMessageHeader().getMimeType());
     }
 
-    private byte[] getBytes(final Collection<QpidByteBuffer> content) throws Exception
+    private byte[] getBytes(final QpidByteBuffer content) throws Exception
     {
-        ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        for (QpidByteBuffer buf : content)
+        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
+             InputStream contentInputStream = content.asInputStream())
         {
-            ByteStreams.copy(buf.asInputStream(), bos);
-            buf.dispose();
+            ByteStreams.copy(contentInputStream, bos);
+            content.dispose();
+            return bos.toByteArray();
         }
-        return bos.toByteArray();
     }
 
     private Message_1_0 createTestMessage(final EncodingRetainingSection encodingRetainingSection)
@@ -1008,20 +1007,21 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
 
         if (section != null)
         {
-            final QpidByteBuffer combined = QpidByteBuffer.wrap(ByteBufferUtils.combine(section.getEncodedForm()));
+            // TODO this seems to leak QBBs
+            final QpidByteBuffer combined = section.getEncodedForm();
             when(storedMessage.getContentSize()).thenReturn((int) section.getEncodedSize());
             final ArgumentCaptor<Integer> offsetCaptor = ArgumentCaptor.forClass(Integer.class);
             final ArgumentCaptor<Integer> sizeCaptor = ArgumentCaptor.forClass(Integer.class);
 
             when(storedMessage.getContent(offsetCaptor.capture(),
-                                          sizeCaptor.capture())).then(invocation ->
-                                                                      {
-                                                                          final QpidByteBuffer view = combined.view(
-                                                                                  offsetCaptor.getValue(),
-                                                                                  sizeCaptor.getValue());
-                                                                          return Collections.singleton(view);
-                                                                      });
+                                          sizeCaptor.capture())).then(invocation -> combined.view(offsetCaptor.getValue(),
+                                                                                                  sizeCaptor.getValue()));
         }
+        else
+        {
+            when(storedMessage.getContent(0,0)).thenReturn(QpidByteBuffer.emptyQpidByteBuffer());
+        }
+
         return new Message_1_0(storedMessage);
     }
 
@@ -1048,7 +1048,7 @@ public class MessageConverter_1_0_to_v0_10Test extends QpidTestCase
 
         assertEquals("Unexpected mime type",
                      expectedMimeType, convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent();
         assertArrayEquals("Unexpected content", data, getBytes(content));
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/PropertyConverter_0_10_to_1_0Test.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/PropertyConverter_0_10_to_1_0Test.java b/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/PropertyConverter_0_10_to_1_0Test.java
index f9b90f6..26f6ff1 100644
--- a/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/PropertyConverter_0_10_to_1_0Test.java
+++ b/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/PropertyConverter_0_10_to_1_0Test.java
@@ -546,8 +546,12 @@ public class PropertyConverter_0_10_to_1_0Test extends QpidTestCase
         if (content != null)
         {
             when(storedMessage.getContentSize()).thenReturn(content.length);
-            when(storedMessage.getContent(0, content.length)).thenReturn(Collections.singleton(QpidByteBuffer.wrap(
-                    content)));
+            when(storedMessage.getContent(0, content.length)).thenReturn(QpidByteBuffer.wrap(content));
+        }
+        else
+        {
+            when(storedMessage.getContentSize()).thenReturn(0);
+            when(storedMessage.getContent(0, 0)).thenReturn(QpidByteBuffer.emptyQpidByteBuffer());
         }
         return new MessageTransferMessage(storedMessage, null);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/PropertyConverter_1_0_to_0_10Test.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/PropertyConverter_1_0_to_0_10Test.java b/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/PropertyConverter_1_0_to_0_10Test.java
index 9e664ba..fea4a40 100644
--- a/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/PropertyConverter_1_0_to_0_10Test.java
+++ b/broker-plugins/amqp-msg-conv-0-10-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_10_v1_0/PropertyConverter_1_0_to_0_10Test.java
@@ -31,15 +31,10 @@ import java.util.Arrays;
 import java.util.Collections;
 import java.util.Date;
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
 import java.util.UUID;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
-import org.apache.qpid.server.message.AMQMessageHeader;
-import org.apache.qpid.server.message.MessageDestination;
-import org.apache.qpid.server.message.internal.InternalMessage;
 import org.apache.qpid.server.model.Exchange;
 import org.apache.qpid.server.model.NamedAddressSpace;
 import org.apache.qpid.server.model.Queue;
@@ -1054,10 +1049,15 @@ public class PropertyConverter_1_0_to_0_10Test extends QpidTestCase
         {
             Binary binary = new Binary(content);
             DataSection dataSection = new Data(binary).createEncodingRetainingSection();
-            List<QpidByteBuffer> qbbList = dataSection.getEncodedForm();
-            int length = (int) QpidByteBufferUtils.remaining(qbbList);
+            QpidByteBuffer qbb = dataSection.getEncodedForm();
+            int length = qbb.remaining();
             when(storedMessage.getContentSize()).thenReturn(length);
-            when(storedMessage.getContent(0, length)).thenReturn(qbbList);
+            when(storedMessage.getContent(0, length)).thenReturn(qbb);
+        }
+        else
+        {
+            when(storedMessage.getContentSize()).thenReturn(0);
+            when(storedMessage.getContent(0, 0)).thenReturn(QpidByteBuffer.emptyQpidByteBuffer());
         }
         return new Message_1_0(storedMessage);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_10_to_0_8.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_10_to_0_8.java b/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_10_to_0_8.java
index 1d298d8..7a2c82c 100644
--- a/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_10_to_0_8.java
+++ b/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_10_to_0_8.java
@@ -20,33 +20,32 @@
  */
 package org.apache.qpid.server.protocol.converter.v0_8_v0_10;
 
-import java.util.Collection;
 import java.util.HashMap;
 import java.util.Map;
 
-import org.apache.qpid.server.protocol.converter.MessageConversionException;
-import org.apache.qpid.server.protocol.v0_8.AMQPInvalidClassException;
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.exchange.ExchangeDefaults;
-import org.apache.qpid.server.protocol.v0_8.AMQShortString;
-import org.apache.qpid.server.protocol.v0_8.transport.BasicContentHeaderProperties;
-import org.apache.qpid.server.protocol.v0_8.transport.ContentHeaderBody;
-import org.apache.qpid.server.protocol.v0_8.FieldTable;
-import org.apache.qpid.server.protocol.v0_8.transport.MessagePublishInfo;
 import org.apache.qpid.server.message.MessageDestination;
 import org.apache.qpid.server.model.Exchange;
 import org.apache.qpid.server.model.NamedAddressSpace;
 import org.apache.qpid.server.plugin.MessageConverter;
 import org.apache.qpid.server.plugin.PluggableService;
+import org.apache.qpid.server.protocol.converter.MessageConversionException;
 import org.apache.qpid.server.protocol.v0_10.MessageTransferMessage;
-import org.apache.qpid.server.protocol.v0_8.AMQMessage;
-import org.apache.qpid.server.protocol.v0_8.MessageMetaData;
-import org.apache.qpid.server.store.StoredMessage;
 import org.apache.qpid.server.protocol.v0_10.transport.DeliveryProperties;
 import org.apache.qpid.server.protocol.v0_10.transport.Header;
 import org.apache.qpid.server.protocol.v0_10.transport.MessageDeliveryMode;
 import org.apache.qpid.server.protocol.v0_10.transport.MessageProperties;
 import org.apache.qpid.server.protocol.v0_10.transport.ReplyTo;
+import org.apache.qpid.server.protocol.v0_8.AMQMessage;
+import org.apache.qpid.server.protocol.v0_8.AMQPInvalidClassException;
+import org.apache.qpid.server.protocol.v0_8.AMQShortString;
+import org.apache.qpid.server.protocol.v0_8.FieldTable;
+import org.apache.qpid.server.protocol.v0_8.MessageMetaData;
+import org.apache.qpid.server.protocol.v0_8.transport.BasicContentHeaderProperties;
+import org.apache.qpid.server.protocol.v0_8.transport.ContentHeaderBody;
+import org.apache.qpid.server.protocol.v0_8.transport.MessagePublishInfo;
+import org.apache.qpid.server.store.StoredMessage;
 
 @PluggableService
 public class MessageConverter_0_10_to_0_8 implements MessageConverter<MessageTransferMessage, AMQMessage>
@@ -257,7 +256,7 @@ public class MessageConverter_0_10_to_0_8 implements MessageConverter<MessageTra
             }
 
             @Override
-            public Collection<QpidByteBuffer> getContent(final int offset, final int length)
+            public QpidByteBuffer getContent(final int offset, final int length)
             {
                 return message.getContent(offset, length);
             }


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[10/10] qpid-broker-j git commit: QPID-7832: [Java Broker] Refactor store/protocol API using Collection

Posted by lq...@apache.org.
QPID-7832: [Java Broker] Refactor store/protocol API using Collection<QpidByteBuffer>


Project: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/repo
Commit: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/commit/660c206d
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/660c206d
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/660c206d

Branch: refs/heads/master
Commit: 660c206deb352aca3694a6b31f5f7cf6fca70533
Parents: 955a79b
Author: Lorenz Quack <lq...@apache.org>
Authored: Fri Oct 13 16:10:50 2017 +0100
Committer: Lorenz Quack <lq...@apache.org>
Committed: Wed Oct 18 16:21:21 2017 +0100

----------------------------------------------------------------------
 .../berkeleydb/AbstractBDBMessageStore.java     |  199 +--
 .../berkeleydb/tuple/ByteBufferBinding.java     |   15 +-
 .../tuple/MessageMetaDataBinding.java           |   25 +-
 .../store/berkeleydb/BDBMessageStoreTest.java   |  247 +--
 .../bytebuffer/NonPooledByteBufferRef.java      |    4 +
 .../server/bytebuffer/PooledByteBufferRef.java  |    6 +
 .../qpid/server/bytebuffer/QpidByteBuffer.java  | 1656 +++++++++++++-----
 .../bytebuffer/QpidByteBufferInputStream.java   |  109 --
 .../bytebuffer/QpidByteBufferOutputStream.java  |   62 +-
 .../server/bytebuffer/QpidByteBufferUtils.java  |  285 ---
 .../configuration/updater/TaskExecutorImpl.java |   33 +-
 .../message/AbstractServerMessageImpl.java      |    8 +-
 .../server/message/MessageContentSource.java    |    5 +-
 .../message/internal/InternalMessage.java       |   21 +-
 .../internal/InternalMessageMetaDataType.java   |    6 +-
 .../qpid/server/plugin/MessageFormat.java       |    6 +-
 .../qpid/server/plugin/MessageMetaDataType.java |    6 +-
 ...idByteBufferDisposingThreadPoolExecutor.java |   81 -
 .../server/protocol/v0_8/AMQShortString.java    |    2 +-
 .../qpid/server/protocol/v0_8/FieldArray.java   |   11 +-
 .../apache/qpid/server/queue/AbstractQueue.java |   53 +-
 .../qpid/server/store/MemoryMessageStore.java   |    9 +-
 .../qpid/server/store/StoredMemoryMessage.java  |   77 +-
 .../apache/qpid/server/store/StoredMessage.java |    4 +-
 .../store/serializer/v1/Deserializer.java       |   27 +-
 .../store/serializer/v1/MessageRecord.java      |   19 +-
 .../v1/MessageStoreSerializer_v1.java           |   35 +-
 .../transport/MultiVersionProtocolEngine.java   |   41 +-
 .../transport/NetworkConnectionScheduler.java   |   17 +-
 .../server/transport/NonBlockingConnection.java |   52 +-
 .../NonBlockingConnectionDelegate.java          |    3 +-
 .../NonBlockingConnectionPlainDelegate.java     |   50 +-
 .../NonBlockingConnectionTLSDelegate.java       |   61 +-
 .../NonBlockingConnectionUndecidedDelegate.java |   38 +-
 .../transport/network/security/ssl/SSLUtil.java |   11 +-
 .../qpid/server/transport/util/Functions.java   |   13 -
 .../qpid/server/util/ByteBufferUtils.java       |   71 -
 .../qpid/server/util/HousekeepingExecutor.java  |   26 +-
 .../AsynchronousMessageStoreRecoverer.java      |   13 +-
 .../QpidByteBufferOutputStreamTest.java         |  119 +-
 .../server/bytebuffer/QpidByteBufferTest.java   |  491 +++---
 .../server/protocol/v0_8/FieldTableTest.java    |   10 +-
 .../security/TrustStoreMessageSourceTest.java   |   22 +-
 .../qpid/server/store/MessageStoreTestCase.java |   12 -
 .../store/TestMessageMetaDataFactory.java       |    9 +-
 .../server/store/TestMessageMetaDataType.java   |   15 +-
 .../qpid/server/txn/MockServerMessage.java      |   10 +-
 .../VirtualHostPropertiesNodeTest.java          |    4 +
 .../protocol/v0_10/ConsumerTarget_0_10.java     |   63 +-
 .../MessageConverter_Internal_to_v0_10.java     |    6 +-
 .../protocol/v0_10/MessageConverter_v0_10.java  |    4 +-
 .../MessageConverter_v0_10_to_Internal.java     |    8 +-
 .../protocol/v0_10/MessageFormat_0_10.java      |   42 +-
 .../v0_10/MessageMetaDataType_0_10.java         |    6 +-
 .../protocol/v0_10/MessageMetaData_0_10.java    |    2 +-
 .../protocol/v0_10/MessageTransferMessage.java  |    8 +-
 .../server/protocol/v0_10/ServerAssembler.java  |  208 ++-
 .../server/protocol/v0_10/ServerConnection.java |   11 +-
 .../server/protocol/v0_10/ServerDecoder.java    |  117 +-
 .../protocol/v0_10/ServerDisassembler.java      |  109 +-
 .../protocol/v0_10/ServerSessionDelegate.java   |    7 +-
 .../v0_10/transport/MessageTransfer.java        |   79 +-
 .../server/protocol/v0_10/transport/Method.java |   10 +-
 .../MessageConverter_0_10_to_InternalTest.java  |   13 +-
 .../MessageConverter_Internal_to_0_10Test.java  |   30 +-
 .../PropertyConverter_0_10_to_InternalTest.java |    8 +-
 ...PropertyConverter_Internal_to_v0_10Test.java |    4 +-
 .../protocol/v0_10/ServerSessionTest.java       |   11 +-
 .../qpid/server/protocol/v0_8/AMQChannel.java   |   22 +
 .../protocol/v0_8/AMQPConnection_0_8Impl.java   |   19 +-
 .../qpid/server/protocol/v0_8/CachedFrame.java  |   14 +-
 .../v0_8/MessageConverter_Internal_to_v0_8.java |    6 +-
 .../v0_8/MessageConverter_v0_8_to_Internal.java |    8 +-
 .../protocol/v0_8/MessageFormat_0_9_1.java      |  153 +-
 .../server/protocol/v0_8/MessageMetaData.java   |   39 +-
 .../protocol/v0_8/MessageMetaDataType_0_8.java  |    6 +-
 .../v0_8/ProtocolOutputConverterImpl.java       |  106 +-
 .../protocol/v0_8/transport/AMQFrame.java       |   23 +-
 .../v0_8/transport/AMQMethodBodyImpl.java       |   15 +-
 .../transport/BasicContentHeaderProperties.java |   33 +-
 .../protocol/v0_8/transport/ContentBody.java    |   19 +-
 .../v0_8/transport/ContentHeaderBody.java       |   22 +-
 .../server/protocol/v0_8/AMQDecoderTest.java    |   65 +-
 .../MessageConverter_0_8_to_InternalTest.java   |   13 +-
 .../MessageConverter_Internal_to_0_8Test.java   |   31 +-
 .../v0_8/MessageMetaDataFactoryTest.java        |   54 +-
 .../PropertyConverter_v0_8_to_InternalTest.java |    9 +-
 .../protocol/v1_0/AMQPConnection_1_0.java       |    3 +-
 .../protocol/v1_0/AMQPConnection_1_0Impl.java   |  115 +-
 .../v1_0/AbstractReceivingLinkEndpoint.java     |   12 +
 .../protocol/v1_0/ConsumerTarget_1_0.java       |   26 +-
 .../qpid/server/protocol/v1_0/Delivery.java     |   21 +-
 .../v1_0/MessageConverter_from_1_0.java         |   49 +-
 .../protocol/v1_0/MessageConverter_to_1_0.java  |   42 +-
 .../server/protocol/v1_0/MessageFormat_1_0.java |   11 +-
 .../protocol/v1_0/MessageMetaDataType_1_0.java  |    6 +-
 .../protocol/v1_0/MessageMetaData_1_0.java      |   25 +-
 .../qpid/server/protocol/v1_0/Message_1_0.java  |   60 +-
 .../qpid/server/protocol/v1_0/Session_1_0.java  |   18 +-
 .../v1_0/StandardReceivingLinkEndpoint.java     |   13 +-
 .../TxnCoordinatorReceivingLinkEndpoint.java    |  106 +-
 .../codec/AbstractCompositeTypeConstructor.java |   22 +-
 .../codec/AbstractDescribedTypeConstructor.java |    8 +-
 .../v1_0/codec/ArrayTypeConstructor.java        |   27 +-
 .../v1_0/codec/BinaryTypeConstructor.java       |   15 +-
 .../protocol/v1_0/codec/BooleanConstructor.java |   15 +-
 .../v1_0/codec/ByteTypeConstructor.java         |    9 +-
 .../v1_0/codec/CharTypeConstructor.java         |   13 +-
 .../protocol/v1_0/codec/DecimalConstructor.java |   22 +-
 .../v1_0/codec/DescribedTypeConstructor.java    |    6 +-
 .../v1_0/codec/DoubleTypeConstructor.java       |    9 +-
 .../v1_0/codec/FloatTypeConstructor.java        |    9 +-
 .../server/protocol/v1_0/codec/FrameWriter.java |   38 +-
 .../protocol/v1_0/codec/IntTypeConstructor.java |    9 +-
 .../protocol/v1_0/codec/ListConstructor.java    |   15 +-
 .../v1_0/codec/LongTypeConstructor.java         |    9 +-
 .../protocol/v1_0/codec/MapConstructor.java     |   18 +-
 .../v1_0/codec/NullTypeConstructor.java         |    4 +-
 .../v1_0/codec/ShortTypeConstructor.java        |    9 +-
 .../v1_0/codec/SmallIntConstructor.java         |    9 +-
 .../v1_0/codec/SmallLongConstructor.java        |    9 +-
 .../v1_0/codec/SmallUIntConstructor.java        |    9 +-
 .../v1_0/codec/SmallULongConstructor.java       |    9 +-
 .../v1_0/codec/StringTypeConstructor.java       |   61 +-
 .../v1_0/codec/SymbolTypeConstructor.java       |   67 +-
 .../v1_0/codec/TimestampTypeConstructor.java    |    8 +-
 .../protocol/v1_0/codec/TypeConstructor.java    |    4 +-
 .../v1_0/codec/UByteTypeConstructor.java        |    9 +-
 .../v1_0/codec/UIntTypeConstructor.java         |    9 +-
 .../v1_0/codec/ULongTypeConstructor.java        |    9 +-
 .../v1_0/codec/UShortTypeConstructor.java       |    9 +-
 .../v1_0/codec/UUIDTypeConstructor.java         |   10 +-
 .../protocol/v1_0/codec/ValueHandler.java       |   42 +-
 .../v1_0/codec/ZeroListConstructor.java         |    2 +-
 .../v1_0/codec/ZeroUIntConstructor.java         |    6 +-
 .../v1_0/codec/ZeroULongConstructor.java        |    6 +-
 .../server/protocol/v1_0/framing/AMQFrame.java  |   12 +-
 .../protocol/v1_0/framing/FrameHandler.java     |   21 +-
 .../protocol/v1_0/framing/TransportFrame.java   |    4 +-
 .../protocol/v1_0/messaging/SectionDecoder.java |    2 +-
 .../v1_0/messaging/SectionDecoderImpl.java      |   36 +-
 .../protocol/v1_0/store/LinkStoreUtils.java     |   22 +-
 .../v1_0/type/messaging/AbstractSection.java    |  101 +-
 .../type/messaging/AmqpSequenceSection.java     |    2 +-
 .../v1_0/type/messaging/AmqpValueSection.java   |    4 +-
 .../messaging/ApplicationPropertiesSection.java |    3 +-
 .../v1_0/type/messaging/DataSection.java        |    4 +-
 .../messaging/DeliveryAnnotationsSection.java   |    3 +-
 .../v1_0/type/messaging/FooterSection.java      |    3 +-
 .../v1_0/type/messaging/HeaderSection.java      |    4 +-
 .../messaging/MessageAnnotationsSection.java    |    3 +-
 .../v1_0/type/messaging/PropertiesSection.java  |    4 +-
 .../codec/AbstractLazyConstructor.java          |   44 +-
 .../codec/AmqpSequenceSectionConstructor.java   |    4 +-
 .../codec/AmqpValueSectionConstructor.java      |   33 +-
 ...ApplicationPropertiesSectionConstructor.java |    4 +-
 .../messaging/codec/DataSectionConstructor.java |   31 +-
 .../DeliveryAnnotationsSectionConstructor.java  |    4 +-
 .../codec/DescribedListSectionConstructor.java  |   35 +-
 .../codec/DescribedMapSectionConstructor.java   |   35 +-
 .../type/messaging/codec/EncodingRetaining.java |    4 +-
 .../codec/FooterSectionConstructor.java         |    4 +-
 .../codec/HeaderSectionConstructor.java         |    4 +-
 .../MessageAnnotationsSectionConstructor.java   |    4 +-
 .../codec/PropertiesSectionConstructor.java     |    4 +-
 .../protocol/v1_0/type/transport/Transfer.java  |   31 +-
 .../protocol/v1_0/ConsumerTarget_1_0Test.java   |   36 +-
 .../MessageConverter_Internal_to_1_0Test.java   |   20 +-
 .../MessageConverter_v1_0_to_InternalTest.java  |   33 +-
 .../PropertyConverter_v1_0_to_InternalTest.java |   13 +-
 .../MessageConverter_1_0_to_v0_10.java          |    6 +-
 .../MessageConverter_0_10_to_1_0Test.java       |   21 +-
 .../MessageConverter_1_0_to_v0_10Test.java      |   88 +-
 .../PropertyConverter_0_10_to_1_0Test.java      |    8 +-
 .../PropertyConverter_1_0_to_0_10Test.java      |   16 +-
 .../MessageConverter_0_10_to_0_8.java           |   23 +-
 .../MessageConverter_0_8_to_0_10.java           |   16 +-
 .../PropertyConverter_0_10_to_0_8Test.java      |    8 +-
 .../PropertyConverter_0_8_to_0_10Test.java      |    9 +-
 .../v0_8_v1_0/MessageConverter_1_0_to_v0_8.java |    6 +-
 .../MessageConverter_0_8_to_1_0Test.java        |   21 +-
 .../MessageConverter_1_0_to_v0_8Test.java       |   87 +-
 .../PropertyConverter_0_8_to_1_0Test.java       |    8 +-
 .../PropertyConverter_1_0_to_0_8Test.java       |    5 +-
 .../store/derby/AbstractDerbyMessageStore.java  |    5 +-
 .../qpid/server/store/derby/DerbyUtils.java     |    5 +-
 .../store/jdbc/AbstractJDBCMessageStore.java    |  204 +--
 .../jdbc/GenericJDBCConfigurationStore.java     |   13 +-
 .../store/jdbc/GenericJDBCMessageStore.java     |    9 +-
 .../management/plugin/HttpManagement.java       |   59 +-
 .../management/plugin/report/ReportRunner.java  |   11 +-
 .../plugin/report/ReportRunnerTest.java         |    3 +
 .../transport/websocket/WebSocketProvider.java  |  119 +-
 .../tests/protocol/v1_0/FrameTransport.java     |   33 +-
 .../qpid/tests/protocol/v1_0/Interaction.java   |   19 +-
 .../tests/protocol/v1_0/MessageDecoder.java     |   11 +-
 .../tests/protocol/v1_0/MessageEncoder.java     |   10 +-
 .../qpid/tests/protocol/v1_0/OutputHandler.java |    4 +-
 .../apache/qpid/tests/protocol/v1_0/Utils.java  |   44 +-
 .../tests/protocol/v1_0/DecodeErrorTest.java    |   39 +-
 .../protocol/v1_0/messaging/MessageFormat.java  |    9 +-
 .../v1_0/messaging/MultiTransferTest.java       |   60 +-
 .../protocol/v1_0/messaging/OutcomeTest.java    |    1 -
 .../protocol/v1_0/messaging/TransferTest.java   |    8 +-
 .../transport/link/ResumeDeliveriesTest.java    |   13 +-
 .../qpid/transport/ProtocolNegotiationTest.java |    1 +
 206 files changed, 3492 insertions(+), 4625 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/AbstractBDBMessageStore.java
----------------------------------------------------------------------
diff --git a/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/AbstractBDBMessageStore.java b/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/AbstractBDBMessageStore.java
index f84b02c..c871508 100644
--- a/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/AbstractBDBMessageStore.java
+++ b/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/AbstractBDBMessageStore.java
@@ -21,11 +21,9 @@ package org.apache.qpid.server.store.berkeleydb;
 import static org.apache.qpid.server.store.berkeleydb.BDBUtils.DEFAULT_DATABASE_CONFIG;
 import static org.apache.qpid.server.store.berkeleydb.BDBUtils.abortTransactionSafely;
 
-import java.nio.ByteBuffer;
-import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
 import java.util.Random;
@@ -62,7 +60,6 @@ import org.apache.qpid.server.store.StoredMessage;
 import org.apache.qpid.server.store.TransactionLogResource;
 import org.apache.qpid.server.store.berkeleydb.entry.PreparedTransaction;
 import org.apache.qpid.server.store.berkeleydb.entry.QueueEntryKey;
-import org.apache.qpid.server.store.berkeleydb.tuple.ByteBufferBinding;
 import org.apache.qpid.server.store.berkeleydb.tuple.MessageMetaDataBinding;
 import org.apache.qpid.server.store.berkeleydb.tuple.PreparedTransactionBinding;
 import org.apache.qpid.server.store.berkeleydb.tuple.QueueEntryBinding;
@@ -88,12 +85,11 @@ public abstract class AbstractBDBMessageStore implements MessageStore
     private static final String BRIDGEDB_NAME = "BRIDGES";
     private static final String LINKDB_NAME = "LINKS";
     private static final String XID_DB_NAME = "XIDS";
-    private static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.allocateDirect(0);
 
     private final EventManager _eventManager = new EventManager();
 
     private final DatabaseEntry MESSAGE_METADATA_SEQ_KEY = new DatabaseEntry("MESSAGE_METADATA_SEQ_KEY".getBytes(
-            Charset.forName("UTF-8")));
+            StandardCharsets.UTF_8));
 
     private final SequenceConfig MESSAGE_METADATA_SEQ_CONFIG = SequenceConfig.DEFAULT.
             setAllowCreate(true).
@@ -351,66 +347,7 @@ public abstract class AbstractBDBMessageStore implements MessageStore
         }
     }
 
-
-    /**
-     * Fills the provided ByteBuffer with as much content for the specified message as possible, starting
-     * from the specified offset in the message.
-     *
-     * @param messageId The message to get the data for.
-     * @param offset    The offset of the data within the message.
-     * @param dst       The destination of the content read back
-     *
-     * @return The number of bytes inserted into the destination
-     *
-     * @throws org.apache.qpid.server.store.StoreException If the operation fails for any reason, or if the specified message does not exist.
-     */
-    int getContent(long messageId, int offset, ByteBuffer dst) throws StoreException
-    {
-        DatabaseEntry contentKeyEntry = new DatabaseEntry();
-        LongBinding.longToEntry(messageId, contentKeyEntry);
-        DatabaseEntry value = new DatabaseEntry();
-        ByteBufferBinding contentTupleBinding = ByteBufferBinding.getInstance();
-
-
-        getLogger().debug("Message Id: {} Getting content body from offset: {}", messageId, offset);
-
-
-        try
-        {
-
-            int written = 0;
-            OperationStatus status = getMessageContentDb().get(null, contentKeyEntry, value, LockMode.READ_UNCOMMITTED);
-            if (status == OperationStatus.SUCCESS)
-            {
-                QpidByteBuffer buffer = contentTupleBinding.entryToObject(value);
-                int size = buffer.remaining();
-                if (offset > size)
-                {
-                    throw new RuntimeException("Offset " + offset + " is greater than message size " + size
-                                               + " for message id " + messageId + "!");
-
-                }
-
-                written = size - offset;
-                if(written > dst.remaining())
-                {
-                    written = dst.remaining();
-                }
-                buffer = buffer.view(offset, written);
-                buffer.get(dst);
-            }
-            return written;
-        }
-        catch (RuntimeException e)
-        {
-            throw getEnvironmentFacade().handleDatabaseException("Error getting AMQMessage with id "
-                                                                 + messageId
-                                                                 + " to database: "
-                                                                 + e.getMessage(), e);
-        }
-    }
-
-    Collection<QpidByteBuffer> getAllContent(long messageId) throws StoreException
+    QpidByteBuffer getAllContent(long messageId) throws StoreException
     {
         DatabaseEntry contentKeyEntry = new DatabaseEntry();
         LongBinding.longToEntry(messageId, contentKeyEntry);
@@ -427,15 +364,10 @@ public abstract class AbstractBDBMessageStore implements MessageStore
                 byte[] data = value.getData();
                 int offset = value.getOffset();
                 int length = value.getSize();
-                Collection<QpidByteBuffer> buffers = QpidByteBuffer.allocateDirectCollection(length);
-                for(QpidByteBuffer buf : buffers)
-                {
-                    int bufSize = buf.remaining();
-                    buf.put(data, offset, bufSize);
-                    buf.flip();
-                    offset+=bufSize;
-                }
-                return buffers;
+                QpidByteBuffer buf = QpidByteBuffer.allocateDirect(length);
+                buf.put(data, offset, length);
+                buf.flip();
+                return buf;
             }
             else
             {
@@ -534,25 +466,14 @@ public abstract class AbstractBDBMessageStore implements MessageStore
      *
      * @throws org.apache.qpid.server.store.StoreException If the operation fails for any reason, or if the specified message does not exist.
      */
-    private void addContent(final Transaction tx, long messageId,
-                            Collection<QpidByteBuffer> contentBody) throws StoreException
+    private void addContent(final Transaction tx, long messageId, QpidByteBuffer contentBody) throws StoreException
     {
         DatabaseEntry key = new DatabaseEntry();
         LongBinding.longToEntry(messageId, key);
         DatabaseEntry value = new DatabaseEntry();
 
-        int size = 0;
-
-        for(QpidByteBuffer buf : contentBody)
-        {
-            size += buf.remaining();
-        }
-        byte[] data = new byte[size];
-        ByteBuffer dst = ByteBuffer.wrap(data);
-        for(QpidByteBuffer buf : contentBody)
-        {
-            buf.copyTo(dst);
-        }
+        byte[] data = new byte[contentBody.remaining()];
+        contentBody.copyTo(data);
         value.setData(data);
         try
         {
@@ -937,7 +858,7 @@ public abstract class AbstractBDBMessageStore implements MessageStore
     private static class MessageDataRef<T extends StorableMessageMetaData>
     {
         private volatile T _metaData;
-        private volatile Collection<QpidByteBuffer> _data;
+        private volatile QpidByteBuffer _data;
         private volatile boolean _isHardRef;
 
         private MessageDataRef(final T metaData, boolean isHardRef)
@@ -945,7 +866,7 @@ public abstract class AbstractBDBMessageStore implements MessageStore
             this(metaData, null, isHardRef);
         }
 
-        private MessageDataRef(final T metaData, Collection<QpidByteBuffer> data, boolean isHardRef)
+        private MessageDataRef(final T metaData, QpidByteBuffer data, boolean isHardRef)
         {
             _metaData = metaData;
             _data = data;
@@ -957,12 +878,12 @@ public abstract class AbstractBDBMessageStore implements MessageStore
             return _metaData;
         }
 
-        public Collection<QpidByteBuffer> getData()
+        public QpidByteBuffer getData()
         {
             return _data;
         }
 
-        public void setData(final Collection<QpidByteBuffer> data)
+        public void setData(final QpidByteBuffer data)
         {
             _data = data;
         }
@@ -997,11 +918,8 @@ public abstract class AbstractBDBMessageStore implements MessageStore
             }
             if(_data != null)
             {
-                for(QpidByteBuffer buf : _data)
-                {
-                    bytesCleared += buf.remaining();
-                    buf.dispose();
-                }
+                bytesCleared += _data.remaining();
+                _data.dispose();
                 _data = null;
             }
             return bytesCleared;
@@ -1058,20 +976,17 @@ public abstract class AbstractBDBMessageStore implements MessageStore
         @Override
         public synchronized void addContent(QpidByteBuffer src)
         {
-            src = src.slice();
-            Collection<QpidByteBuffer> data = _messageDataRef.getData();
-            if(data == null)
+            try(QpidByteBuffer data = _messageDataRef.getData())
             {
-                _messageDataRef.setData(Collections.singleton(src));
-            }
-            else
-            {
-                List<QpidByteBuffer> newCollection = new ArrayList<>(data.size()+1);
-                newCollection.addAll(data);
-                newCollection.add(src);
-                _messageDataRef.setData(Collections.unmodifiableCollection(newCollection));
+                if(data == null)
+                {
+                    _messageDataRef.setData(src.slice());
+                }
+                else
+                {
+                    _messageDataRef.setData(QpidByteBuffer.concatenate(Arrays.asList(data, src)));
+                }
             }
-
         }
 
         @Override
@@ -1082,11 +997,11 @@ public abstract class AbstractBDBMessageStore implements MessageStore
         }
 
         /**
-         * returns QBBs containing the content. The caller must not dispose of them because we keep a reference in _messageDataRef.
+         * returns QBB containing the content. The caller must not dispose of them because we keep a reference in _messageDataRef.
          */
-        private Collection<QpidByteBuffer> getContentAsByteBuffer()
+        private QpidByteBuffer getContentAsByteBuffer()
         {
-            Collection<QpidByteBuffer> data = _messageDataRef == null ? Collections.<QpidByteBuffer>emptyList() : _messageDataRef.getData();
+            QpidByteBuffer data = _messageDataRef == null ? QpidByteBuffer.emptyQpidByteBuffer() : _messageDataRef.getData();
             if(data == null)
             {
                 if(stored())
@@ -1098,7 +1013,7 @@ public abstract class AbstractBDBMessageStore implements MessageStore
                 }
                 else
                 {
-                    data = Collections.emptyList();
+                    data = QpidByteBuffer.emptyQpidByteBuffer();
                 }
             }
             return data;
@@ -1106,49 +1021,9 @@ public abstract class AbstractBDBMessageStore implements MessageStore
 
 
         @Override
-        public synchronized Collection<QpidByteBuffer> getContent(int offset, int length)
+        public synchronized QpidByteBuffer getContent(int offset, int length)
         {
-            Collection<QpidByteBuffer> bufs = getContentAsByteBuffer();
-            Collection<QpidByteBuffer> content = new ArrayList<>(bufs.size());
-            int pos = 0;
-            for (QpidByteBuffer buf : bufs)
-            {
-                if(length > 0)
-                {
-                    int bufRemaining = buf.remaining();
-                    if (pos + bufRemaining <= offset)
-                    {
-                        pos += bufRemaining;
-                    }
-                    else if (pos >= offset)
-                    {
-                        buf = buf.duplicate();
-                        if (bufRemaining <= length)
-                        {
-                            length -= bufRemaining;
-                        }
-                        else
-                        {
-                            buf.limit(length);
-                            length = 0;
-                        }
-                        content.add(buf);
-                        pos += buf.remaining();
-
-                    }
-                    else
-                    {
-                        int offsetInBuf = offset - pos;
-                        int limit = length < bufRemaining - offsetInBuf ? length : bufRemaining - offsetInBuf;
-                        final QpidByteBuffer bufView = buf.view(offsetInBuf, limit);
-                        content.add(bufView);
-                        length -= limit;
-                        pos+=limit+offsetInBuf;
-                    }
-                }
-
-            }
-            return content;
+            return getContentAsByteBuffer().view(offset, length);
         }
 
         @Override
@@ -1170,7 +1045,7 @@ public abstract class AbstractBDBMessageStore implements MessageStore
                 AbstractBDBMessageStore.this.storeMetaData(txn, _messageId, _messageDataRef.getMetaData());
                 AbstractBDBMessageStore.this.addContent(txn, _messageId,
                                                         _messageDataRef.getData() == null
-                                                                ? Collections.<QpidByteBuffer>emptySet()
+                                                                ? QpidByteBuffer.emptyQpidByteBuffer()
                                                                 : _messageDataRef.getData());
                 _messageDataRef.setSoft();
             }
@@ -1219,14 +1094,12 @@ public abstract class AbstractBDBMessageStore implements MessageStore
                 metaData.dispose();
             }
 
-            Collection<QpidByteBuffer> data = _messageDataRef.getData();
-            if(data != null)
+            try (QpidByteBuffer data = _messageDataRef.getData())
             {
-                bytesCleared += getContentSize();
-                _messageDataRef.setData(null);
-                for(QpidByteBuffer buf : data)
+                if (data != null)
                 {
-                    buf.dispose();
+                    bytesCleared += getContentSize();
+                    _messageDataRef.setData(null);
                 }
             }
             _messageDataRef = null;

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuple/ByteBufferBinding.java
----------------------------------------------------------------------
diff --git a/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuple/ByteBufferBinding.java b/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuple/ByteBufferBinding.java
index d6d09dc..3b10bfc 100644
--- a/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuple/ByteBufferBinding.java
+++ b/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuple/ByteBufferBinding.java
@@ -71,15 +71,16 @@ public class ByteBufferBinding extends TupleBinding<QpidByteBuffer>
     @Override
     public void objectToEntry(QpidByteBuffer data, final TupleOutput output)
     {
-        QpidByteBuffer dup = data.duplicate();
-        byte[] copyBuf = COPY_BUFFER.get();
-        while(dup.hasRemaining())
+        try (QpidByteBuffer dup = data.duplicate())
         {
-            int length = Math.min(COPY_BUFFER_SIZE, dup.remaining());
-            dup.get(copyBuf,0,length);
-            output.write(copyBuf,0,length);
+            byte[] copyBuf = COPY_BUFFER.get();
+            while (dup.hasRemaining())
+            {
+                int length = Math.min(COPY_BUFFER_SIZE, dup.remaining());
+                dup.get(copyBuf, 0, length);
+                output.write(copyBuf, 0, length);
+            }
         }
-        dup.dispose();
     }
 
     public ByteBuffer readByteBuffer(final TupleInput input, int length)

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuple/MessageMetaDataBinding.java
----------------------------------------------------------------------
diff --git a/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuple/MessageMetaDataBinding.java b/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuple/MessageMetaDataBinding.java
index 0fd3e44..0b9fa17 100644
--- a/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuple/MessageMetaDataBinding.java
+++ b/bdbstore/src/main/java/org/apache/qpid/server/store/berkeleydb/tuple/MessageMetaDataBinding.java
@@ -23,7 +23,6 @@ package org.apache.qpid.server.store.berkeleydb.tuple;
 import java.io.ByteArrayInputStream;
 import java.io.DataInputStream;
 import java.io.IOException;
-import java.util.List;
 
 import com.sleepycat.bind.EntryBinding;
 import com.sleepycat.je.DatabaseEntry;
@@ -61,15 +60,10 @@ public class MessageMetaDataBinding implements EntryBinding<StorableMessageMetaD
             final int metaDataType = stream.readByte() & 0xff;
             MessageMetaDataType type = MessageMetaDataTypeRegistry.fromOrdinal(metaDataType);
 
-            List<QpidByteBuffer> bufs = QpidByteBuffer.asQpidByteBuffers(stream);
-
-            final StorableMessageMetaData metaData = type.createMetaData(bufs);
-
-            for (final QpidByteBuffer buf : bufs)
+            try (QpidByteBuffer buf = QpidByteBuffer.asQpidByteBuffer(stream))
             {
-                buf.dispose();
+                return type.createMetaData(buf);
             }
-            return metaData;
         }
         catch (IOException | RuntimeException e)
         {
@@ -83,12 +77,15 @@ public class MessageMetaDataBinding implements EntryBinding<StorableMessageMetaD
         final int bodySize = 1 + metaData.getStorableSize();
         byte[] underlying = new byte[4+bodySize];
         underlying[4] = (byte) metaData.getType().ordinal();
-        QpidByteBuffer buf = QpidByteBuffer.wrap(underlying);
-        buf.putInt(bodySize ^ 0x80000000);
-        buf.position(5);
-        buf = buf.slice();
-
-        metaData.writeToBuffer(buf);
+        try (QpidByteBuffer buf = QpidByteBuffer.wrap(underlying))
+        {
+            buf.putInt(bodySize ^ 0x80000000);
+            buf.position(5);
+            try (QpidByteBuffer bufSlice = buf.slice())
+            {
+                metaData.writeToBuffer(bufSlice);
+            }
+        }
         entry.setData(underlying);
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreTest.java
----------------------------------------------------------------------
diff --git a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreTest.java b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreTest.java
index da45856..91f698a 100644
--- a/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreTest.java
+++ b/bdbstore/src/test/java/org/apache/qpid/server/store/berkeleydb/BDBMessageStoreTest.java
@@ -24,36 +24,21 @@ import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
 import java.io.File;
-import java.nio.ByteBuffer;
-import java.util.Arrays;
-import java.util.Collections;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
+import org.apache.qpid.server.model.VirtualHost;
 import org.apache.qpid.server.protocol.v0_8.AMQShortString;
+import org.apache.qpid.server.protocol.v0_8.MessageMetaData;
 import org.apache.qpid.server.protocol.v0_8.transport.BasicContentHeaderProperties;
 import org.apache.qpid.server.protocol.v0_8.transport.ContentHeaderBody;
 import org.apache.qpid.server.protocol.v0_8.transport.MessagePublishInfo;
-import org.apache.qpid.server.model.VirtualHost;
-import org.apache.qpid.server.protocol.v0_10.MessageMetaDataType_0_10;
-import org.apache.qpid.server.protocol.v0_10.MessageMetaData_0_10;
-import org.apache.qpid.server.protocol.v0_8.MessageMetaData;
-import org.apache.qpid.server.protocol.v0_8.MessageMetaDataType_0_8;
 import org.apache.qpid.server.store.MessageHandle;
 import org.apache.qpid.server.store.MessageStore;
 import org.apache.qpid.server.store.MessageStoreTestCase;
-import org.apache.qpid.server.store.StorableMessageMetaData;
 import org.apache.qpid.server.store.StoreException;
 import org.apache.qpid.server.store.StoredMessage;
-import org.apache.qpid.server.virtualhost.berkeleydb.BDBVirtualHost;
-import org.apache.qpid.server.protocol.v0_10.transport.DeliveryProperties;
-import org.apache.qpid.server.protocol.v0_10.transport.Header;
-import org.apache.qpid.server.protocol.v0_10.transport.MessageAcceptMode;
-import org.apache.qpid.server.protocol.v0_10.transport.MessageAcquireMode;
-import org.apache.qpid.server.protocol.v0_10.transport.MessageDeliveryMode;
-import org.apache.qpid.server.protocol.v0_10.transport.MessageDeliveryPriority;
-import org.apache.qpid.server.protocol.v0_10.transport.MessageProperties;
-import org.apache.qpid.server.protocol.v0_10.transport.MessageTransfer;
 import org.apache.qpid.server.util.FileUtils;
+import org.apache.qpid.server.virtualhost.berkeleydb.BDBVirtualHost;
 
 /**
  * Subclass of MessageStoreTestCase which runs the standard tests from the superclass against
@@ -78,164 +63,6 @@ public class BDBMessageStoreTest extends MessageStoreTestCase
         }
     }
 
-    /**
-     * Tests that message metadata and content are successfully read back from a
-     * store after it has been reloaded. Both 0-8 and 0-10 metadata is used to
-     * verify their ability to co-exist within the store and be successful retrieved.
-     */
-    public void testBDBMessagePersistence() throws Exception
-    {
-        MessageStore bdbStore = getStore();
-
-        // Create content ByteBuffers.
-        // Split the content into 2 chunks for the 0-8 message, as per broker behaviour.
-        // Use a single chunk for the 0-10 message as per broker behaviour.
-        String bodyText = "jfhdjsflsdhfjdshfjdslhfjdslhfsjlhfsjkhfdsjkhfdsjkfhdslkjf";
-
-        QpidByteBuffer firstContentBytes_0_8 = QpidByteBuffer.wrap(bodyText.substring(0, 10).getBytes());
-        QpidByteBuffer secondContentBytes_0_8 = QpidByteBuffer.wrap(bodyText.substring(10).getBytes());
-
-        QpidByteBuffer completeContentBody_0_10 = QpidByteBuffer.wrap(bodyText.getBytes());
-        int bodySize = completeContentBody_0_10.limit();
-
-        /*
-         * Create and insert a 0-8 message (metadata and multi-chunk content)
-         */
-        MessagePublishInfo pubInfoBody_0_8 = createPublishInfoBody_0_8();
-        BasicContentHeaderProperties props_0_8 = createContentHeaderProperties_0_8();
-
-        ContentHeaderBody chb_0_8 = createContentHeaderBody_0_8(props_0_8, bodySize);
-
-        MessageMetaData messageMetaData_0_8 = new MessageMetaData(pubInfoBody_0_8, chb_0_8);
-        MessageHandle<MessageMetaData> messageHandle_0_8 = bdbStore.addMessage(messageMetaData_0_8);
-
-        long origArrivalTime_0_8 = messageMetaData_0_8.getArrivalTime();
-
-        messageHandle_0_8.addContent(firstContentBytes_0_8);
-        messageHandle_0_8.addContent(secondContentBytes_0_8);
-        final StoredMessage<MessageMetaData> storedMessage_0_8 = messageHandle_0_8.allContentAdded();
-        long messageid_0_8 = storedMessage_0_8.getMessageNumber();
-        ((AbstractBDBMessageStore.StoredBDBMessage)messageHandle_0_8).flushToStore();
-
-        /*
-         * Create and insert a 0-10 message (metadata and content)
-         */
-        MessageProperties msgProps_0_10 = createMessageProperties_0_10(bodySize);
-        DeliveryProperties delProps_0_10 = createDeliveryProperties_0_10();
-        Header header_0_10 = new Header(delProps_0_10, msgProps_0_10);
-
-        MessageTransfer xfr_0_10 = new MessageTransfer("destination", MessageAcceptMode.EXPLICIT,
-                                                       MessageAcquireMode.PRE_ACQUIRED, header_0_10,
-                                                       Collections.singletonList(completeContentBody_0_10));
-
-        MessageMetaData_0_10 messageMetaData_0_10 = new MessageMetaData_0_10(xfr_0_10);
-        MessageHandle<MessageMetaData_0_10> messageHandle_0_10 = bdbStore.addMessage(messageMetaData_0_10);
-
-        long origArrivalTime_0_10 = messageMetaData_0_10.getArrivalTime();
-
-        messageHandle_0_10.addContent(completeContentBody_0_10);
-        final StoredMessage<MessageMetaData_0_10> storedMessage_0_10 = messageHandle_0_10.allContentAdded();
-        long messageid_0_10 = storedMessage_0_10.getMessageNumber();
-        ((AbstractBDBMessageStore.StoredBDBMessage)messageHandle_0_10).flushToStore();
-
-        /*
-         * reload the store only (read-only)
-         */
-        reopenStore();
-
-        /*
-         * Read back and validate the 0-8 message metadata and content
-         */
-        BDBMessageStore reopenedBdbStore = (BDBMessageStore) getStore();
-        StorableMessageMetaData storeableMMD_0_8 = reopenedBdbStore.getMessageMetaData(messageid_0_8);
-
-        assertEquals("Unexpected message type", MessageMetaDataType_0_8.TYPE, storeableMMD_0_8.getType().ordinal());
-        assertTrue("Unexpected instance type", storeableMMD_0_8 instanceof MessageMetaData);
-        MessageMetaData returnedMMD_0_8 = (MessageMetaData) storeableMMD_0_8;
-
-        assertEquals("Message arrival time has changed", origArrivalTime_0_8, returnedMMD_0_8.getArrivalTime());
-
-        MessagePublishInfo returnedPubBody_0_8 = returnedMMD_0_8.getMessagePublishInfo();
-        assertEquals("Message exchange has changed", pubInfoBody_0_8.getExchange(), returnedPubBody_0_8.getExchange());
-        assertEquals("Immediate flag has changed", pubInfoBody_0_8.isImmediate(), returnedPubBody_0_8.isImmediate());
-        assertEquals("Mandatory flag has changed", pubInfoBody_0_8.isMandatory(), returnedPubBody_0_8.isMandatory());
-        assertEquals("Routing key has changed", pubInfoBody_0_8.getRoutingKey(), returnedPubBody_0_8.getRoutingKey());
-
-        ContentHeaderBody returnedHeaderBody_0_8 = returnedMMD_0_8.getContentHeaderBody();
-        assertEquals("ContentHeader ClassID has changed", chb_0_8.getClassId(), returnedHeaderBody_0_8.getClassId());
-        assertEquals("ContentHeader weight has changed", chb_0_8.getWeight(), returnedHeaderBody_0_8.getWeight());
-        assertEquals("ContentHeader bodySize has changed", chb_0_8.getBodySize(), returnedHeaderBody_0_8.getBodySize());
-
-        BasicContentHeaderProperties returnedProperties_0_8 =   returnedHeaderBody_0_8.getProperties();
-        assertEquals("Property ContentType has changed", props_0_8.getContentTypeAsString(), returnedProperties_0_8.getContentTypeAsString());
-        assertEquals("Property MessageID has changed", props_0_8.getMessageIdAsString(), returnedProperties_0_8.getMessageIdAsString());
-
-        ByteBuffer recoveredContent_0_8 = ByteBuffer.allocate((int) chb_0_8.getBodySize()) ;
-        long recoveredCount_0_8 = reopenedBdbStore.getContent(messageid_0_8, 0, recoveredContent_0_8);
-        assertEquals("Incorrect amount of payload data recovered", chb_0_8.getBodySize(), recoveredCount_0_8);
-        String returnedPayloadString_0_8 = new String(recoveredContent_0_8.array());
-        assertEquals("Message Payload has changed", bodyText, returnedPayloadString_0_8);
-
-        /*
-         * Read back and validate the 0-10 message metadata and content
-         */
-        StorableMessageMetaData storeableMMD_0_10 = reopenedBdbStore.getMessageMetaData(messageid_0_10);
-
-        assertEquals("Unexpected message type", MessageMetaDataType_0_10.TYPE, storeableMMD_0_10.getType().ordinal());
-        assertTrue("Unexpected instance type", storeableMMD_0_10 instanceof MessageMetaData_0_10);
-        MessageMetaData_0_10 returnedMMD_0_10 = (MessageMetaData_0_10) storeableMMD_0_10;
-
-        assertEquals("Message arrival time has changed", origArrivalTime_0_10, returnedMMD_0_10.getArrivalTime());
-
-        DeliveryProperties returnedDelProps_0_10 = returnedMMD_0_10.getHeader().getDeliveryProperties();
-        assertNotNull("DeliveryProperties were not returned", returnedDelProps_0_10);
-        assertEquals("Immediate flag has changed", delProps_0_10.getImmediate(), returnedDelProps_0_10.getImmediate());
-        assertEquals("Routing key has changed", delProps_0_10.getRoutingKey(), returnedDelProps_0_10.getRoutingKey());
-        assertEquals("Message exchange has changed", delProps_0_10.getExchange(), returnedDelProps_0_10.getExchange());
-        assertEquals("Message expiration has changed", delProps_0_10.getExpiration(), returnedDelProps_0_10.getExpiration());
-        assertEquals("Message delivery priority has changed", delProps_0_10.getPriority(), returnedDelProps_0_10.getPriority());
-
-        MessageProperties returnedMsgProps = returnedMMD_0_10.getHeader().getMessageProperties();
-        assertNotNull("MessageProperties were not returned", returnedMsgProps);
-        assertTrue("Message correlationID has changed", Arrays.equals(msgProps_0_10.getCorrelationId(), returnedMsgProps.getCorrelationId()));
-        assertEquals("Message content length has changed", msgProps_0_10.getContentLength(), returnedMsgProps.getContentLength());
-        assertEquals("Message content type has changed", msgProps_0_10.getContentType(), returnedMsgProps.getContentType());
-
-        ByteBuffer recoveredContent = ByteBuffer.allocate((int) msgProps_0_10.getContentLength()) ;
-        long recoveredCount = reopenedBdbStore.getContent(messageid_0_10, 0, recoveredContent);
-        assertEquals("Incorrect amount of payload data recovered", msgProps_0_10.getContentLength(), recoveredCount);
-
-        String returnedPayloadString_0_10 = new String(recoveredContent.array());
-        assertEquals("Message Payload has changed", bodyText, returnedPayloadString_0_10);
-
-        reopenedBdbStore.closeMessageStore();
-    }
-
-    private DeliveryProperties createDeliveryProperties_0_10()
-    {
-        DeliveryProperties delProps_0_10 = new DeliveryProperties();
-
-        delProps_0_10.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
-        delProps_0_10.setImmediate(true);
-        delProps_0_10.setExchange("exchange12345");
-        delProps_0_10.setRoutingKey("routingKey12345");
-        delProps_0_10.setExpiration(5);
-        delProps_0_10.setPriority(MessageDeliveryPriority.ABOVE_AVERAGE);
-
-        return delProps_0_10;
-    }
-
-    private MessageProperties createMessageProperties_0_10(int bodySize)
-    {
-        MessageProperties msgProps_0_10 = new MessageProperties();
-        msgProps_0_10.setContentLength(bodySize);
-        msgProps_0_10.setCorrelationId("qwerty".getBytes());
-        msgProps_0_10.setContentType("text/html");
-
-        return msgProps_0_10;
-    }
-
-
     private MessagePublishInfo createPublishInfoBody_0_8()
     {
         return new MessagePublishInfo(new AMQShortString("exchange12345"), false, true,
@@ -257,60 +84,6 @@ public class BDBMessageStoreTest extends MessageStoreTestCase
         return props;
     }
 
-    public void testGetContentWithOffset() throws Exception
-    {
-        BDBMessageStore bdbStore = (BDBMessageStore) getStore();
-        StoredMessage<MessageMetaData> storedMessage_0_8 = createAndStoreSingleChunkMessage_0_8(bdbStore);
-        long messageid_0_8 = storedMessage_0_8.getMessageNumber();
-
-        // normal case: offset is 0
-        ByteBuffer dst = ByteBuffer.allocate(10);
-        int length = bdbStore.getContent(messageid_0_8, 0, dst);
-        assertEquals("Unexpected length", CONTENT_BYTES.length, length);
-        byte[] array = dst.array();
-        assertTrue("Unexpected content", Arrays.equals(CONTENT_BYTES, array));
-
-        // offset is in the middle
-        dst = ByteBuffer.allocate(10);
-        length = bdbStore.getContent(messageid_0_8, 5, dst);
-        assertEquals("Unexpected length", 5, length);
-        array = dst.array();
-        byte[] expected = new byte[10];
-        System.arraycopy(CONTENT_BYTES, 5, expected, 0, 5);
-        assertTrue("Unexpected content", Arrays.equals(expected, array));
-
-        // offset beyond the content length
-        dst = ByteBuffer.allocate(10);
-        try
-        {
-            bdbStore.getContent(messageid_0_8, 15, dst);
-            fail("Should fail for the offset greater than message size");
-        }
-        catch (RuntimeException e)
-        {
-            assertEquals("Unexpected exception message", "Offset 15 is greater than message size 10 for message id "
-                    + messageid_0_8 + "!", e.getCause().getMessage());
-        }
-
-        // buffer is smaller then message size
-        dst = ByteBuffer.allocate(5);
-        length = bdbStore.getContent(messageid_0_8, 0, dst);
-        assertEquals("Unexpected length", 5, length);
-        array = dst.array();
-        expected = new byte[5];
-        System.arraycopy(CONTENT_BYTES, 0, expected, 0, 5);
-        assertTrue("Unexpected content", Arrays.equals(expected, array));
-
-        // buffer is smaller then message size, offset is not 0
-        dst = ByteBuffer.allocate(5);
-        length = bdbStore.getContent(messageid_0_8, 2, dst);
-        assertEquals("Unexpected length", 5, length);
-        array = dst.array();
-        expected = new byte[5];
-        System.arraycopy(CONTENT_BYTES, 2, expected, 0, 5);
-        assertTrue("Unexpected content", Arrays.equals(expected, array));
-    }
-
     /**
      * Tests that messages which are added to the store and then removed using the
      * public MessageStore interfaces are actually removed from the store by then
@@ -338,11 +111,15 @@ public class BDBMessageStoreTest extends MessageStoreTestCase
             // pass since exception expected
         }
 
-        //expecting no content, allocate a 1 byte
-        ByteBuffer dst = ByteBuffer.allocate(1);
-
-        assertEquals("Retrieved content when none was expected",
-                        0, bdbStore.getContent(messageid_0_8, 0, dst));
+        try
+        {
+            bdbStore.getAllContent(messageid_0_8);
+            fail("Expected exception not thrown");
+        }
+        catch (StoreException se)
+        {
+            // PASS
+        }
     }
 
     private StoredMessage<MessageMetaData> createAndStoreSingleChunkMessage_0_8(MessageStore store)

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/NonPooledByteBufferRef.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/NonPooledByteBufferRef.java b/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/NonPooledByteBufferRef.java
index 2d0d668..27ad899 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/NonPooledByteBufferRef.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/NonPooledByteBufferRef.java
@@ -28,6 +28,10 @@ class NonPooledByteBufferRef implements ByteBufferRef
 
     NonPooledByteBufferRef(final ByteBuffer buffer)
     {
+        if (buffer == null)
+        {
+            throw new NullPointerException();
+        }
         _buffer = buffer;
     }
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/PooledByteBufferRef.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/PooledByteBufferRef.java b/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/PooledByteBufferRef.java
index 01ad373..0126e20 100644
--- a/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/PooledByteBufferRef.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/bytebuffer/PooledByteBufferRef.java
@@ -21,6 +21,8 @@
 package org.apache.qpid.server.bytebuffer;
 
 import java.nio.ByteBuffer;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
 import java.util.concurrent.atomic.AtomicLong;
@@ -43,6 +45,10 @@ class PooledByteBufferRef implements ByteBufferRef
 
     PooledByteBufferRef(final ByteBuffer buffer)
     {
+        if (buffer == null)
+        {
+            throw new NullPointerException();
+        }
         _buffer = buffer;
         ACTIVE_BUFFERS.incrementAndGet();
     }


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[02/10] qpid-broker-j git commit: QPID-7832: [Java Broker] Refactor store/protocol API using Collection

Posted by lq...@apache.org.
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_8_to_0_10.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_8_to_0_10.java b/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_8_to_0_10.java
index 9a48b84..6d9c190 100644
--- a/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_8_to_0_10.java
+++ b/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/MessageConverter_0_8_to_0_10.java
@@ -23,28 +23,26 @@ package org.apache.qpid.server.protocol.converter.v0_8_v0_10;
 import static java.nio.charset.StandardCharsets.UTF_8;
 
 import java.net.URISyntaxException;
-import java.util.Collection;
 import java.util.Map;
 import java.util.UUID;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.protocol.converter.MessageConversionException;
-import org.apache.qpid.server.protocol.v0_10.transport.MessageDeliveryMode;
-import org.apache.qpid.server.protocol.v0_8.AMQShortString;
-import org.apache.qpid.server.protocol.v0_8.transport.BasicContentHeaderProperties;
-import org.apache.qpid.server.protocol.v0_8.FieldTable;
 import org.apache.qpid.server.model.NamedAddressSpace;
 import org.apache.qpid.server.plugin.MessageConverter;
 import org.apache.qpid.server.plugin.PluggableService;
 import org.apache.qpid.server.protocol.v0_10.MessageMetaData_0_10;
 import org.apache.qpid.server.protocol.v0_10.MessageTransferMessage;
-import org.apache.qpid.server.protocol.v0_8.AMQMessage;
-import org.apache.qpid.server.store.StoredMessage;
 import org.apache.qpid.server.protocol.v0_10.transport.DeliveryProperties;
 import org.apache.qpid.server.protocol.v0_10.transport.Header;
+import org.apache.qpid.server.protocol.v0_10.transport.MessageDeliveryMode;
 import org.apache.qpid.server.protocol.v0_10.transport.MessageDeliveryPriority;
 import org.apache.qpid.server.protocol.v0_10.transport.MessageProperties;
 import org.apache.qpid.server.protocol.v0_10.transport.ReplyTo;
+import org.apache.qpid.server.protocol.v0_8.AMQMessage;
+import org.apache.qpid.server.protocol.v0_8.AMQShortString;
+import org.apache.qpid.server.protocol.v0_8.FieldTable;
+import org.apache.qpid.server.protocol.v0_8.transport.BasicContentHeaderProperties;
+import org.apache.qpid.server.store.StoredMessage;
 import org.apache.qpid.server.url.AMQBindingURL;
 
 @PluggableService
@@ -93,7 +91,7 @@ public class MessageConverter_0_8_to_0_10  implements MessageConverter<AMQMessag
             }
 
             @Override
-            public Collection<QpidByteBuffer> getContent(final int offset, final int length)
+            public QpidByteBuffer getContent(final int offset, final int length)
             {
                 return message_0_8.getContent(offset, length);
             }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/PropertyConverter_0_10_to_0_8Test.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/PropertyConverter_0_10_to_0_8Test.java b/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/PropertyConverter_0_10_to_0_8Test.java
index e46d732..645d102 100644
--- a/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/PropertyConverter_0_10_to_0_8Test.java
+++ b/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/PropertyConverter_0_10_to_0_8Test.java
@@ -578,8 +578,12 @@ public class PropertyConverter_0_10_to_0_8Test extends QpidTestCase
         if (content != null)
         {
             when(storedMessage.getContentSize()).thenReturn(content.length);
-            when(storedMessage.getContent(0, content.length)).thenReturn(Collections.singleton(QpidByteBuffer.wrap(
-                    content)));
+            when(storedMessage.getContent(0, content.length)).thenReturn(QpidByteBuffer.wrap(content));
+        }
+        else
+        {
+            when(storedMessage.getContentSize()).thenReturn(0);
+            when(storedMessage.getContent(0, 0)).thenReturn(QpidByteBuffer.emptyQpidByteBuffer());
         }
         return new MessageTransferMessage(storedMessage, null);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/PropertyConverter_0_8_to_0_10Test.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/PropertyConverter_0_8_to_0_10Test.java b/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/PropertyConverter_0_8_to_0_10Test.java
index 8bb4a47..76bc200 100644
--- a/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/PropertyConverter_0_8_to_0_10Test.java
+++ b/broker-plugins/amqp-msg-conv-0-8-to-0-10/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v0_10/PropertyConverter_0_8_to_0_10Test.java
@@ -24,7 +24,6 @@ import static java.nio.charset.StandardCharsets.UTF_8;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
-import java.util.Collections;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.UUID;
@@ -472,8 +471,12 @@ public class PropertyConverter_0_8_to_0_10Test extends QpidTestCase
         if (content != null)
         {
             when(storedMessage.getContentSize()).thenReturn(content.length);
-            when(storedMessage.getContent(0, content.length)).thenReturn(Collections.singleton(QpidByteBuffer.wrap(
-                    content)));
+            when(storedMessage.getContent(0, content.length)).thenReturn(QpidByteBuffer.wrap(content));
+        }
+        else
+        {
+            when(storedMessage.getContentSize()).thenReturn(0);
+            when(storedMessage.getContent(0, 0)).thenReturn(QpidByteBuffer.emptyQpidByteBuffer());
         }
 
         return new AMQMessage(storedMessage);

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_1_0_to_v0_8.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_1_0_to_v0_8.java b/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_1_0_to_v0_8.java
index dcdd430..e8a02fd 100644
--- a/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_1_0_to_v0_8.java
+++ b/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/main/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_1_0_to_v0_8.java
@@ -32,8 +32,6 @@ import static org.apache.qpid.server.protocol.v1_0.MessageConverter_from_1_0.get
 import static org.apache.qpid.server.protocol.v1_0.MessageConverter_from_1_0.getTtl;
 import static org.apache.qpid.server.protocol.v1_0.MessageConverter_from_1_0.getUserId;
 
-import java.util.Collection;
-import java.util.Collections;
 import java.util.Date;
 import java.util.LinkedHashMap;
 import java.util.Map;
@@ -117,9 +115,9 @@ public class MessageConverter_1_0_to_v0_8 implements MessageConverter<Message_1_
             }
 
             @Override
-            public Collection<QpidByteBuffer> getContent(final int offset, final int length)
+            public QpidByteBuffer getContent(final int offset, final int length)
             {
-                return Collections.singleton(QpidByteBuffer.wrap(convertedContent, offset, length));
+                return QpidByteBuffer.wrap(convertedContent, offset, length);
             }
 
             @Override

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_0_8_to_1_0Test.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_0_8_to_1_0Test.java b/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_0_8_to_1_0Test.java
index df1a786..4fa5734 100644
--- a/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_0_8_to_1_0Test.java
+++ b/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_0_8_to_1_0Test.java
@@ -30,8 +30,6 @@ import java.io.ByteArrayOutputStream;
 import java.io.ObjectOutputStream;
 import java.io.Serializable;
 import java.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
@@ -39,8 +37,6 @@ import java.util.UUID;
 
 import com.google.common.collect.Lists;
 import org.mockito.ArgumentCaptor;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.AMQMessageHeader;
@@ -340,12 +336,12 @@ public class MessageConverter_0_8_to_1_0Test extends QpidTestCase
         return expected;
     }
 
-    private List<EncodingRetainingSection<?>> getEncodingRetainingSections(final Collection<QpidByteBuffer> content,
+    private List<EncodingRetainingSection<?>> getEncodingRetainingSections(final QpidByteBuffer content,
                                                                            final int expectedNumberOfSections)
             throws Exception
     {
         SectionDecoder sectionDecoder = new SectionDecoderImpl(_typeRegistry.getSectionDecoderRegistry());
-        final List<EncodingRetainingSection<?>> sections = sectionDecoder.parseAll(new ArrayList<>(content));
+        final List<EncodingRetainingSection<?>> sections = sectionDecoder.parseAll(content);
         assertEquals("Unexpected number of sections", expectedNumberOfSections, sections.size());
         return sections;
     }
@@ -376,15 +372,8 @@ public class MessageConverter_0_8_to_1_0Test extends QpidTestCase
         final ArgumentCaptor<Integer> sizeCaptor = ArgumentCaptor.forClass(Integer.class);
 
         when(_handle.getContent(offsetCaptor.capture(),
-                                sizeCaptor.capture())).then(new Answer<Collection<QpidByteBuffer>>()
-        {
-            @Override
-            public Collection<QpidByteBuffer> answer(final InvocationOnMock invocation) throws Throwable
-            {
-                final QpidByteBuffer view = combined.view(offsetCaptor.getValue(), sizeCaptor.getValue());
-                return Collections.singleton(view);
-            }
-        });
+                                sizeCaptor.capture())).then(invocation -> combined.view(offsetCaptor.getValue(),
+                                                                                        sizeCaptor.getValue()));
     }
 
     private Byte getJmsMessageTypeAnnotation(final Message_1_0 convertedMessage)
@@ -466,7 +455,7 @@ public class MessageConverter_0_8_to_1_0Test extends QpidTestCase
     {
         final AMQMessage sourceMessage = getAmqMessage(messageBytes, mimeType);
         final Message_1_0 convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         List<EncodingRetainingSection<?>> sections = getEncodingRetainingSections(content, 1);
         EncodingRetainingSection<?> encodingRetainingSection = sections.get(0);

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_1_0_to_v0_8Test.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_1_0_to_v0_8Test.java b/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_1_0_to_v0_8Test.java
index c9d17cc..cc2ada2 100644
--- a/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_1_0_to_v0_8Test.java
+++ b/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/MessageConverter_1_0_to_v0_8Test.java
@@ -27,9 +27,9 @@ import static org.mockito.Mockito.when;
 
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.io.ObjectOutputStream;
 import java.util.ArrayList;
-import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.LinkedHashMap;
@@ -67,7 +67,6 @@ import org.apache.qpid.server.typedmessage.mimecontentconverter.JmsMapMessageToM
 import org.apache.qpid.server.typedmessage.mimecontentconverter.JmsStreamMessageToList;
 import org.apache.qpid.server.typedmessage.mimecontentconverter.ListToJmsStreamMessage;
 import org.apache.qpid.server.typedmessage.mimecontentconverter.MapToJmsMapMessage;
-import org.apache.qpid.server.util.ByteBufferUtils;
 import org.apache.qpid.test.utils.QpidTestCase;
 
 public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
@@ -127,7 +126,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
 
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         assertEquals("Unexpected mime type",
                      "application/java-object-stream",
@@ -143,7 +142,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
 
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType());
         assertArrayEquals("Unexpected content size",
@@ -235,7 +234,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
 
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType());
 
@@ -265,7 +264,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "text/plain", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertEquals("Unexpected content", expected, new String(getBytes(content), UTF_8));
     }
 
@@ -279,7 +278,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "text/plain", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertEquals("Unexpected content", expected, new String(getBytes(content), UTF_8));
     }
 
@@ -295,7 +294,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         Map<String, Object> convertedMap = new JmsMapMessageToMap().toObject(getBytes(content));
         assertEquals("Unexpected size", originalMap.size(), convertedMap.size());
@@ -316,7 +315,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "amqp/map", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         Map<String, Object> convertedMap = new AmqpMapToMapConverter().toObject(getBytes(content));
         assertEquals("Unexpected size", originalMap.size(), convertedMap.size());
@@ -352,7 +351,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "jms/stream-message", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         List<Object> convertedList = new JmsStreamMessageToList().toObject(getBytes(content));
         assertEquals("Unexpected size", originalList.size(), convertedList.size());
@@ -371,7 +370,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "amqp/list", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         List<Object> convertedList = new AmqpListToListConverter().toObject(getBytes(content));
         assertEquals("Unexpected size", originalList.size(), convertedList.size());
@@ -424,7 +423,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "jms/stream-message", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertEquals("Unexpected content", expected, new JmsStreamMessageToList().toObject(getBytes(content)));
     }
 
@@ -437,7 +436,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "amqp/list", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         List<Object> convertedList = new AmqpListToListConverter().toObject(getBytes(content));
         assertEquals("Unexpected size", originalList.size(), convertedList.size());
@@ -497,7 +496,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
 
         assertEquals("Unexpected mime type",
                      expectedMimeType, convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", data, getBytes(content));
     }
 
@@ -517,7 +516,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
 
         assertEquals("Unexpected mime type",
                      expectedMimeType, convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", data, getBytes(content));
     }
 
@@ -550,7 +549,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
 
         assertEquals("Unexpected mime type",
                      expectedMimeType, convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", data, getBytes(content));
     }
 
@@ -570,7 +569,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
 
         assertEquals("Unexpected mime type",
                      expectedMimeType, convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", data, getBytes(content));
     }
 
@@ -640,7 +639,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "amqp/map", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", bytes, getBytes(content));
     }
 
@@ -657,7 +656,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", bytes, getBytes(content));
     }
 
@@ -674,7 +673,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "amqp/list", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", bytes, getBytes(content));
     }
 
@@ -691,7 +690,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
         assertEquals("Unexpected mime type", "jms/stream-message", convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", bytes, getBytes(content));
     }
 
@@ -708,7 +707,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
         assertEquals("Unexpected mime type",
                      "application/java-object-stream",
                      convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", expected, getBytes(content));
     }
 
@@ -726,7 +725,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
         assertEquals("Unexpected mime type",
                      "application/java-object-stream",
                      convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", expected, getBytes(content));
     }
 
@@ -743,7 +742,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
         assertEquals("Unexpected mime type",
                      "application/octet-stream",
                      convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", expected, getBytes(content));
     }
 
@@ -758,7 +757,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
         assertEquals("Unexpected mime type",
                      "application/octet-stream",
                      convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertArrayEquals("Unexpected content", expected, getBytes(content));
     }
 
@@ -778,7 +777,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
 
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         assertEquals("Unexpected mime type",
                      "application/java-object-stream",
@@ -792,7 +791,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
 
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType());
         assertArrayEquals("Unexpected content size",
@@ -891,7 +890,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
 
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
 
         assertEquals("Unexpected mime type", "jms/map-message", convertedMessage.getMessageHeader().getMimeType());
 
@@ -926,21 +925,21 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
 
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
 
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
         assertEquals("Unexpected content", expected, new String(getBytes(content), UTF_8));
 
         assertEquals("Unexpected mime type", "text/plain", convertedMessage.getMessageHeader().getMimeType());
     }
 
-    private byte[] getBytes(final Collection<QpidByteBuffer> content) throws Exception
+    private byte[] getBytes(final QpidByteBuffer content) throws Exception
     {
-        ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        for (QpidByteBuffer buf : content)
+        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
+             InputStream contentInputStream = content.asInputStream())
         {
-            ByteStreams.copy(buf.asInputStream(), bos);
-            buf.dispose();
+            ByteStreams.copy(contentInputStream, bos);
+            content.dispose();
+            return bos.toByteArray();
         }
-        return bos.toByteArray();
     }
 
     private Message_1_0 createTestMessage(final EncodingRetainingSection encodingRetainingSection)
@@ -1005,19 +1004,19 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
 
         if (section != null)
         {
-            final QpidByteBuffer combined = QpidByteBuffer.wrap(ByteBufferUtils.combine(section.getEncodedForm()));
+            // TODO this seems to leak QBBs
+            final QpidByteBuffer combined = section.getEncodedForm();
             when(storedMessage.getContentSize()).thenReturn((int) section.getEncodedSize());
             final ArgumentCaptor<Integer> offsetCaptor = ArgumentCaptor.forClass(Integer.class);
             final ArgumentCaptor<Integer> sizeCaptor = ArgumentCaptor.forClass(Integer.class);
 
             when(storedMessage.getContent(offsetCaptor.capture(),
-                                          sizeCaptor.capture())).then(invocation ->
-                                                                      {
-                                                                          final QpidByteBuffer view = combined.view(
-                                                                                  offsetCaptor.getValue(),
-                                                                                  sizeCaptor.getValue());
-                                                                          return Collections.singleton(view);
-                                                                      });
+                                          sizeCaptor.capture())).then(invocation -> combined.view(offsetCaptor.getValue(),
+                                                                                                  sizeCaptor.getValue()));
+        }
+        else
+        {
+            when(storedMessage.getContent(0,0)).thenReturn(QpidByteBuffer.emptyQpidByteBuffer());
         }
         return new Message_1_0(storedMessage);
     }
@@ -1045,7 +1044,7 @@ public class MessageConverter_1_0_to_v0_8Test extends QpidTestCase
 
         assertEquals("Unexpected mime type",
                      expectedMimeType, convertedMessage.getMessageHeader().getMimeType());
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent();
         assertArrayEquals("Unexpected content", data, getBytes(content));
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/PropertyConverter_0_8_to_1_0Test.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/PropertyConverter_0_8_to_1_0Test.java b/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/PropertyConverter_0_8_to_1_0Test.java
index 0520baf..f9443e0 100644
--- a/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/PropertyConverter_0_8_to_1_0Test.java
+++ b/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/PropertyConverter_0_8_to_1_0Test.java
@@ -472,8 +472,12 @@ public class PropertyConverter_0_8_to_1_0Test extends QpidTestCase
         if (content != null)
         {
             when(storedMessage.getContentSize()).thenReturn(content.length);
-            when(storedMessage.getContent(0, content.length)).thenReturn(Collections.singleton(QpidByteBuffer.wrap(
-                    content)));
+            when(storedMessage.getContent(0, content.length)).thenReturn(QpidByteBuffer.wrap(content));
+        }
+        else
+        {
+            when(storedMessage.getContentSize()).thenReturn(0);
+            when(storedMessage.getContent(0, 0)).thenReturn(QpidByteBuffer.emptyQpidByteBuffer());
         }
 
         return new AMQMessage(storedMessage);

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/PropertyConverter_1_0_to_0_8Test.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/PropertyConverter_1_0_to_0_8Test.java b/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/PropertyConverter_1_0_to_0_8Test.java
index 059e268..6f7e75c 100644
--- a/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/PropertyConverter_1_0_to_0_8Test.java
+++ b/broker-plugins/amqp-msg-conv-0-8-to-1-0/src/test/java/org/apache/qpid/server/protocol/converter/v0_8_v1_0/PropertyConverter_1_0_to_0_8Test.java
@@ -33,13 +33,12 @@ import java.util.HashMap;
 import java.util.Map;
 import java.util.UUID;
 
+import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.exchange.ExchangeDefaults;
 import org.apache.qpid.server.model.Exchange;
 import org.apache.qpid.server.model.NamedAddressSpace;
 import org.apache.qpid.server.model.Queue;
 import org.apache.qpid.server.protocol.converter.MessageConversionException;
-import org.apache.qpid.server.protocol.v0_10.MessageTransferMessage;
-import org.apache.qpid.server.protocol.v0_10.transport.ReplyTo;
 import org.apache.qpid.server.protocol.v0_8.AMQMessage;
 import org.apache.qpid.server.protocol.v0_8.AMQShortString;
 import org.apache.qpid.server.protocol.v0_8.FieldTable;
@@ -922,6 +921,8 @@ public class PropertyConverter_1_0_to_0_8Test extends QpidTestCase
                                           final long arrivalTime)
     {
         final StoredMessage<MessageMetaData_1_0> storedMessage = mock(StoredMessage.class);
+        when(storedMessage.getContentSize()).thenReturn(0);
+        when(storedMessage.getContent(0, 0)).thenReturn(QpidByteBuffer.emptyQpidByteBuffer());
         MessageMetaData_1_0 metaData = new MessageMetaData_1_0(header.createEncodingRetainingSection(),
                                                                deliveryAnnotations.createEncodingRetainingSection(),
                                                                messageAnnotations.createEncodingRetainingSection(),

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/AbstractDerbyMessageStore.java
----------------------------------------------------------------------
diff --git a/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/AbstractDerbyMessageStore.java b/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/AbstractDerbyMessageStore.java
index e417f9a..d5a4de6 100644
--- a/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/AbstractDerbyMessageStore.java
+++ b/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/AbstractDerbyMessageStore.java
@@ -21,6 +21,7 @@
 package org.apache.qpid.server.store.derby;
 
 
+import java.io.InputStream;
 import java.sql.CallableStatement;
 import java.sql.Connection;
 import java.sql.PreparedStatement;
@@ -137,9 +138,9 @@ public abstract class AbstractDerbyMessageStore extends AbstractJDBCMessageStore
     }
 
     @Override
-    protected byte[] getBlobAsBytes(ResultSet rs, int col) throws SQLException
+    protected InputStream getBlobAsInputStream(ResultSet rs, int col) throws SQLException
     {
-        return DerbyUtils.getBlobAsBytes(rs, col);
+        return DerbyUtils.getBlobAsInputStream(rs, col);
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyUtils.java
----------------------------------------------------------------------
diff --git a/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyUtils.java b/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyUtils.java
index 9af478d..62c9889 100644
--- a/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyUtils.java
+++ b/broker-plugins/derby-store/src/main/java/org/apache/qpid/server/store/derby/DerbyUtils.java
@@ -23,6 +23,7 @@ package org.apache.qpid.server.store.derby;
 
 import java.io.File;
 import java.io.IOException;
+import java.io.InputStream;
 import java.io.Writer;
 import java.nio.charset.StandardCharsets;
 import java.sql.Blob;
@@ -151,10 +152,10 @@ public class DerbyUtils
         return new String(bytes, StandardCharsets.UTF_8);
     }
 
-    protected static byte[] getBlobAsBytes(ResultSet rs, int col) throws SQLException
+    protected static InputStream getBlobAsInputStream(ResultSet rs, int col) throws SQLException
     {
         Blob dataAsBlob = rs.getBlob(col);
-        return dataAsBlob.getBytes(1,(int) dataAsBlob.length());
+        return dataAsBlob.getBinaryStream();
     }
 
     public static boolean tableExists(final String tableName, final Connection conn) throws SQLException

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/AbstractJDBCMessageStore.java
----------------------------------------------------------------------
diff --git a/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/AbstractJDBCMessageStore.java b/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/AbstractJDBCMessageStore.java
index 099029c..9c6cfa9 100644
--- a/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/AbstractJDBCMessageStore.java
+++ b/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/AbstractJDBCMessageStore.java
@@ -23,7 +23,6 @@ package org.apache.qpid.server.store.jdbc;
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.InputStream;
-import java.nio.ByteBuffer;
 import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.ResultSet;
@@ -31,7 +30,6 @@ import java.sql.SQLException;
 import java.sql.Statement;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
 import java.util.Set;
@@ -831,11 +829,14 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
             final int bodySize = 1 + metaData.getStorableSize();
             byte[] underlying = new byte[bodySize];
             underlying[0] = (byte) metaData.getType().ordinal();
-            QpidByteBuffer buf = QpidByteBuffer.wrap(underlying);
-            buf.position(1);
-            buf = buf.slice();
-
-            metaData.writeToBuffer(buf);
+            try (QpidByteBuffer buf = QpidByteBuffer.wrap(underlying))
+            {
+                buf.position(1);
+                try (QpidByteBuffer bufSlice = buf.slice())
+                {
+                    metaData.writeToBuffer(buf);
+                }
+            }
             try(ByteArrayInputStream bis = new ByteArrayInputStream(underlying))
             {
                 stmt.setBinaryStream(2, bis, underlying.length);
@@ -938,7 +939,14 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
 
                     if (rs.next())
                     {
-                        return getStorableMessageMetaData(messageId, getBlobAsBytes(rs, 1));
+                        try (InputStream blobAsInputStream = getBlobAsInputStream(rs, 1))
+                        {
+                            return getStorableMessageMetaData(messageId, blobAsInputStream);
+                        }
+                        catch (IOException e)
+                        {
+                            throw new StoreException("Error reading meta data from the store for message with id " + messageId, e);
+                        }
                     }
                     else
                     {
@@ -949,20 +957,18 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
         }
     }
 
-    private StorableMessageMetaData getStorableMessageMetaData(final long messageId, final byte[] blobAsBytes)
+    private StorableMessageMetaData getStorableMessageMetaData(final long messageId, final InputStream stream)
             throws SQLException
     {
-        try(InputStream stream = new ByteArrayInputStream(blobAsBytes))
+        try
         {
             int typeOrdinal = stream.read() & 0xff;
             MessageMetaDataType type = MessageMetaDataTypeRegistry.fromOrdinal(typeOrdinal);
-            List<QpidByteBuffer> bufs = QpidByteBuffer.asQpidByteBuffers(stream);
-            StorableMessageMetaData metaData = type.createMetaData(bufs);
-            for (final QpidByteBuffer buf : bufs)
+
+            try (QpidByteBuffer buf = QpidByteBuffer.asQpidByteBuffer(stream))
             {
-                buf.dispose();
+                return type.createMetaData(buf);
             }
-            return metaData;
         }
         catch (IOException | RuntimeException e)
         {
@@ -970,41 +976,30 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
         }
     }
 
-    protected abstract byte[] getBlobAsBytes(ResultSet rs, int col) throws SQLException;
+    protected abstract InputStream getBlobAsInputStream(ResultSet rs, int col) throws SQLException;
 
     private void addContent(final Connection conn, long messageId,
-                            Collection<QpidByteBuffer> contentBody)
+                            QpidByteBuffer contentBody)
     {
         getLogger().debug("Adding content for message {}", messageId);
 
-        int size = 0;
-
-        for(QpidByteBuffer buf : contentBody)
-        {
-            size += buf.remaining();
-        }
-        byte[] data = new byte[size];
-        ByteBuffer dst = ByteBuffer.wrap(data);
-        for(QpidByteBuffer buf : contentBody)
-        {
-            buf.copyTo(dst);
-        }
-
-        try(PreparedStatement stmt = conn.prepareStatement("INSERT INTO " + getMessageContentTableName()
-                                                           + "( message_id, content ) values (?, ?)"))
+        try (PreparedStatement stmt = conn.prepareStatement("INSERT INTO " + getMessageContentTableName()
+                                                            + "( message_id, content ) values (?, ?)");
+             QpidByteBuffer bodyDuplicate = contentBody.duplicate();
+             InputStream inputStream = bodyDuplicate.asInputStream())
         {
             stmt.setLong(1, messageId);
-            stmt.setBinaryStream(2, new ByteArrayInputStream(data), data.length);
+            stmt.setBinaryStream(2, inputStream, contentBody.remaining());
             stmt.executeUpdate();
         }
-        catch (SQLException e)
+        catch (SQLException | IOException e)
         {
             JdbcUtils.closeConnection(conn, getLogger());
             throw new StoreException("Error adding content for message " + messageId + ": " + e.getMessage(), e);
         }
     }
 
-    Collection<QpidByteBuffer> getAllContent(long messageId) throws StoreException
+    QpidByteBuffer getAllContent(long messageId) throws StoreException
     {
         getLogger().debug("Message Id: {} Getting content body", messageId);
 
@@ -1017,18 +1012,10 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
 
             if (rs.next())
             {
-                byte[] data = getBlobAsBytes(rs, 1);
-                int offset = 0;
-                int length = data.length;
-                Collection<QpidByteBuffer> buffers = QpidByteBuffer.allocateDirectCollection(length);
-                for(QpidByteBuffer buf : buffers)
+                try (InputStream blobAsInputStream = getBlobAsInputStream(rs, 1))
                 {
-                    int bufSize = buf.remaining();
-                    buf.put(data, offset, bufSize);
-                    buf.flip();
-                    offset+=bufSize;
+                    return QpidByteBuffer.asQpidByteBuffer(blobAsInputStream);
                 }
-                return buffers;
             }
             else
             {
@@ -1036,7 +1023,7 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
             }
 
         }
-        catch (SQLException e)
+        catch (SQLException | IOException e)
         {
             throw new StoreException("Error retrieving content for message " + messageId + ": " + e.getMessage(), e);
         }
@@ -1262,7 +1249,7 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
     private static class MessageDataRef<T extends StorableMessageMetaData>
     {
         private volatile T _metaData;
-        private volatile Collection<QpidByteBuffer> _data;
+        private volatile QpidByteBuffer _data;
         private volatile boolean _isHardRef;
 
         private MessageDataRef(final T metaData, boolean isHardRef)
@@ -1270,7 +1257,7 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
             this(metaData, null, isHardRef);
         }
 
-        private MessageDataRef(final T metaData, Collection<QpidByteBuffer> data, boolean isHardRef)
+        private MessageDataRef(final T metaData, QpidByteBuffer data, boolean isHardRef)
         {
             _metaData = metaData;
             _data = data;
@@ -1282,12 +1269,12 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
             return _metaData;
         }
 
-        public Collection<QpidByteBuffer> getData()
+        public QpidByteBuffer getData()
         {
             return _data;
         }
 
-        public void setData(final Collection<QpidByteBuffer> data)
+        public void setData(final QpidByteBuffer data)
         {
             _data = data;
         }
@@ -1322,11 +1309,8 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
             }
             if(_data != null)
             {
-                for(QpidByteBuffer buf : _data)
-                {
-                    bytesCleared += buf.remaining();
-                    buf.dispose();
-                }
+                bytesCleared += _data.remaining();
+                _data.dispose();
                 _data = null;
             }
             return bytesCleared;
@@ -1405,20 +1389,17 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
         @Override
         public synchronized void addContent(QpidByteBuffer src)
         {
-            src = src.slice();
-            Collection<QpidByteBuffer> data = _messageDataRef.getData();
-            if(data == null)
+            try(QpidByteBuffer data = _messageDataRef.getData())
             {
-                _messageDataRef.setData(Collections.singleton(src));
-            }
-            else
-            {
-                List<QpidByteBuffer> newCollection = new ArrayList<>(data.size()+1);
-                newCollection.addAll(data);
-                newCollection.add(src);
-                _messageDataRef.setData(Collections.unmodifiableCollection(newCollection));
+                if(data == null)
+                {
+                    _messageDataRef.setData(src.slice());
+                }
+                else
+                {
+                    _messageDataRef.setData(QpidByteBuffer.concatenate(Arrays.asList(data, src)));
+                }
             }
-
         }
 
         @Override
@@ -1429,11 +1410,11 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
         }
 
         /**
-         * returns QBBs containing the content. The caller must not dispose of them because we keep a reference in _messageDataRef.
+         * returns QBB containing the content. The caller must not dispose of them because we keep a reference in _messageDataRef.
          */
-        private Collection<QpidByteBuffer> getContentAsByteBuffer()
+        private QpidByteBuffer getContentAsByteBuffer()
         {
-            Collection<QpidByteBuffer> data = _messageDataRef == null ? Collections.<QpidByteBuffer>emptyList() : _messageDataRef.getData();
+            QpidByteBuffer data = _messageDataRef == null ? QpidByteBuffer.emptyQpidByteBuffer() : _messageDataRef.getData();
             if(data == null)
             {
                 if(stored())
@@ -1445,57 +1426,16 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
                 }
                 else
                 {
-                    data = Collections.emptyList();
+                    data = QpidByteBuffer.emptyQpidByteBuffer();
                 }
             }
             return data;
         }
 
         @Override
-        public synchronized Collection<QpidByteBuffer> getContent(int offset, int length)
+        public synchronized QpidByteBuffer getContent(int offset, int length)
         {
-            Collection<QpidByteBuffer> bufs = getContentAsByteBuffer();
-            Collection<QpidByteBuffer> content = new ArrayList<>(bufs.size());
-
-            int pos = 0;
-            for (QpidByteBuffer buf : bufs)
-            {
-                if (length > 0)
-                {
-                    int bufRemaining = buf.remaining();
-                    if (pos + bufRemaining <= offset)
-                    {
-                        pos += bufRemaining;
-                    }
-                    else if (pos >= offset)
-                    {
-                        buf = buf.duplicate();
-                        if (bufRemaining <= length)
-                        {
-                            length -= bufRemaining;
-                        }
-                        else
-                        {
-                            buf.limit(length);
-                            length = 0;
-                        }
-                        content.add(buf);
-                        pos += buf.remaining();
-
-                    }
-                    else
-                    {
-                        int offsetInBuf = offset - pos;
-                        int limit = length < bufRemaining - offsetInBuf ? length : bufRemaining - offsetInBuf;
-                        final QpidByteBuffer bufView = buf.view(offsetInBuf, limit);
-                        content.add(bufView);
-                        length -= limit;
-                        pos+=limit+offsetInBuf;
-                    }
-                }
-
-            }
-            return content;
+            return getContentAsByteBuffer().view(offset, length);
         }
 
         @Override
@@ -1517,7 +1457,7 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
                 AbstractJDBCMessageStore.this.storeMetaData(conn, _messageId, _messageDataRef.getMetaData());
                 AbstractJDBCMessageStore.this.addContent(conn, _messageId,
                                                          _messageDataRef.getData() == null
-                                                                ? Collections.<QpidByteBuffer>emptySet()
+                                                                ? QpidByteBuffer.emptyQpidByteBuffer()
                                                                 : _messageDataRef.getData());
 
                 getLogger().debug("Storing message {} to store", _messageId);
@@ -1569,14 +1509,12 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
                 metaData.dispose();
             }
 
-            Collection<QpidByteBuffer> data = _messageDataRef.getData();
-            if(data != null)
+            try (QpidByteBuffer data = _messageDataRef.getData())
             {
-                bytesCleared += getContentSize();
-                _messageDataRef.setData(null);
-                for(QpidByteBuffer buf : data)
+                if (data != null)
                 {
-                    buf.dispose();
+                    bytesCleared += getContentSize();
+                    _messageDataRef.setData(null);
                 }
             }
             _messageDataRef = null;
@@ -1670,9 +1608,11 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
                     {
                         if (rs.next())
                         {
-                            byte[] dataAsBytes = getBlobAsBytes(rs, 2);
-                            StorableMessageMetaData metaData = getStorableMessageMetaData(messageId, dataAsBytes);
-                            message = createStoredJDBCMessage(messageId, metaData, true);
+                            try (InputStream blobAsInputStream = getBlobAsInputStream(rs, 2))
+                            {
+                                final StorableMessageMetaData metaData = getStorableMessageMetaData(messageId, blobAsInputStream);
+                                message = createStoredJDBCMessage(messageId, metaData, true);
+                            }
                         }
                         else
                         {
@@ -1682,7 +1622,7 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
                 }
                 return message;
             }
-            catch (SQLException e)
+            catch (SQLException | IOException e)
             {
                 throw new StoreException("Error encountered when visiting messages", e);
             }
@@ -1710,18 +1650,20 @@ public abstract class AbstractJDBCMessageStore implements MessageStore
                         while (rs.next())
                         {
                             long messageId = rs.getLong(1);
-                            byte[] dataAsBytes = getBlobAsBytes(rs, 2);
-                            StorableMessageMetaData metaData = getStorableMessageMetaData(messageId, dataAsBytes);
-                            StoredJDBCMessage message = createStoredJDBCMessage(messageId, metaData, true);
-                            if (!handler.handle(message))
+                            try (InputStream dataAsInputStream = getBlobAsInputStream(rs, 2))
                             {
-                                break;
+                                StorableMessageMetaData metaData = getStorableMessageMetaData(messageId, dataAsInputStream);
+                                StoredJDBCMessage message = createStoredJDBCMessage(messageId, metaData, true);
+                                if (!handler.handle(message))
+                                {
+                                    break;
+                                }
                             }
                         }
                     }
                 }
             }
-            catch (SQLException e)
+            catch (SQLException | IOException e)
             {
                 throw new StoreException("Error encountered when visiting messages", e);
             }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCConfigurationStore.java
----------------------------------------------------------------------
diff --git a/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCConfigurationStore.java b/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCConfigurationStore.java
index 3b77b10..efbedb3 100644
--- a/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCConfigurationStore.java
+++ b/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCConfigurationStore.java
@@ -22,7 +22,9 @@ package org.apache.qpid.server.store.jdbc;
 import static org.apache.qpid.server.store.jdbc.AbstractJDBCConfigurationStore.State.CLOSED;
 import static org.apache.qpid.server.store.jdbc.AbstractJDBCConfigurationStore.State.CONFIGURED;
 
+import java.io.ByteArrayInputStream;
 import java.io.File;
+import java.io.InputStream;
 import java.nio.charset.Charset;
 import java.sql.Blob;
 import java.sql.Connection;
@@ -204,17 +206,16 @@ public class GenericJDBCConfigurationStore extends AbstractJDBCConfigurationStor
 
     }
 
-    protected byte[] getBlobAsBytes(ResultSet rs, int col) throws SQLException
+    protected InputStream getBlobAsInputStream(ResultSet rs, int col) throws SQLException
     {
         if(_useBytesMethodsForBlob)
         {
-            return rs.getBytes(col);
+            return new ByteArrayInputStream(rs.getBytes(col));
         }
         else
         {
             Blob dataAsBlob = rs.getBlob(col);
-            return dataAsBlob.getBytes(1,(int) dataAsBlob.length());
-
+            return dataAsBlob.getBinaryStream();
         }
     }
 
@@ -298,9 +299,9 @@ public class GenericJDBCConfigurationStore extends AbstractJDBCConfigurationStor
         }
 
         @Override
-        protected byte[] getBlobAsBytes(final ResultSet rs, final int col) throws SQLException
+        protected InputStream getBlobAsInputStream(final ResultSet rs, final int col) throws SQLException
         {
-            return GenericJDBCConfigurationStore.this.getBlobAsBytes(rs, col);
+            return GenericJDBCConfigurationStore.this.getBlobAsInputStream(rs, col);
         }
     }
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCMessageStore.java
----------------------------------------------------------------------
diff --git a/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCMessageStore.java b/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCMessageStore.java
index 1b3c827..551362d 100644
--- a/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCMessageStore.java
+++ b/broker-plugins/jdbc-store/src/main/java/org/apache/qpid/server/store/jdbc/GenericJDBCMessageStore.java
@@ -21,7 +21,9 @@
 package org.apache.qpid.server.store.jdbc;
 
 
+import java.io.ByteArrayInputStream;
 import java.io.File;
+import java.io.InputStream;
 import java.sql.Blob;
 import java.sql.Connection;
 import java.sql.ResultSet;
@@ -156,17 +158,16 @@ public class GenericJDBCMessageStore extends GenericAbstractJDBCMessageStore
     }
 
     @Override
-    protected byte[] getBlobAsBytes(ResultSet rs, int col) throws SQLException
+    protected InputStream getBlobAsInputStream(ResultSet rs, int col) throws SQLException
     {
         if(_useBytesMethodsForBlob)
         {
-            return rs.getBytes(col);
+            return new ByteArrayInputStream(rs.getBytes(col));
         }
         else
         {
             Blob dataAsBlob = rs.getBlob(col);
-            return dataAsBlob.getBytes(1,(int) dataAsBlob.length());
-
+            return dataAsBlob.getBinaryStream();
         }
     }
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagement.java
----------------------------------------------------------------------
diff --git a/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagement.java b/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagement.java
index f81648b..5dbbe67 100644
--- a/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagement.java
+++ b/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/HttpManagement.java
@@ -34,9 +34,9 @@ import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
 
 import javax.net.ssl.SSLContext;
 import javax.net.ssl.SSLEngine;
@@ -856,69 +856,18 @@ public class HttpManagement extends AbstractPluginAdapter<HttpManagement> implem
 
     private static class QBBTrackingThreadPool extends QueuedThreadPool
     {
-        private final Map<Thread, QpidByteBuffer> _cachedBufferMap = new ConcurrentHashMap<>();
+        private final ThreadFactory _threadFactory;
 
         public QBBTrackingThreadPool(@Name("maxThreads") final int maxThreads, @Name("minThreads") final int minThreads)
         {
             super(maxThreads, minThreads);
-        }
-
-        @Override
-        protected void doStop() throws Exception
-        {
-            try
-            {
-                super.doStop();
-            }
-            finally
-            {
-                for (QpidByteBuffer qpidByteBuffer : _cachedBufferMap.values())
-                {
-                    qpidByteBuffer.dispose();
-                }
-                _cachedBufferMap.clear();
-            }
+            _threadFactory = QpidByteBuffer.createQpidByteBufferTrackingThreadFactory(r -> QBBTrackingThreadPool.super.newThread(r));
         }
 
         @Override
         protected Thread newThread(final Runnable runnable)
         {
-            return super.newThread(() ->
-                {
-                    try
-                    {
-                        runnable.run();
-                    }
-                    finally
-                    {
-                        QpidByteBuffer qbb = _cachedBufferMap.remove(Thread.currentThread());
-                        if (qbb != null)
-                        {
-                            qbb.dispose();
-                        }
-                    }
-            });
-        }
-
-        @Override
-        protected void runJob(final Runnable job)
-        {
-            try
-            {
-                super.runJob(job);
-            }
-            finally
-            {
-                final QpidByteBuffer cachedThreadLocalBuffer = QpidByteBuffer.getCachedThreadLocalBuffer();
-                if (cachedThreadLocalBuffer != null)
-                {
-                    _cachedBufferMap.put(Thread.currentThread(), cachedThreadLocalBuffer);
-                }
-                else
-                {
-                    _cachedBufferMap.remove(Thread.currentThread());
-                }
-            }
+            return _threadFactory.newThread(runnable);
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportRunner.java
----------------------------------------------------------------------
diff --git a/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportRunner.java b/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportRunner.java
index 3242f01..a33a3d6 100644
--- a/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportRunner.java
+++ b/broker-plugins/management-http/src/main/java/org/apache/qpid/server/management/plugin/report/ReportRunner.java
@@ -45,7 +45,6 @@ import org.apache.qpid.server.message.ServerMessage;
 import org.apache.qpid.server.model.Queue;
 import org.apache.qpid.server.queue.QueueEntry;
 import org.apache.qpid.server.queue.QueueEntryVisitor;
-import org.apache.qpid.server.util.ByteBufferUtils;
 
 public class ReportRunner<T>
 {
@@ -216,11 +215,11 @@ public class ReportRunner<T>
     {
         final MessageInfoImpl messageInfo = new MessageInfoImpl(entry, true);
         ServerMessage message = entry.getMessage();
-        final Collection<QpidByteBuffer> contentBuffers = message.getContent(0, (int) message.getSize());
-        final ByteBuffer content = ByteBufferUtils.combine(contentBuffers);
-        for(QpidByteBuffer buf : contentBuffers)
+        byte[] content;
+        try (QpidByteBuffer contentBuffer = message.getContent())
         {
-            buf.dispose();
+            content = new byte[contentBuffer.remaining()];
+            contentBuffer.get(content);
         }
 
         return new ReportableMessage()
@@ -240,7 +239,7 @@ public class ReportRunner<T>
             @Override
             public ByteBuffer getContent()
             {
-                return content.asReadOnlyBuffer();
+                return ByteBuffer.wrap(content).asReadOnlyBuffer();
             }
 
             @Override

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/report/ReportRunnerTest.java
----------------------------------------------------------------------
diff --git a/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/report/ReportRunnerTest.java b/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/report/ReportRunnerTest.java
index a1c3f34..7c85f39 100644
--- a/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/report/ReportRunnerTest.java
+++ b/broker-plugins/management-http/src/test/java/org/apache/qpid/server/management/plugin/report/ReportRunnerTest.java
@@ -35,6 +35,7 @@ import org.mockito.ArgumentCaptor;
 import org.mockito.invocation.InvocationOnMock;
 import org.mockito.stubbing.Answer;
 
+import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.AMQMessageHeader;
 import org.apache.qpid.server.message.ServerMessage;
 import org.apache.qpid.server.model.Queue;
@@ -67,6 +68,7 @@ public class ReportRunnerTest extends QpidTestCase
         final ServerMessage message = mock(ServerMessage.class);
         final AMQMessageHeader header = mock(AMQMessageHeader.class);
         when(message.getMessageHeader()).thenReturn(header);
+        when(message.getContent()).thenReturn(QpidByteBuffer.emptyQpidByteBuffer());
 
         return message;
     }
@@ -158,6 +160,7 @@ public class ReportRunnerTest extends QpidTestCase
             }
         });
         when(header.getHeaderNames()).thenReturn(props.keySet());
+        when(message.getContent()).thenReturn(QpidByteBuffer.emptyQpidByteBuffer());
         return message;
     }
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/websocket/src/main/java/org/apache/qpid/server/transport/websocket/WebSocketProvider.java
----------------------------------------------------------------------
diff --git a/broker-plugins/websocket/src/main/java/org/apache/qpid/server/transport/websocket/WebSocketProvider.java b/broker-plugins/websocket/src/main/java/org/apache/qpid/server/transport/websocket/WebSocketProvider.java
index 76b3fbd..8394ca8 100644
--- a/broker-plugins/websocket/src/main/java/org/apache/qpid/server/transport/websocket/WebSocketProvider.java
+++ b/broker-plugins/websocket/src/main/java/org/apache/qpid/server/transport/websocket/WebSocketProvider.java
@@ -30,11 +30,10 @@ import java.security.cert.X509Certificate;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
-import java.util.Map;
 import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentLinkedQueue;
 import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.atomic.AtomicBoolean;
 
 import javax.net.ssl.SSLContext;
@@ -130,68 +129,7 @@ class WebSocketProvider implements AcceptingTransport
     {
         _idleTimeoutChecker.start();
 
-        _server = new Server(new QueuedThreadPool()
-        {
-            private final Map<Thread, QpidByteBuffer> _cachedBufferMap = new ConcurrentHashMap<>();
-
-            @Override
-            protected void doStop() throws Exception
-            {
-                try
-                {
-                    super.doStop();
-                }
-                finally
-                {
-                    for (QpidByteBuffer qpidByteBuffer : _cachedBufferMap.values())
-                    {
-                        qpidByteBuffer.dispose();
-                    }
-                    _cachedBufferMap.clear();
-                }
-            }
-
-            @Override
-            protected Thread newThread(final Runnable runnable)
-            {
-                return super.newThread(() ->
-                                       {
-                                           try
-                                           {
-                                               runnable.run();
-                                           }
-                                           finally
-                                           {
-                                               QpidByteBuffer qbb = _cachedBufferMap.remove(Thread.currentThread());
-                                               if (qbb != null)
-                                               {
-                                                   qbb.dispose();
-                                               }
-                                           }
-                                       });
-            }
-
-            @Override
-            protected void runJob(final Runnable job)
-            {
-                try
-                {
-                    super.runJob(job);
-                }
-                finally
-                {
-                    final QpidByteBuffer cachedThreadLocalBuffer = QpidByteBuffer.getCachedThreadLocalBuffer();
-                    if (cachedThreadLocalBuffer != null)
-                    {
-                        _cachedBufferMap.put(Thread.currentThread(), cachedThreadLocalBuffer);
-                    }
-                    else
-                    {
-                        _cachedBufferMap.remove(Thread.currentThread());
-                    }
-                }
-            }
-        });
+        _server = new Server(new QBBTrackingThreadPool());
 
         final ServerConnector connector;
         HttpConnectionFactory httpConnectionFactory = new HttpConnectionFactory();
@@ -357,6 +295,17 @@ class WebSocketProvider implements AcceptingTransport
                 ((ServerConnector) server.getConnectors()[0]).getLocalPort();
     }
 
+    private static class QBBTrackingThreadPool extends QueuedThreadPool
+    {
+        private final ThreadFactory _threadFactory = QpidByteBuffer.createQpidByteBufferTrackingThreadFactory(r -> QBBTrackingThreadPool.super.newThread(r));
+
+        @Override
+        protected Thread newThread(final Runnable runnable)
+        {
+            return _threadFactory.newThread(runnable);
+        }
+    }
+
     @WebSocket
     public class AmqpWebSocket
     {
@@ -442,13 +391,14 @@ class WebSocketProvider implements AcceptingTransport
 
         private void restoreApplicationBufferForWrite()
         {
-            QpidByteBuffer oldNetInputBuffer = _netInputBuffer;
-            int unprocessedDataLength = _netInputBuffer.remaining();
+            try (QpidByteBuffer oldNetInputBuffer = _netInputBuffer)
+            {
+                int unprocessedDataLength = _netInputBuffer.remaining();
 
-            _netInputBuffer.limit(_netInputBuffer.capacity());
-            _netInputBuffer = oldNetInputBuffer.slice();
-            _netInputBuffer.limit(unprocessedDataLength);
-            oldNetInputBuffer.dispose();
+                _netInputBuffer.limit(_netInputBuffer.capacity());
+                _netInputBuffer = oldNetInputBuffer.slice();
+                _netInputBuffer.limit(unprocessedDataLength);
+            }
             if (_netInputBuffer.limit() != _netInputBuffer.capacity())
             {
                 _netInputBuffer.position(_netInputBuffer.limit());
@@ -456,22 +406,23 @@ class WebSocketProvider implements AcceptingTransport
             }
             else
             {
-                QpidByteBuffer currentBuffer = _netInputBuffer;
-                int newBufSize;
-
-                if (currentBuffer.capacity() < _broker.getNetworkBufferSize())
+                try (QpidByteBuffer currentBuffer = _netInputBuffer)
                 {
-                    newBufSize = _broker.getNetworkBufferSize();
-                }
-                else
-                {
-                    newBufSize = currentBuffer.capacity() + _broker.getNetworkBufferSize();
-                    reportUnexpectedByteBufferSizeUsage();
-                }
+                    int newBufSize;
 
-                _netInputBuffer = QpidByteBuffer.allocateDirect(newBufSize);
-                _netInputBuffer.put(currentBuffer);
-                currentBuffer.dispose();
+                    if (currentBuffer.capacity() < _broker.getNetworkBufferSize())
+                    {
+                        newBufSize = _broker.getNetworkBufferSize();
+                    }
+                    else
+                    {
+                        newBufSize = currentBuffer.capacity() + _broker.getNetworkBufferSize();
+                        reportUnexpectedByteBufferSizeUsage();
+                    }
+
+                    _netInputBuffer = QpidByteBuffer.allocateDirect(newBufSize);
+                    _netInputBuffer.put(currentBuffer);
+                }
             }
         }
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/FrameTransport.java
----------------------------------------------------------------------
diff --git a/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/FrameTransport.java b/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/FrameTransport.java
index 4cb0ccb..4d53751 100644
--- a/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/FrameTransport.java
+++ b/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/FrameTransport.java
@@ -26,7 +26,6 @@ import static org.hamcrest.Matchers.is;
 import static org.hamcrest.Matchers.nullValue;
 
 import java.net.InetSocketAddress;
-import java.util.List;
 import java.util.concurrent.ArrayBlockingQueue;
 import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.TimeUnit;
@@ -34,6 +33,7 @@ import java.util.concurrent.TimeUnit;
 import com.google.common.base.Preconditions;
 import com.google.common.util.concurrent.JdkFutureAdapters;
 import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.MoreExecutors;
 import io.netty.bootstrap.Bootstrap;
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.ByteBufAllocator;
@@ -158,11 +158,32 @@ public class FrameTransport implements AutoCloseable
     {
         Preconditions.checkState(_channel != null, "Not connected");
         ChannelPromise promise = _channel.newPromise();
-        final List<QpidByteBuffer> payload = frameBody instanceof Transfer ? ((Transfer) frameBody).getPayload() : null;
-        TransportFrame transportFrame = new TransportFrame(channel.shortValue(), frameBody, payload);
-        _channel.write(transportFrame, promise);
-        _channel.flush();
-        return JdkFutureAdapters.listenInPoolThread(promise);
+        final TransportFrame transportFrame;
+        try (QpidByteBuffer payload = frameBody instanceof Transfer ? ((Transfer) frameBody).getPayload() : null)
+        {
+            final QpidByteBuffer duplicate;
+            if (payload == null)
+            {
+                duplicate = null;
+            }
+            else
+            {
+                duplicate = payload.duplicate();
+            }
+            transportFrame = new TransportFrame(channel.shortValue(), frameBody, duplicate);
+            _channel.write(transportFrame, promise);
+            _channel.flush();
+            final ListenableFuture<Void> listenableFuture = JdkFutureAdapters.listenInPoolThread(promise);
+            if (frameBody instanceof Transfer)
+            {
+                listenableFuture.addListener(() -> ((Transfer) frameBody).dispose(), MoreExecutors.directExecutor());
+            }
+            if (duplicate != null)
+            {
+                listenableFuture.addListener(() -> duplicate.dispose(), MoreExecutors.directExecutor());
+            }
+            return listenableFuture;
+        }
     }
 
     public ListenableFuture<Void> sendPerformative(final SaslFrameBody frameBody) throws Exception

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/Interaction.java
----------------------------------------------------------------------
diff --git a/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/Interaction.java b/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/Interaction.java
index 0b91273..52518ab 100644
--- a/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/Interaction.java
+++ b/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/Interaction.java
@@ -761,7 +761,7 @@ public class Interaction
         return this;
     }
 
-    public Interaction transferPayload(final List<QpidByteBuffer> payload)
+    public Interaction transferPayload(final QpidByteBuffer payload)
     {
         _transfer.setPayload(payload);
         return this;
@@ -777,12 +777,10 @@ public class Interaction
     {
         AmqpValue amqpValue = new AmqpValue(payload);
         final AmqpValueSection section = amqpValue.createEncodingRetainingSection();
-        final List<QpidByteBuffer> encodedForm = section.getEncodedForm();
-        transfer.setPayload(encodedForm);
-        section.dispose();
-        for (QpidByteBuffer qbb : encodedForm)
+        try (QpidByteBuffer encodedForm = section.getEncodedForm())
         {
-            qbb.dispose();
+            transfer.setPayload(encodedForm);
+            section.dispose();
         }
     }
 
@@ -806,15 +804,12 @@ public class Interaction
         transferCopy.setResume(transfer.getResume());
         transferCopy.setAborted(transfer.getAborted());
         transferCopy.setBatchable(transfer.getBatchable());
-        final List<QpidByteBuffer> payload = transfer.getPayload();
-        if (payload != null)
+        try (QpidByteBuffer payload = transfer.getPayload())
         {
-            final List<QpidByteBuffer> payloadCopy = new ArrayList<>(payload.size());
-            for (QpidByteBuffer qpidByteBuffer : payload)
+            if (payload != null)
             {
-                payloadCopy.add(qpidByteBuffer.duplicate());
+                transferCopy.setPayload(payload);
             }
-            transferCopy.setPayload(payloadCopy);
         }
         return transferCopy;
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/MessageDecoder.java
----------------------------------------------------------------------
diff --git a/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/MessageDecoder.java b/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/MessageDecoder.java
index 8656b9b..1a513f7 100644
--- a/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/MessageDecoder.java
+++ b/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/MessageDecoder.java
@@ -32,7 +32,6 @@ import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.codec.SectionDecoderRegistry;
 import org.apache.qpid.server.protocol.v1_0.messaging.SectionDecoder;
 import org.apache.qpid.server.protocol.v1_0.messaging.SectionDecoderImpl;
-import org.apache.qpid.server.protocol.v1_0.messaging.SectionEncoder;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.codec.AMQPDescribedTypeRegistry;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.AmqpSequenceSection;
@@ -72,14 +71,20 @@ public class MessageDecoder
         {
             throw new IllegalStateException("The section fragments have already been parsed");
         }
-        _fragments.addAll(transfer.getPayload());
+        _fragments.add(transfer.getPayload());
     }
 
     public void parse() throws AmqpErrorException
     {
         if (!_parsed)
         {
-            List<EncodingRetainingSection<?>> sections = _sectionDecoder.parseAll(_fragments);
+            List<EncodingRetainingSection<?>> sections;
+            try (QpidByteBuffer combined = QpidByteBuffer.concatenate(_fragments))
+            {
+                sections = _sectionDecoder.parseAll(combined);
+            }
+            _fragments.forEach(QpidByteBuffer::dispose);
+
             Iterator<EncodingRetainingSection<?>> iter = sections.iterator();
             EncodingRetainingSection<?> s = iter.hasNext() ? iter.next() : null;
             if (s instanceof HeaderSection)

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/MessageEncoder.java
----------------------------------------------------------------------
diff --git a/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/MessageEncoder.java b/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/MessageEncoder.java
index 0c77ab1..37e327e 100644
--- a/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/MessageEncoder.java
+++ b/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/MessageEncoder.java
@@ -44,12 +44,12 @@ public class MessageEncoder
         _header = header;
     }
 
-    public List<QpidByteBuffer> getPayload()
+    public QpidByteBuffer getPayload()
     {
         List<QpidByteBuffer> payload = new ArrayList<>();
         if (_header != null)
         {
-            payload.addAll(_header.createEncodingRetainingSection().getEncodedForm());
+            payload.add(_header.createEncodingRetainingSection().getEncodedForm());
         }
 
         if (_data.isEmpty())
@@ -70,10 +70,12 @@ public class MessageEncoder
 
         for (EncodingRetainingSection<?> section: dataSections)
         {
-            payload.addAll(section.getEncodedForm());
+            payload.add(section.getEncodedForm());
             section.dispose();
         }
 
-        return payload;
+        QpidByteBuffer combined = QpidByteBuffer.concatenate(payload);
+        payload.forEach(QpidByteBuffer::dispose);
+        return combined;
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/OutputHandler.java
----------------------------------------------------------------------
diff --git a/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/OutputHandler.java b/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/OutputHandler.java
index dbd4cd6..68f4322 100644
--- a/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/OutputHandler.java
+++ b/systests/protocol-tests-amqp-1-0/src/main/java/org/apache/qpid/tests/protocol/v1_0/OutputHandler.java
@@ -59,8 +59,10 @@ public class OutputHandler extends ChannelOutboundHandlerAdapter
                 @Override
                 public void send(final QpidByteBuffer msg)
                 {
+                    byte[] data = new byte[msg.remaining()];
+                    msg.get(data);
                     ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
-                    buffer.writeBytes(msg.asByteBuffer());
+                    buffer.writeBytes(data);
                     try
                     {
                         OutputHandler.super.write(ctx, buffer, promise);


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[05/10] qpid-broker-j git commit: QPID-7832: [Java Broker] Refactor store/protocol API using Collection

Posted by lq...@apache.org.
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/PropertyConverter_v0_8_to_InternalTest.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/PropertyConverter_v0_8_to_InternalTest.java b/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/PropertyConverter_v0_8_to_InternalTest.java
index cc9a2ed..4c9cf37 100644
--- a/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/PropertyConverter_v0_8_to_InternalTest.java
+++ b/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/PropertyConverter_v0_8_to_InternalTest.java
@@ -24,7 +24,6 @@ package org.apache.qpid.server.protocol.v0_8;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
-import java.util.Collections;
 import java.util.HashMap;
 import java.util.Map;
 
@@ -313,8 +312,12 @@ public class PropertyConverter_v0_8_to_InternalTest extends QpidTestCase
         if (content != null)
         {
             when(storedMessage.getContentSize()).thenReturn(content.length);
-            when(storedMessage.getContent(0, content.length)).thenReturn(Collections.singleton(QpidByteBuffer.wrap(
-                    content)));
+            when(storedMessage.getContent(0, content.length)).thenReturn(QpidByteBuffer.wrap(content));
+        }
+        else
+        {
+            when(storedMessage.getContentSize()).thenReturn(0);
+            when(storedMessage.getContent(0, 0)).thenReturn(QpidByteBuffer.emptyQpidByteBuffer());
         }
 
         return new AMQMessage(storedMessage);

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AMQPConnection_1_0.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AMQPConnection_1_0.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AMQPConnection_1_0.java
index a1576cd..660d995 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AMQPConnection_1_0.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AMQPConnection_1_0.java
@@ -21,7 +21,6 @@
 package org.apache.qpid.server.protocol.v1_0;
 
 import java.util.Iterator;
-import java.util.List;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.logging.EventLoggerProvider;
@@ -71,7 +70,7 @@ public interface AMQPConnection_1_0<C extends AMQPConnection_1_0<C>> extends AMQ
 
     AMQPDescribedTypeRegistry getDescribedTypeRegistry();
 
-    int sendFrame(int channel, FrameBody body, List<QpidByteBuffer> payload);
+    int sendFrame(int channel, FrameBody body, QpidByteBuffer payload);
 
     void sendFrame(int channel, FrameBody body);
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AMQPConnection_1_0Impl.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AMQPConnection_1_0Impl.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AMQPConnection_1_0Impl.java
index 8419b0b..bbdc148 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AMQPConnection_1_0Impl.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AMQPConnection_1_0Impl.java
@@ -58,7 +58,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.logging.messages.ConnectionMessages;
 import org.apache.qpid.server.model.AuthenticationProvider;
 import org.apache.qpid.server.model.Broker;
@@ -444,37 +443,60 @@ public class AMQPConnection_1_0Impl extends AbstractAMQPConnection<AMQPConnectio
     @Override
     public void receive(final List<ChannelFrameBody> channelFrameBodies)
     {
-        PeekingIterator<ChannelFrameBody> itr = Iterators.peekingIterator(channelFrameBodies.iterator());
-
-        while(itr.hasNext())
+        if (!channelFrameBodies.isEmpty())
         {
-            final ChannelFrameBody channelFrameBody = itr.next();
-            final int frameChannel = channelFrameBody.getChannel();
-
-            Session_1_0 session = _receivingSessions == null || frameChannel >= _receivingSessions.length ? null : _receivingSessions[frameChannel];
-            if (session != null)
+            PeekingIterator<ChannelFrameBody> itr = Iterators.peekingIterator(channelFrameBodies.iterator());
+            boolean cleanExit = false;
+            try
             {
-                final AccessControlContext context = session.getAccessControllerContext();
-                AccessController.doPrivileged((PrivilegedAction<Void>) () ->
+                while (itr.hasNext())
                 {
-                    ChannelFrameBody channelFrame = channelFrameBody;
-                    boolean nextIsSameChannel;
-                    do
+                    final ChannelFrameBody channelFrameBody = itr.next();
+                    final int frameChannel = channelFrameBody.getChannel();
+
+                    Session_1_0 session = _receivingSessions == null || frameChannel >= _receivingSessions.length
+                            ? null
+                            : _receivingSessions[frameChannel];
+                    if (session != null)
                     {
-                        received(frameChannel, channelFrame.getFrameBody());
-                        nextIsSameChannel = itr.hasNext() && frameChannel == itr.peek().getChannel();
-                        if (nextIsSameChannel)
+                        final AccessControlContext context = session.getAccessControllerContext();
+                        AccessController.doPrivileged((PrivilegedAction<Void>) () ->
                         {
-                            channelFrame = itr.next();
-                        }
+                            ChannelFrameBody channelFrame = channelFrameBody;
+                            boolean nextIsSameChannel;
+                            do
+                            {
+                                received(frameChannel, channelFrame.getFrameBody());
+                                nextIsSameChannel = itr.hasNext() && frameChannel == itr.peek().getChannel();
+                                if (nextIsSameChannel)
+                                {
+                                    channelFrame = itr.next();
+                                }
+                            }
+                            while (nextIsSameChannel);
+                            return null;
+                        }, context);
                     }
-                    while (nextIsSameChannel);
-                    return null;
-                }, context);
+                    else
+                    {
+                        received(frameChannel, channelFrameBody.getFrameBody());
+                    }
+                }
+                cleanExit = true;
             }
-            else
+            finally
             {
-                received(frameChannel, channelFrameBody.getFrameBody());
+                if (!cleanExit)
+                {
+                    while (itr.hasNext())
+                    {
+                        final Object frameBody = itr.next().getFrameBody();
+                        if (frameBody instanceof Transfer)
+                        {
+                            ((Transfer) frameBody).dispose();
+                        }
+                    }
+                }
             }
         }
     }
@@ -1178,7 +1200,7 @@ public class AMQPConnection_1_0Impl extends AbstractAMQPConnection<AMQPConnectio
     }
 
     @Override
-    public int sendFrame(final int channel, final FrameBody body, final List<QpidByteBuffer> payload)
+    public int sendFrame(final int channel, final FrameBody body, final QpidByteBuffer payload)
     {
         if (!_closedForOutput)
         {
@@ -1192,8 +1214,8 @@ public class AMQPConnection_1_0Impl extends AbstractAMQPConnection<AMQPConnectio
             {
                 int size = writer.getEncodedSize();
                 int maxPayloadSize = _maxFrameSize - (size + 9);
-                long payloadLength = QpidByteBufferUtils.remaining(payload);
-                if(payloadLength <= maxPayloadSize)
+                long payloadLength = (long) payload.remaining();
+                if (payloadLength <= maxPayloadSize)
                 {
                     send(AMQFrame.createAMQFrame(channel, body, payload));
                     return (int)payloadLength;
@@ -1206,32 +1228,10 @@ public class AMQPConnection_1_0Impl extends AbstractAMQPConnection<AMQPConnectio
                     size = writer.getEncodedSize();
                     maxPayloadSize = _maxFrameSize - (size + 9);
 
-                    List<QpidByteBuffer> payloadDup = new ArrayList<>(payload.size());
-                    int payloadSize = 0;
-                    for(QpidByteBuffer buf : payload)
+                    try (QpidByteBuffer payloadDup = payload.view(0, maxPayloadSize))
                     {
-                        if (buf.hasRemaining())
-                        {
-                            if (payloadSize + buf.remaining() < maxPayloadSize)
-                            {
-                                payloadSize += buf.remaining();
-                                payloadDup.add(buf.duplicate());
-                            }
-                            else
-                            {
-                                QpidByteBuffer dup = buf.slice();
-                                dup.limit(maxPayloadSize - payloadSize);
-                                payloadDup.add(dup);
-                                break;
-                            }
-                        }
-                    }
-
-                    QpidByteBufferUtils.skip(payload, maxPayloadSize);
-                    send(AMQFrame.createAMQFrame(channel, body, payloadDup));
-                    for(QpidByteBuffer buf : payloadDup)
-                    {
-                        buf.dispose();
+                        payload.position(payload.position() + maxPayloadSize);
+                        send(AMQFrame.createAMQFrame(channel, body, payloadDup));
                     }
 
                     return maxPayloadSize;
@@ -1361,8 +1361,10 @@ public class AMQPConnection_1_0Impl extends AbstractAMQPConnection<AMQPConnectio
                     throw new ConnectionScopedRuntimeException("SASL Layer header received after SASL already established");
                 }
 
-                getSender().send(QpidByteBuffer.wrap(SASL_HEADER));
-
+                try (QpidByteBuffer protocolHeader = QpidByteBuffer.wrap(SASL_HEADER))
+                {
+                    getSender().send(protocolHeader);
+                }
                 SaslMechanisms mechanisms = new SaslMechanisms();
                 ArrayList<Symbol> mechanismsList = new ArrayList<>();
                 for (String name :  authenticationProvider.getAvailableMechanisms(getTransport().isSecure()))
@@ -1397,7 +1399,10 @@ public class AMQPConnection_1_0Impl extends AbstractAMQPConnection<AMQPConnectio
                     }
 
                 }
-                getSender().send(QpidByteBuffer.wrap(AMQP_HEADER));
+                try (QpidByteBuffer protocolHeader = QpidByteBuffer.wrap(AMQP_HEADER))
+                {
+                    getSender().send(protocolHeader);
+                }
                 _connectionState = ConnectionState.AWAIT_OPEN;
                 _frameHandler = getFrameHandler(false);
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AbstractReceivingLinkEndpoint.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AbstractReceivingLinkEndpoint.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AbstractReceivingLinkEndpoint.java
index 5cc329d..1579573 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AbstractReceivingLinkEndpoint.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AbstractReceivingLinkEndpoint.java
@@ -83,6 +83,12 @@ public abstract class AbstractReceivingLinkEndpoint<T extends BaseTarget> extend
             Error error = validateTransfer(transfer);
             if (error != null)
             {
+                transfer.dispose();
+                if (_currentDelivery != null)
+                {
+                    _currentDelivery.discard();
+                    _currentDelivery = null;
+                }
                 close(error);
                 return;
             }
@@ -92,6 +98,7 @@ public abstract class AbstractReceivingLinkEndpoint<T extends BaseTarget> extend
                 error = validateNewTransfer(transfer);
                 if (error != null)
                 {
+                    transfer.dispose();
                     close(error);
                     return;
                 }
@@ -109,6 +116,9 @@ public abstract class AbstractReceivingLinkEndpoint<T extends BaseTarget> extend
                 error = validateSubsequentTransfer(transfer);
                 if (error != null)
                 {
+                    transfer.dispose();
+                    _currentDelivery.discard();
+                    _currentDelivery = null;
                     close(error);
                     return;
                 }
@@ -121,6 +131,8 @@ public abstract class AbstractReceivingLinkEndpoint<T extends BaseTarget> extend
                                   String.format("delivery '%s' exceeds max-message-size %d",
                                                 _currentDelivery.getDeliveryTag(),
                                                 getSession().getConnection().getMaxMessageSize()));
+                _currentDelivery.discard();
+                _currentDelivery = null;
                 close(error);
                 return;
             }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ConsumerTarget_1_0.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ConsumerTarget_1_0.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ConsumerTarget_1_0.java
index 92237a0..5cfb7c4 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ConsumerTarget_1_0.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ConsumerTarget_1_0.java
@@ -22,7 +22,6 @@ package org.apache.qpid.server.protocol.v1_0;
 
 import java.nio.ByteBuffer;
 import java.util.ArrayList;
-import java.util.Collection;
 import java.util.List;
 
 import org.slf4j.Logger;
@@ -152,7 +151,7 @@ class ConsumerTarget_1_0 extends AbstractConsumerTarget<ConsumerTarget_1_0>
         Transfer transfer = new Transfer();
         try
         {
-            Collection<QpidByteBuffer> bodyContent = message.getContent(0, (int) message.getSize());
+            QpidByteBuffer bodyContent = message.getContent();
             HeaderSection headerSection = message.getHeaderSection();
 
             UnsignedInteger ttl = headerSection == null ? null : headerSection.getValue().getTtl();
@@ -184,50 +183,49 @@ class ConsumerTarget_1_0 extends AbstractConsumerTarget<ConsumerTarget_1_0>
             List<QpidByteBuffer> payload = new ArrayList<>();
             if(headerSection != null)
             {
-                payload.addAll(headerSection.getEncodedForm());
+                payload.add(headerSection.getEncodedForm());
                 headerSection.dispose();
             }
             EncodingRetainingSection<?> section;
             if((section = message.getDeliveryAnnotationsSection()) != null)
             {
-                payload.addAll(section.getEncodedForm());
+                payload.add(section.getEncodedForm());
                 section.dispose();
             }
 
             if((section = message.getMessageAnnotationsSection()) != null)
             {
-                payload.addAll(section.getEncodedForm());
+                payload.add(section.getEncodedForm());
                 section.dispose();
             }
 
             if((section = message.getPropertiesSection()) != null)
             {
-                payload.addAll(section.getEncodedForm());
+                payload.add(section.getEncodedForm());
                 section.dispose();
             }
 
             if((section = message.getApplicationPropertiesSection()) != null)
             {
-                payload.addAll(section.getEncodedForm());
+                payload.add(section.getEncodedForm());
                 section.dispose();
             }
 
-            payload.addAll(bodyContent);
+            payload.add(bodyContent);
 
             if((section = message.getFooterSection()) != null)
             {
-                payload.addAll(section.getEncodedForm());
+                payload.add(section.getEncodedForm());
                 section.dispose();
             }
 
-
-            transfer.setPayload(payload);
-
-            for(QpidByteBuffer buf : payload)
+            try (QpidByteBuffer combined = QpidByteBuffer.concatenate(payload))
             {
-                buf.dispose();
+                transfer.setPayload(combined);
             }
 
+            payload.forEach(QpidByteBuffer::dispose);
+
             byte[] data = new byte[8];
             ByteBuffer.wrap(data).putLong(_deliveryTag++);
             final Binary tag = new Binary(data);

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Delivery.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Delivery.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Delivery.java
index 877e934..0f8e893 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Delivery.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Delivery.java
@@ -24,7 +24,6 @@ import java.util.List;
 import java.util.concurrent.CopyOnWriteArrayList;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.BaseSource;
 import org.apache.qpid.server.protocol.v1_0.type.BaseTarget;
 import org.apache.qpid.server.protocol.v1_0.type.Binary;
@@ -171,11 +170,12 @@ public class Delivery
             }
         }
 
-        final List<QpidByteBuffer> payload = transfer.getPayload();
-        if (payload != null)
+        try (QpidByteBuffer payload = transfer.getPayload())
         {
-            _totalPayloadSize += QpidByteBufferUtils.remaining(payload);
-            QpidByteBufferUtils.dispose(payload);
+            if (payload != null)
+            {
+                _totalPayloadSize += (long) payload.remaining();
+            }
         }
     }
 
@@ -184,17 +184,18 @@ public class Delivery
         return _linkEndpoint;
     }
 
-
-    public List<QpidByteBuffer> getPayload()
+    public QpidByteBuffer getPayload()
     {
-        List<QpidByteBuffer> fragments = new ArrayList<>(_transfers.size());
+        List<QpidByteBuffer> transferBuffers = new ArrayList<>(_transfers.size());
         for (Transfer t : _transfers)
         {
-            fragments.addAll(t.getPayload());
+            transferBuffers.add(t.getPayload());
             t.dispose();
         }
         _transfers.clear();
-        return fragments;
+        final QpidByteBuffer combined = QpidByteBuffer.concatenate(transferBuffers);
+        transferBuffers.forEach(QpidByteBuffer::dispose);
+        return combined;
     }
 
     public void discard()

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_from_1_0.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_from_1_0.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_from_1_0.java
index a0158ad..b744d25 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_from_1_0.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_from_1_0.java
@@ -26,7 +26,6 @@ import java.io.Serializable;
 import java.nio.ByteBuffer;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Collection;
 import java.util.Date;
 import java.util.HashSet;
 import java.util.LinkedHashMap;
@@ -57,6 +56,7 @@ import org.apache.qpid.server.protocol.v1_0.type.messaging.HeaderSection;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.MessageAnnotationsSection;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.Properties;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.PropertiesSection;
+import org.apache.qpid.server.protocol.v1_0.type.messaging.codec.EncodingRetaining;
 import org.apache.qpid.server.util.ConnectionScopedRuntimeException;
 import org.apache.qpid.server.util.ServerScopedRuntimeException;
 
@@ -78,30 +78,26 @@ public class MessageConverter_from_1_0
 
     static Object convertBodyToObject(final Message_1_0 serverMessage)
     {
-        final Collection<QpidByteBuffer> allData = serverMessage.getContent(0, (int) serverMessage.getSize());
         SectionDecoderImpl sectionDecoder = new SectionDecoderImpl(MessageConverter_v1_0_to_Internal.TYPE_REGISTRY.getSectionDecoderRegistry());
 
         Object bodyObject = null;
+        List<EncodingRetainingSection<?>> sections = null;
         try
         {
-            List<EncodingRetainingSection<?>> sections = sectionDecoder.parseAll(new ArrayList<>(allData));
-            for(QpidByteBuffer buf : allData)
+            try (QpidByteBuffer allData = serverMessage.getContent())
             {
-                buf.dispose();
+                sections = sectionDecoder.parseAll(allData);
             }
 
+            List<EncodingRetainingSection<?>> bodySections = new ArrayList<>(sections.size());
             ListIterator<EncodingRetainingSection<?>> iterator = sections.listIterator();
             EncodingRetainingSection<?> previousSection = null;
             while(iterator.hasNext())
             {
                 EncodingRetainingSection<?> section = iterator.next();
-                if(!(section instanceof AmqpValueSection || section instanceof DataSection || section instanceof AmqpSequenceSection))
+                if (section instanceof AmqpValueSection || section instanceof DataSection || section instanceof AmqpSequenceSection)
                 {
-                    iterator.remove();
-                }
-                else
-                {
-                    if(previousSection != null && (previousSection.getClass() != section.getClass() || section instanceof AmqpValueSection))
+                    if (previousSection != null && (previousSection.getClass() != section.getClass() || section instanceof AmqpValueSection))
                     {
                         throw new MessageConversionException("Message is badly formed and has multiple body section which are not all Data or not all AmqpSequence");
                     }
@@ -109,13 +105,14 @@ public class MessageConverter_from_1_0
                     {
                         previousSection = section;
                     }
+                    bodySections.add(section);
                 }
             }
 
             // In 1.0 of the spec, it is illegal to have message with no body but AMQP-127 asks to have that restriction lifted
-            if(!sections.isEmpty())
+            if (!bodySections.isEmpty())
             {
-                EncodingRetainingSection<?> firstBodySection = sections.get(0);
+                EncodingRetainingSection<?> firstBodySection = bodySections.get(0);
                 if(firstBodySection instanceof AmqpValueSection)
                 {
                     bodyObject = convertValue(firstBodySection.getValue());
@@ -123,13 +120,13 @@ public class MessageConverter_from_1_0
                 else if(firstBodySection instanceof DataSection)
                 {
                     int totalSize = 0;
-                    for(EncodingRetainingSection<?> section : sections)
+                    for(EncodingRetainingSection<?> section : bodySections)
                     {
                         totalSize += ((DataSection)section).getValue().getArray().length;
                     }
                     byte[] bodyData = new byte[totalSize];
                     ByteBuffer buf = ByteBuffer.wrap(bodyData);
-                    for(EncodingRetainingSection<?> section : sections)
+                    for(EncodingRetainingSection<?> section : bodySections)
                     {
                         buf.put(((DataSection) section).getValue().asByteBuffer());
                     }
@@ -138,7 +135,7 @@ public class MessageConverter_from_1_0
                 else
                 {
                     ArrayList<Object> totalSequence = new ArrayList<>();
-                    for(EncodingRetainingSection<?> section : sections)
+                    for(EncodingRetainingSection<?> section : bodySections)
                     {
                         totalSequence.addAll(((AmqpSequenceSection)section).getValue());
                     }
@@ -151,6 +148,13 @@ public class MessageConverter_from_1_0
         {
             throw new ConnectionScopedRuntimeException(e);
         }
+        finally
+        {
+            if (sections != null)
+            {
+                sections.forEach(EncodingRetaining::dispose);
+            }
+        }
         return bodyObject;
     }
 
@@ -315,6 +319,7 @@ public class MessageConverter_from_1_0
         if (section != null)
         {
             Map<Symbol, Object> annotations = section.getValue();
+            section.dispose();
             if (annotations != null && annotations.containsKey(JmsMessageTypeAnnotation.ANNOTATION_KEY))
             {
                 Object object = annotations.get(JmsMessageTypeAnnotation.ANNOTATION_KEY);
@@ -337,9 +342,11 @@ public class MessageConverter_from_1_0
     public static Symbol getContentType(final Message_1_0 serverMsg)
     {
         final PropertiesSection propertiesSection = serverMsg.getPropertiesSection();
+
         if (propertiesSection != null)
         {
             final Properties properties = propertiesSection.getValue();
+            propertiesSection.dispose();
             if (properties != null)
             {
                 return properties.getContentType();
@@ -354,6 +361,7 @@ public class MessageConverter_from_1_0
         if (propertiesSection != null)
         {
             final Properties properties = propertiesSection.getValue();
+            propertiesSection.dispose();
             if (properties != null)
             {
                 return properties.getGroupSequence();
@@ -368,6 +376,7 @@ public class MessageConverter_from_1_0
         if (propertiesSection != null)
         {
             final Properties properties = propertiesSection.getValue();
+            propertiesSection.dispose();
             if (properties != null)
             {
                 return properties.getGroupId();
@@ -382,6 +391,7 @@ public class MessageConverter_from_1_0
         if (propertiesSection != null)
         {
             final Properties properties = propertiesSection.getValue();
+            propertiesSection.dispose();
             if (properties != null)
             {
                 return properties.getCreationTime();
@@ -396,6 +406,7 @@ public class MessageConverter_from_1_0
         if (propertiesSection != null)
         {
             final Properties properties = propertiesSection.getValue();
+            propertiesSection.dispose();
             if (properties != null)
             {
                 return properties.getAbsoluteExpiryTime();
@@ -410,6 +421,7 @@ public class MessageConverter_from_1_0
         if (headerSection != null)
         {
             Header header = headerSection.getValue();
+            headerSection.dispose();
             if (header != null)
             {
                 UnsignedInteger ttl = header.getTtl();
@@ -429,6 +441,7 @@ public class MessageConverter_from_1_0
         if (propertiesSection != null)
         {
             final Properties properties = propertiesSection.getValue();
+            propertiesSection.dispose();
             if (properties != null)
             {
                 userId = properties.getUserId();
@@ -444,6 +457,7 @@ public class MessageConverter_from_1_0
         if (propertiesSection != null)
         {
             final Properties properties = propertiesSection.getValue();
+            propertiesSection.dispose();
             if (properties != null)
             {
                 replyTo = properties.getReplyTo();
@@ -459,6 +473,7 @@ public class MessageConverter_from_1_0
         if (propertiesSection != null)
         {
             final Properties properties = propertiesSection.getValue();
+            propertiesSection.dispose();
             if (properties != null)
             {
                 contentEncoding = properties.getContentEncoding();
@@ -474,6 +489,7 @@ public class MessageConverter_from_1_0
         if (propertiesSection != null)
         {
             final Properties properties = propertiesSection.getValue();
+            propertiesSection.dispose();
             if (properties != null)
             {
                 correlationIdObject = properties.getCorrelationId();
@@ -490,6 +506,7 @@ public class MessageConverter_from_1_0
         if (propertiesSection != null)
         {
             final Properties properties = propertiesSection.getValue();
+            propertiesSection.dispose();
             if (properties != null)
             {
                 messageId = properties.getMessageId();

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_to_1_0.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_to_1_0.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_to_1_0.java
index fa85d84..71c3b06 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_to_1_0.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageConverter_to_1_0.java
@@ -38,7 +38,6 @@ import java.io.IOException;
 import java.io.ObjectOutputStream;
 import java.nio.ByteBuffer;
 import java.util.ArrayList;
-import java.util.Collection;
 import java.util.Collections;
 import java.util.LinkedHashMap;
 import java.util.List;
@@ -357,16 +356,13 @@ public abstract class MessageConverter_to_1_0<M extends ServerMessage> implement
     {
         final String mimeType = serverMessage.getMessageHeader().getMimeType();
         byte[] data = new byte[(int) serverMessage.getSize()];
-        int total = 0;
-        for(QpidByteBuffer b : serverMessage.getContent(0, (int) serverMessage.getSize()))
+
+        try (QpidByteBuffer content = serverMessage.getContent())
         {
-            int len = b.remaining();
-            b.get(data, total, len);
-            b.dispose();
-            total += len;
+            content.get(data);
         }
-        byte[] uncompressed;
 
+        byte[] uncompressed;
         if(GZIPUtils.GZIP_CONTENT_ENCODING.equals(serverMessage.getMessageHeader().getEncoding())
            && (uncompressed = GZIPUtils.uncompressBufferToArray(ByteBuffer.wrap(data))) != null)
         {
@@ -420,35 +416,12 @@ public abstract class MessageConverter_to_1_0<M extends ServerMessage> implement
         }
 
         @Override
-        public Collection<QpidByteBuffer> getContent(int offset, int length)
+        public QpidByteBuffer getContent(int offset, int length)
         {
-            int position = 0;
-            List<QpidByteBuffer> content = new ArrayList<>();
-            for(QpidByteBuffer buf : _section.getEncodedForm())
+            try (QpidByteBuffer content = _section.getEncodedForm())
             {
-                if(position < offset)
-                {
-                    if(offset - position < buf.remaining())
-                    {
-                        QpidByteBuffer view = buf.view(offset - position, Math.min(length, buf.remaining() - (offset-position)));
-                        content.add(view);
-                        position += view.remaining();
-                    }
-                    else
-                    {
-                        position += buf.remaining();
-                    }
-                }
-                else if(position <= offset+length)
-                {
-                    QpidByteBuffer view = buf.view(0, Math.min(length - (position-offset), buf.remaining()));
-                    content.add(view);
-                    position += view.remaining();
-                }
-
-                buf.dispose();
+                return content.view(offset, length);
             }
-            return content;
         }
 
         @Override
@@ -490,6 +463,7 @@ public abstract class MessageConverter_to_1_0<M extends ServerMessage> implement
         private void dispose()
         {
             _section.dispose();
+            _metaData.dispose();
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageFormat_1_0.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageFormat_1_0.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageFormat_1_0.java
index 6da3327..bf9731d 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageFormat_1_0.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageFormat_1_0.java
@@ -83,13 +83,13 @@ public class MessageFormat_1_0 implements MessageFormat<Message_1_0>
     }
 
     @Override
-    public List<QpidByteBuffer> convertToMessageFormat(final Message_1_0 message)
+    public QpidByteBuffer convertToMessageFormat(final Message_1_0 message)
     {
         throw new UnsupportedOperationException("not implemented");
     }
 
     @Override
-    public Message_1_0 createMessage(final List<QpidByteBuffer> buf,
+    public Message_1_0 createMessage(final QpidByteBuffer payload,
                                      final MessageStore store,
                                      final Object connectionReference)
     {
@@ -98,7 +98,7 @@ public class MessageFormat_1_0 implements MessageFormat<Message_1_0>
         List<EncodingRetainingSection<?>> allSections;
         try
         {
-            allSections = getSectionDecoder().parseAll(buf);
+            allSections = getSectionDecoder().parseAll(payload);
         }
         catch (AmqpErrorException e)
         {
@@ -110,10 +110,9 @@ public class MessageFormat_1_0 implements MessageFormat<Message_1_0>
 
         for (EncodingRetainingSection<?> dataSection : dataSections)
         {
-            for (QpidByteBuffer buffer : dataSection.getEncodedForm())
+            try (QpidByteBuffer encodedForm = dataSection.getEncodedForm())
             {
-                handle.addContent(buffer);
-                buffer.dispose();
+                handle.addContent(encodedForm);
             }
             dataSection.dispose();
         }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaDataType_1_0.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaDataType_1_0.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaDataType_1_0.java
index 7db8bcd..97fff01 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaDataType_1_0.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaDataType_1_0.java
@@ -20,8 +20,6 @@
  */
 package org.apache.qpid.server.protocol.v1_0;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.ServerMessage;
 import org.apache.qpid.server.plugin.MessageMetaDataType;
@@ -42,9 +40,9 @@ public class MessageMetaDataType_1_0 implements MessageMetaDataType<MessageMetaD
     }
 
     @Override
-    public MessageMetaData_1_0 createMetaData(List<QpidByteBuffer> bufs)
+    public MessageMetaData_1_0 createMetaData(QpidByteBuffer buf)
     {
-        return MessageMetaData_1_0.FACTORY.createMetaData(bufs);
+        return MessageMetaData_1_0.FACTORY.createMetaData(buf);
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaData_1_0.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaData_1_0.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaData_1_0.java
index 6bd9249..e3f9a0e 100755
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaData_1_0.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/MessageMetaData_1_0.java
@@ -34,7 +34,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.message.AMQMessageHeader;
 import org.apache.qpid.server.plugin.MessageMetaDataType;
 import org.apache.qpid.server.protocol.v1_0.messaging.SectionDecoder;
@@ -415,37 +414,29 @@ public class MessageMetaData_1_0 implements StorableMessageMetaData
         }
 
         @Override
-        public MessageMetaData_1_0 createMetaData(List<QpidByteBuffer> bufs)
+        public MessageMetaData_1_0 createMetaData(QpidByteBuffer buf)
         {
             try
             {
-                if (!QpidByteBufferUtils.hasRemaining(bufs))
+                if (!buf.hasRemaining())
                 {
                     throw new ConnectionScopedRuntimeException("No metadata found");
                 }
 
-                byte versionByte = 0;
-                for (final QpidByteBuffer buf : bufs)
-                {
-                    if (buf.hasRemaining())
-                    {
-                        versionByte = buf.get(buf.position());
-                        break;
-                    }
-                }
+                byte versionByte = buf.get(buf.position());
 
                 long arrivalTime;
                 long contentSize = 0;
                 if (versionByte == 1)
                 {
-                    if (!QpidByteBufferUtils.hasRemaining(bufs, 17))
+                    if (!buf.hasRemaining(17))
                     {
                         throw new ConnectionScopedRuntimeException("Cannot decode stored message meta data.");
                     }
                     // we can discard the first byte
-                    QpidByteBufferUtils.get(bufs);
-                    arrivalTime = QpidByteBufferUtils.getLong(bufs);
-                    contentSize = QpidByteBufferUtils.getLong(bufs);
+                    buf.get();
+                    arrivalTime = buf.getLong();
+                    contentSize = buf.getLong();
                 }
                 else if (versionByte == 0)
                 {
@@ -460,7 +451,7 @@ public class MessageMetaData_1_0 implements StorableMessageMetaData
 
                 SectionDecoder sectionDecoder = new SectionDecoderImpl(_typeRegistry.getSectionDecoderRegistry());
 
-                List<EncodingRetainingSection<?>> sections = sectionDecoder.parseAll(bufs);
+                List<EncodingRetainingSection<?>> sections = sectionDecoder.parseAll(buf);
 
                 if (versionByte == 0)
                 {

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Message_1_0.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Message_1_0.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Message_1_0.java
index 50fd0f3..e02f24a 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Message_1_0.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Message_1_0.java
@@ -22,14 +22,11 @@ package org.apache.qpid.server.protocol.v1_0;
 
 
 import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
 import java.util.List;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.AbstractServerMessageImpl;
 import org.apache.qpid.server.model.Queue;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.messaging.SectionDecoder;
 import org.apache.qpid.server.protocol.v1_0.messaging.SectionDecoderImpl;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
@@ -144,12 +141,6 @@ public class Message_1_0 extends AbstractServerMessageImpl<Message_1_0, MessageM
         return resource instanceof Queue && ((Queue<?>)resource).isHoldOnPublishEnabled();
     }
 
-
-    public Collection<QpidByteBuffer> getFragments()
-    {
-        return getContent(0, (int) getSize());
-    }
-
     public HeaderSection getHeaderSection()
     {
         return getMessageMetaData().getHeaderSection();
@@ -181,7 +172,7 @@ public class Message_1_0 extends AbstractServerMessageImpl<Message_1_0, MessageM
     }
 
     @Override
-    public Collection<QpidByteBuffer> getContent(final int offset, final int length)
+    public QpidByteBuffer getContent(final int offset, final int length)
     {
         if(getMessageMetaData().getVersion() == 0)
         {
@@ -189,15 +180,12 @@ public class Message_1_0 extends AbstractServerMessageImpl<Message_1_0, MessageM
 
             try
             {
-                final Collection<QpidByteBuffer> allSectionsContent = super.getContent(0, Integer.MAX_VALUE);
-
-                List<EncodingRetainingSection<?>> sections = sectionDecoder.parseAll(new ArrayList<>(allSectionsContent));
-
-                List<QpidByteBuffer> bodySectionContent = new ArrayList<>();
-                for(QpidByteBuffer buf : allSectionsContent)
+                List<EncodingRetainingSection<?>> sections;
+                try (QpidByteBuffer allSectionsContent = super.getContent())
                 {
-                    buf.dispose();
+                    sections = sectionDecoder.parseAll(allSectionsContent);
                 }
+                List<QpidByteBuffer> bodySectionContent = new ArrayList<>();
 
                 for (final EncodingRetainingSection<?> section : sections)
                 {
@@ -205,44 +193,14 @@ public class Message_1_0 extends AbstractServerMessageImpl<Message_1_0, MessageM
                         || section instanceof AmqpValueSection
                         || section instanceof AmqpSequenceSection)
                     {
-                        bodySectionContent.addAll(section.getEncodedForm());
+                        bodySectionContent.add(section.getEncodedForm());
                     }
                     section.dispose();
                 }
-                if(offset == 0 && length >= QpidByteBufferUtils.remaining(bodySectionContent))
-                {
-                    return bodySectionContent;
-                }
-                else
+                try (QpidByteBuffer bodyContent = QpidByteBuffer.concatenate(bodySectionContent))
                 {
-                    final Collection<QpidByteBuffer> contentView = new ArrayList<>();
-                    int position = 0;
-                    for(QpidByteBuffer buf :bodySectionContent)
-                    {
-                        if (position < offset)
-                        {
-                            if (offset - position < buf.remaining())
-                            {
-                                QpidByteBuffer view = buf.view(offset - position,
-                                                               Math.min(length, buf.remaining() - (offset - position)));
-                                contentView.add(view);
-                                position += view.remaining();
-                            }
-                            else
-                            {
-                                position += buf.remaining();
-                            }
-                        }
-                        else if (position <= offset + length)
-                        {
-                            QpidByteBuffer view = buf.view(0, Math.min(length - (position - offset), buf.remaining()));
-                            contentView.add(view);
-                            position += view.remaining();
-                        }
-
-                        buf.dispose();
-                    }
-                    return contentView;
+                    bodySectionContent.forEach(QpidByteBuffer::dispose);
+                    return bodyContent.view(offset, length);
                 }
             }
             catch (AmqpErrorException e)

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Session_1_0.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Session_1_0.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Session_1_0.java
index 6156a57..753fcec 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Session_1_0.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/Session_1_0.java
@@ -50,7 +50,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.exchange.ExchangeDefaults;
 import org.apache.qpid.server.logging.LogMessage;
 import org.apache.qpid.server.logging.LogSubject;
@@ -286,10 +285,9 @@ public class Session_1_0 extends AbstractAMQPSession<Session_1_0, ConsumerTarget
         }
 
         _remoteIncomingWindow--;
-        List<QpidByteBuffer> payload = xfr.getPayload();
-        try
+        try (QpidByteBuffer payload = xfr.getPayload())
         {
-            long remaining = payload == null ? 0 : QpidByteBufferUtils.remaining(payload);
+            long remaining = payload == null ? 0 : (long) payload.remaining();
             int payloadSent = _connection.sendFrame(_sendingChannel, xfr, payload);
             if(payload != null)
             {
@@ -305,7 +303,7 @@ public class Session_1_0 extends AbstractAMQPSession<Session_1_0, ConsumerTarget
                     _nextOutgoingId.incr();
                     _remoteIncomingWindow--;
 
-                    remaining = QpidByteBufferUtils.remaining(payload);
+                    remaining = (long) payload.remaining();
                     payloadSent = _connection.sendFrame(_sendingChannel, continuationTransfer, payload);
 
                     continuationTransfer.dispose();
@@ -316,16 +314,6 @@ public class Session_1_0 extends AbstractAMQPSession<Session_1_0, ConsumerTarget
         {
             throw new ConnectionScopedRuntimeException(e);
         }
-        finally
-        {
-            if(payload != null)
-            {
-                for (QpidByteBuffer buf : payload)
-                {
-                    buf.dispose();
-                }
-            }
-        }
     }
 
     public boolean isActive()

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/StandardReceivingLinkEndpoint.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/StandardReceivingLinkEndpoint.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/StandardReceivingLinkEndpoint.java
index 99ce73a..f8f12aa 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/StandardReceivingLinkEndpoint.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/StandardReceivingLinkEndpoint.java
@@ -156,10 +156,9 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
             MessageFormat format = MessageFormatRegistry.getFormat(messageFormat.intValue());
             if(format != null)
             {
-                List<QpidByteBuffer> fragments = delivery.getPayload();
-                try
+                try (QpidByteBuffer payload = delivery.getPayload())
                 {
-                    serverMessage = format.createMessage(fragments,
+                    serverMessage = format.createMessage(payload,
                                                          getAddressSpace().getMessageStore(),
                                                          getSession().getConnection().getReference());
                 }
@@ -167,14 +166,6 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
                 {
                     return e.getCause().getError();
                 }
-                finally
-                {
-                    for(QpidByteBuffer fragment: fragments)
-                    {
-                        fragment.dispose();
-                    }
-                    fragments = null;
-                }
             }
             else
             {

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/TxnCoordinatorReceivingLinkEndpoint.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/TxnCoordinatorReceivingLinkEndpoint.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/TxnCoordinatorReceivingLinkEndpoint.java
index afab510..0f98e0b 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/TxnCoordinatorReceivingLinkEndpoint.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/TxnCoordinatorReceivingLinkEndpoint.java
@@ -67,74 +67,77 @@ public class TxnCoordinatorReceivingLinkEndpoint extends AbstractReceivingLinkEn
     @Override
     protected Error receiveDelivery(Delivery delivery)
     {
-        List<QpidByteBuffer> payload = delivery.getPayload();
-
-
-
         // Only interested in the amqp-value section that holds the message to the coordinator
-        try
+        try (QpidByteBuffer payload = delivery.getPayload())
         {
             List<EncodingRetainingSection<?>> sections = getSectionDecoder().parseAll(payload);
             boolean amqpValueSectionFound = false;
             for(EncodingRetainingSection section : sections)
             {
-                if(section instanceof AmqpValueSection)
+                try
                 {
-                    if (amqpValueSectionFound)
-                    {
-                        throw new ConnectionScopedRuntimeException("Received more than one AmqpValue sections");
-                    }
-                    amqpValueSectionFound = true;
-                    Object command = section.getValue();
-
-                    Session_1_0 session = getSession();
-                    if(command instanceof Declare)
+                    if (section instanceof AmqpValueSection)
                     {
-                        final IdentifiedTransaction txn = session.getConnection().createIdentifiedTransaction();
-                        _createdTransactions.put(txn.getId(), txn.getServerTransaction());
+                        if (amqpValueSectionFound)
+                        {
+                            throw new ConnectionScopedRuntimeException("Received more than one AmqpValue sections");
+                        }
+                        amqpValueSectionFound = true;
+                        Object command = section.getValue();
 
-                        Declared state = new Declared();
+                        Session_1_0 session = getSession();
+                        if (command instanceof Declare)
+                        {
+                            final IdentifiedTransaction txn = session.getConnection().createIdentifiedTransaction();
+                            _createdTransactions.put(txn.getId(), txn.getServerTransaction());
 
-                        session.incrementStartedTransactions();
+                            Declared state = new Declared();
 
-                        state.setTxnId(Session_1_0.integerToTransactionId(txn.getId()));
-                        updateDisposition(delivery.getDeliveryTag(), state, true);
+                            session.incrementStartedTransactions();
 
-                    }
-                    else if(command instanceof Discharge)
-                    {
-                        Discharge discharge = (Discharge) command;
-
-                        Error error = discharge(discharge.getTxnId(), Boolean.TRUE.equals(discharge.getFail()));
-                        final DeliveryState outcome;
-                        if (error == null)
-                        {
-                            outcome = new Accepted();
+                            state.setTxnId(Session_1_0.integerToTransactionId(txn.getId()));
+                            updateDisposition(delivery.getDeliveryTag(), state, true);
                         }
-                        else if (Arrays.asList(getSource().getOutcomes()).contains(Rejected.REJECTED_SYMBOL))
+                        else if (command instanceof Discharge)
                         {
-                            final Rejected rejected = new Rejected();
-                            rejected.setError(error);
-                            outcome = rejected;
-                            error = null;
+                            Discharge discharge = (Discharge) command;
+
+                            Error error = discharge(discharge.getTxnId(), Boolean.TRUE.equals(discharge.getFail()));
+                            final DeliveryState outcome;
+                            if (error == null)
+                            {
+                                outcome = new Accepted();
+                            }
+                            else if (Arrays.asList(getSource().getOutcomes()).contains(Rejected.REJECTED_SYMBOL))
+                            {
+                                final Rejected rejected = new Rejected();
+                                rejected.setError(error);
+                                outcome = rejected;
+                                error = null;
+                            }
+                            else
+                            {
+                                outcome = null;
+                            }
+
+                            if (error == null)
+                            {
+                                updateDisposition(delivery.getDeliveryTag(), outcome, true);
+                            }
+                            return error;
                         }
                         else
                         {
-                            outcome = null;
+                            throw new ConnectionScopedRuntimeException(String.format("Received unknown command '%s'",
+                                                                                     command.getClass()
+                                                                                            .getSimpleName()));
                         }
-
-                        if (error == null)
-                        {
-                            updateDisposition(delivery.getDeliveryTag(), outcome, true);
-                        }
-                        return error;
-                    }
-                    else
-                    {
-                        throw new ConnectionScopedRuntimeException(String.format("Received unknown command '%s'",
-                                                                                 command.getClass().getSimpleName()));
                     }
                 }
+                finally
+                {
+                    section.dispose();
+                }
             }
             if (!amqpValueSectionFound)
             {
@@ -145,13 +148,6 @@ public class TxnCoordinatorReceivingLinkEndpoint extends AbstractReceivingLinkEn
         {
             return e.getError();
         }
-        finally
-        {
-            for(QpidByteBuffer buf : payload)
-            {
-                buf.dispose();
-            }
-        }
         return null;
     }
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/AbstractCompositeTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/AbstractCompositeTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/AbstractCompositeTypeConstructor.java
index 00a1252..1b159f6 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/AbstractCompositeTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/AbstractCompositeTypeConstructor.java
@@ -22,11 +22,9 @@ package org.apache.qpid.server.protocol.v1_0.codec;
 
 
 import java.lang.reflect.Array;
-import java.util.List;
 import java.util.Map;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 import org.apache.qpid.server.protocol.v1_0.type.transport.Error;
@@ -35,8 +33,8 @@ public abstract class AbstractCompositeTypeConstructor<T> implements DescribedTy
 {
     @Override
     public TypeConstructor<T> construct(final Object descriptor,
-                                        final List<QpidByteBuffer> in,
-                                        final int[] originalPositions,
+                                        final QpidByteBuffer in,
+                                        final int originalPosition,
                                         final ValueHandler valueHandler) throws AmqpErrorException
     {
         return new FieldValueReader();
@@ -48,12 +46,12 @@ public abstract class AbstractCompositeTypeConstructor<T> implements DescribedTy
 
     protected class FieldValueReader implements TypeConstructor<T>
     {
-        private List<QpidByteBuffer> _in;
+        private QpidByteBuffer _in;
         private ValueHandler _valueHandler;
         private int _count;
 
         @Override
-        public T construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+        public T construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
         {
             _in = in;
             _valueHandler = handler;
@@ -64,7 +62,7 @@ public abstract class AbstractCompositeTypeConstructor<T> implements DescribedTy
         {
             int size;
             final TypeConstructor typeConstructor = _valueHandler.readConstructor(_in);
-            long remaining = QpidByteBufferUtils.remaining(_in);
+            long remaining = _in.remaining();
             if (typeConstructor instanceof ListConstructor)
             {
                 ListConstructor listConstructor = (ListConstructor) typeConstructor;
@@ -80,13 +78,13 @@ public abstract class AbstractCompositeTypeConstructor<T> implements DescribedTy
 
                 if (listConstructor.getSize() == 1)
                 {
-                    size = QpidByteBufferUtils.get(_in) & 0xFF;
-                    _count = QpidByteBufferUtils.get(_in) & 0xFF;
+                    size = _in.getUnsignedByte();
+                    _count = _in.getUnsignedByte();
                 }
                 else
                 {
-                    size = QpidByteBufferUtils.getInt(_in);
-                    _count = QpidByteBufferUtils.getInt(_in);
+                    size = _in.getInt();
+                    _count = _in.getInt();
                 }
 
                 remaining -= listConstructor.getSize();
@@ -115,7 +113,7 @@ public abstract class AbstractCompositeTypeConstructor<T> implements DescribedTy
             final T constructedObject = AbstractCompositeTypeConstructor.this.construct(this);
 
             long expectedRemaining = remaining - size;
-            long unconsumedBytes = QpidByteBufferUtils.remaining(_in) - expectedRemaining;
+            long unconsumedBytes = _in.remaining() - expectedRemaining;
             if(unconsumedBytes > 0)
             {
                 final String msg =

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/AbstractDescribedTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/AbstractDescribedTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/AbstractDescribedTypeConstructor.java
index 7b1cda6..4dc50f1 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/AbstractDescribedTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/AbstractDescribedTypeConstructor.java
@@ -20,8 +20,6 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 
@@ -29,8 +27,8 @@ public abstract class AbstractDescribedTypeConstructor<T> implements DescribedTy
 {
     @Override
     public TypeConstructor<T> construct(final Object descriptor,
-                                        final List<QpidByteBuffer> in,
-                                        final int[] originalPositions, final ValueHandler valueHandler)
+                                        final QpidByteBuffer in,
+                                        final int originalPosition, final ValueHandler valueHandler)
             throws AmqpErrorException
     {
         return new TypeConstructorFromUnderlying<>(this, valueHandler.readConstructor(in));
@@ -52,7 +50,7 @@ public abstract class AbstractDescribedTypeConstructor<T> implements DescribedTy
         }
 
         @Override
-        public S construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+        public S construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
         {
             return _describedTypeConstructor.construct(_describedConstructor.construct(in, handler));
         }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ArrayTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ArrayTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ArrayTypeConstructor.java
index 3c75d96..f4ae161 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ArrayTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ArrayTypeConstructor.java
@@ -23,7 +23,6 @@ import java.util.ArrayList;
 import java.util.List;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 
@@ -32,10 +31,10 @@ public abstract class ArrayTypeConstructor implements TypeConstructor<Object[]>
 
 
     @Override
-    public Object[] construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public Object[] construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
         int size = read(in);
-        long remaining = QpidByteBufferUtils.remaining(in);
+        long remaining = in.remaining();
         if(remaining < (long) size)
         {
             throw new AmqpErrorException(AmqpError.DECODE_ERROR,
@@ -53,7 +52,7 @@ public abstract class ArrayTypeConstructor implements TypeConstructor<Object[]>
         }
 
         long expectedRemaining = remaining - size;
-        long unconsumedBytes = QpidByteBufferUtils.remaining(in) - expectedRemaining;
+        long unconsumedBytes = in.remaining() - expectedRemaining;
         if(unconsumedBytes > 0)
         {
             final String msg = String.format("Array incorrectly encoded, %d bytes remaining after decoding %d elements",
@@ -81,7 +80,6 @@ public abstract class ArrayTypeConstructor implements TypeConstructor<Object[]>
 
 
     abstract int read(QpidByteBuffer in) throws AmqpErrorException;
-    abstract int read(List<QpidByteBuffer> in) throws AmqpErrorException;
 
 
     private static final ArrayTypeConstructor ONE_BYTE_SIZE_ARRAY = new ArrayTypeConstructor()
@@ -95,16 +93,6 @@ public abstract class ArrayTypeConstructor implements TypeConstructor<Object[]>
             }
             return ((int)in.get()) & 0xff;
         }
-
-        @Override
-        int read(final List<QpidByteBuffer> in) throws AmqpErrorException
-        {
-            if(!QpidByteBufferUtils.hasRemaining(in))
-            {
-                throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Insufficient data to decode array");
-            }
-            return ((int)QpidByteBufferUtils.get(in)) & 0xff;
-        }
     };
 
     private static final ArrayTypeConstructor FOUR_BYTE_SIZE_ARRAY = new ArrayTypeConstructor()
@@ -118,15 +106,6 @@ public abstract class ArrayTypeConstructor implements TypeConstructor<Object[]>
             }
             return in.getInt();
         }
-        @Override
-        int read(final List<QpidByteBuffer> in) throws AmqpErrorException
-        {
-            if(!QpidByteBufferUtils.hasRemaining(in,4))
-            {
-                throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Insufficient data to decode array");
-            }
-            return QpidByteBufferUtils.getInt(in);
-        }
     };
 
     public static ArrayTypeConstructor getOneByteSizeTypeConstructor()

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/BinaryTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/BinaryTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/BinaryTypeConstructor.java
index 3ab576e..cda7f69 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/BinaryTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/BinaryTypeConstructor.java
@@ -20,10 +20,7 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.Binary;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
@@ -45,32 +42,32 @@ public class BinaryTypeConstructor extends VariableWidthTypeConstructor<Binary>
     }
 
     @Override
-    public Binary construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public Binary construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
 
         int size;
 
-        if (!QpidByteBufferUtils.hasRemaining(in, getSize()))
+        if (!in.hasRemaining(getSize()))
         {
             throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Cannot construct binary: insufficient input data");
         }
 
         if (getSize() == 1)
         {
-            size = QpidByteBufferUtils.get(in) & 0xFF;
+            size = in.getUnsignedByte();
         }
         else
         {
-            size = QpidByteBufferUtils.getInt(in);
+            size = in.getInt();
         }
 
-        if (!QpidByteBufferUtils.hasRemaining(in, size))
+        if (!in.hasRemaining(size))
         {
             throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Cannot construct binary: insufficient input data");
         }
 
         byte[] data = new byte[size];
-        QpidByteBufferUtils.get(in, data);
+        in.get(data);
         return new Binary(data);
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/BooleanConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/BooleanConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/BooleanConstructor.java
index 38fda60..ca49996 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/BooleanConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/BooleanConstructor.java
@@ -19,12 +19,9 @@
 
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
+import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
-import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 
 public class BooleanConstructor
 {
@@ -32,7 +29,7 @@ public class BooleanConstructor
     {
 
         @Override
-        public Boolean construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+        public Boolean construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
         {
             return Boolean.TRUE;
         }
@@ -42,7 +39,7 @@ public class BooleanConstructor
         {
 
             @Override
-            public Boolean construct(final List<QpidByteBuffer> in, final ValueHandler handler)
+            public Boolean construct(final QpidByteBuffer in, final ValueHandler handler)
                     throws AmqpErrorException
             {
                 return Boolean.FALSE;
@@ -52,11 +49,11 @@ public class BooleanConstructor
     {
 
         @Override
-        public Boolean construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+        public Boolean construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
         {
-            if(QpidByteBufferUtils.hasRemaining(in))
+            if (in.hasRemaining())
             {
-                byte b = QpidByteBufferUtils.get(in);
+                byte b = in.get();
                 return b != (byte) 0;
             }
             else

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ByteTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ByteTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ByteTypeConstructor.java
index 47213cd..78feca7 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ByteTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ByteTypeConstructor.java
@@ -20,10 +20,7 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 
@@ -41,11 +38,11 @@ public class ByteTypeConstructor implements TypeConstructor<Byte>
     }
 
     @Override
-    public Byte construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public Byte construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
-        if(QpidByteBufferUtils.hasRemaining(in))
+        if (in.hasRemaining())
         {
-            return QpidByteBufferUtils.get(in);
+            return in.get();
         }
         else
         {

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/CharTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/CharTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/CharTypeConstructor.java
index 5f7a1ab..a6727a1 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/CharTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/CharTypeConstructor.java
@@ -20,12 +20,9 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
-import org.apache.qpid.server.protocol.v1_0.type.*;
-import org.apache.qpid.server.protocol.v1_0.type.transport.*;
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
+import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
+import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 
 public class CharTypeConstructor implements TypeConstructor<String>
 {
@@ -42,11 +39,11 @@ public class CharTypeConstructor implements TypeConstructor<String>
     }
 
     @Override
-    public String construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public String construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
-        if(QpidByteBufferUtils.hasRemaining(in, 4))
+        if (in.hasRemaining(4))
         {
-            int codePoint = QpidByteBufferUtils.getInt(in);
+            int codePoint = in.getInt(); // TODO look wrong AMQP 1.0 type is actually UTF-32BE not a code point
             char[] chars = Character.toChars(codePoint);
             return new String(chars);
         }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/DecimalConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/DecimalConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/DecimalConstructor.java
index f996de1..cf91f99 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/DecimalConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/DecimalConstructor.java
@@ -20,10 +20,8 @@
 package org.apache.qpid.server.protocol.v1_0.codec;
 
 import java.math.BigDecimal;
-import java.util.List;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 
@@ -34,13 +32,13 @@ public abstract class DecimalConstructor implements TypeConstructor<BigDecimal>
     {
 
         @Override
-        public BigDecimal construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+        public BigDecimal construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
         {
             int val;
 
-            if(QpidByteBufferUtils.hasRemaining(in, 4))
+            if (in.hasRemaining(4))
             {
-                val = QpidByteBufferUtils.getInt(in);
+                val = in.getInt();
             }
             else
             {
@@ -57,13 +55,13 @@ public abstract class DecimalConstructor implements TypeConstructor<BigDecimal>
     {
 
         @Override
-        public BigDecimal construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+        public BigDecimal construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
         {
             long val;
 
-            if(QpidByteBufferUtils.hasRemaining(in, 8))
+            if (in.hasRemaining(8))
             {
-                val = QpidByteBufferUtils.getLong(in);
+                val = in.getLong();
             }
             else
             {
@@ -80,16 +78,16 @@ public abstract class DecimalConstructor implements TypeConstructor<BigDecimal>
     {
 
         @Override
-        public BigDecimal construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+        public BigDecimal construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
         {
 
             long high;
             long low;
 
-            if(QpidByteBufferUtils.hasRemaining(in, 16))
+            if (in.hasRemaining(16))
             {
-                high = QpidByteBufferUtils.getLong(in);
-                low = QpidByteBufferUtils.getLong(in);
+                high = in.getLong();
+                low = in.getLong();
             }
             else
             {

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/DescribedTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/DescribedTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/DescribedTypeConstructor.java
index 99bba13..788dcb0 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/DescribedTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/DescribedTypeConstructor.java
@@ -20,15 +20,13 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 
 public interface DescribedTypeConstructor<T>
 {
     TypeConstructor<T> construct(Object descriptor,
-                                 List<QpidByteBuffer> in,
-                                 final int[] originalPositions,
+                                 QpidByteBuffer in,
+                                 final int originalPosition,
                                  ValueHandler valueHandler) throws AmqpErrorException;
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/DoubleTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/DoubleTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/DoubleTypeConstructor.java
index aaaef75..d874cff 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/DoubleTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/DoubleTypeConstructor.java
@@ -20,10 +20,7 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 
@@ -42,11 +39,11 @@ public class DoubleTypeConstructor implements TypeConstructor<Double>
     }
 
     @Override
-    public Double construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public Double construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
-        if(QpidByteBufferUtils.hasRemaining(in, 8))
+        if (in.hasRemaining(8))
         {
-            return QpidByteBufferUtils.getDouble(in);
+            return in.getDouble();
         }
         else
         {

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/FloatTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/FloatTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/FloatTypeConstructor.java
index 9c8c88e..dc529c3 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/FloatTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/FloatTypeConstructor.java
@@ -20,10 +20,7 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 
@@ -42,11 +39,11 @@ public class FloatTypeConstructor implements TypeConstructor<Float>
     }
 
     @Override
-    public Float construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public Float construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
-        if(QpidByteBufferUtils.hasRemaining(in, 4))
+        if (in.hasRemaining(4))
         {
-            return QpidByteBufferUtils.getFloat(in);
+            return in.getFloat();
         }
         else
         {


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[06/10] qpid-broker-j git commit: QPID-7832: [Java Broker] Refactor store/protocol API using Collection

Posted by lq...@apache.org.
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerDisassembler.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerDisassembler.java b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerDisassembler.java
index 25eb871..fd2ffaa 100644
--- a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerDisassembler.java
+++ b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerDisassembler.java
@@ -27,15 +27,11 @@ import static org.apache.qpid.server.protocol.v0_10.transport.Frame.HEADER_SIZE;
 import static org.apache.qpid.server.protocol.v0_10.transport.Frame.LAST_FRAME;
 import static org.apache.qpid.server.protocol.v0_10.transport.Frame.LAST_SEG;
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.transport.ByteBufferSender;
+import org.apache.qpid.server.protocol.v0_10.transport.Frame;
 import org.apache.qpid.server.protocol.v0_10.transport.Header;
 import org.apache.qpid.server.protocol.v0_10.transport.Method;
 import org.apache.qpid.server.protocol.v0_10.transport.ProtocolDelegate;
@@ -44,7 +40,7 @@ import org.apache.qpid.server.protocol.v0_10.transport.ProtocolEvent;
 import org.apache.qpid.server.protocol.v0_10.transport.ProtocolHeader;
 import org.apache.qpid.server.protocol.v0_10.transport.SegmentType;
 import org.apache.qpid.server.protocol.v0_10.transport.Struct;
-import org.apache.qpid.server.protocol.v0_10.transport.Frame;
+import org.apache.qpid.server.transport.ByteBufferSender;
 
 /**
  * Disassembler
@@ -94,58 +90,36 @@ public final class ServerDisassembler implements ProtocolEventSender, ProtocolDe
         }
     }
 
-    private void frame(byte flags, byte type, byte track, int channel, int size, Collection<QpidByteBuffer> buffers)
+    private void frame(byte flags, byte type, byte track, int channel, int size, QpidByteBuffer buffer)
     {
-        QpidByteBuffer data = QpidByteBuffer.allocateDirect(HEADER_SIZE);
-
-        data.put(0, flags);
-        data.put(1, type);
-        data.putShort(2, (short) (size + HEADER_SIZE));
-        data.put(4, (byte) 0);
-        data.put(5, track);
-        data.putShort(6, (short) channel);
-
-
-        _sender.send(data);
-        data.dispose();
+        try (QpidByteBuffer data = QpidByteBuffer.allocateDirect(HEADER_SIZE))
+        {
+            data.put(0, flags);
+            data.put(1, type);
+            data.putShort(2, (short) (size + HEADER_SIZE));
+            data.put(4, (byte) 0);
+            data.put(5, track);
+            data.putShort(6, (short) channel);
+            _sender.send(data);
+        }
 
         if(size > 0)
         {
-            int residual = size;
-            for(QpidByteBuffer b : buffers)
+            try (QpidByteBuffer view = buffer.view(0, size))
             {
-                final int remaining = b.remaining();
-                if(remaining > 0 )
-                {
-                    if(remaining >= residual)
-                    {
-                        final QpidByteBuffer buffer = b.view(0, residual);
-                        _sender.send(buffer);
-                        buffer.dispose();
-                        b.position(b.position() + residual);
-                        break;
-                    }
-                    else
-                    {
-                        _sender.send(b);
-                        residual-=remaining;
-                    }
-                }
+                _sender.send(view);
+                buffer.position(buffer.position() + size);
             }
         }
 
     }
 
-    private void fragment(byte flags, SegmentType type, ProtocolEvent event, Collection<QpidByteBuffer> buffers)
+    private void fragment(byte flags, SegmentType type, ProtocolEvent event, QpidByteBuffer buffer)
     {
         byte typeb = (byte) type.getValue();
         byte track = event.getEncodedTrack() == Frame.L4 ? (byte) 1 : (byte) 0;
 
-        int remaining = 0;
-        for(QpidByteBuffer b : buffers)
-        {
-            remaining += b.remaining();
-        }
+        int remaining = buffer.remaining();
         boolean first = true;
         while (true)
         {
@@ -163,7 +137,7 @@ public final class ServerDisassembler implements ProtocolEventSender, ProtocolDe
                 newflags |= LAST_FRAME;
             }
 
-            frame(newflags, typeb, track, event.getChannel(), size, buffers);
+            frame(newflags, typeb, track, event.getChannel(), size, buffer);
 
             if (remaining == 0)
             {
@@ -245,42 +219,33 @@ public final class ServerDisassembler implements ProtocolEventSender, ProtocolDe
         }
         synchronized (_sendLock)
         {
-            final QpidByteBuffer buf = enc.getBuffer();
-
-            QpidByteBuffer duplicate = buf.view(0, methodLimit);
-            fragment(flags, type, method, Collections.singletonList(duplicate));
-            duplicate.dispose();
-
-            if (payload)
+            try (QpidByteBuffer buf = enc.getBuffer())
             {
-                Collection<QpidByteBuffer> body = method.getBody();
-                buf.limit(headerLimit);
-                buf.position(methodLimit);
-
-                duplicate = buf.slice();
-                fragment(body == null ? LAST_SEG : 0x0,
-                         SegmentType.HEADER,
-                         method,
-                         Collections.singletonList(duplicate));
-                duplicate.dispose();
+                try (QpidByteBuffer duplicate = buf.view(0, methodLimit))
+                {
+                    fragment(flags, type, method, duplicate);
+                }
 
-                if (body != null)
+                if (payload)
                 {
-                    Collection<QpidByteBuffer> dup = new ArrayList<>(body.size());
-                    for(QpidByteBuffer b : body)
+                    QpidByteBuffer body = method.getBody();
+                    buf.limit(headerLimit);
+                    buf.position(methodLimit);
+
+                    try (QpidByteBuffer slice = buf.slice())
                     {
-                        dup.add(b.duplicate());
+                        fragment(body == null ? LAST_SEG : 0x0, SegmentType.HEADER, method, slice);
                     }
-                    fragment(LAST_SEG, SegmentType.BODY, method, dup);
-                    for(QpidByteBuffer b : dup)
+
+                    if (body != null)
                     {
-                        b.dispose();
+                        try (QpidByteBuffer dup = body.duplicate())
+                        {
+                            fragment(LAST_SEG, SegmentType.BODY, method, dup);
+                        }
                     }
-
                 }
-
             }
-            buf.dispose();
         }
     }
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSessionDelegate.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSessionDelegate.java b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSessionDelegate.java
index 087d853..fa37c17 100644
--- a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSessionDelegate.java
+++ b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSessionDelegate.java
@@ -557,13 +557,10 @@ public class ServerSessionDelegate extends MethodDelegate<ServerSession> impleme
                                                                    final MessageMetaData_0_10 messageMetaData, final MessageStore store)
     {
         final MessageHandle<MessageMetaData_0_10> addedMessage = store.addMessage(messageMetaData);
-        Collection<QpidByteBuffer> body = xfr.getBody();
+        QpidByteBuffer body = xfr.getBody();
         if(body != null)
         {
-            for(QpidByteBuffer b : body)
-            {
-                addedMessage.addContent(b);
-            }
+            addedMessage.addContent(body);
         }
         final StoredMessage<MessageMetaData_0_10> storedMessage = addedMessage.allContentAdded();
         return storedMessage;

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java
index 7494bda..8602e7b 100644
--- a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java
+++ b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/MessageTransfer.java
@@ -22,17 +22,11 @@
 package org.apache.qpid.server.protocol.v0_10.transport;
 
 
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
 import java.util.LinkedHashMap;
-import java.util.List;
 import java.util.Map;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 
-import org.apache.qpid.server.util.Strings;
-
 
 public final class MessageTransfer extends Method {
 
@@ -75,7 +69,7 @@ public final class MessageTransfer extends Method {
     private MessageAcceptMode acceptMode;
     private MessageAcquireMode acquireMode;
     private Header header;
-    private Collection<QpidByteBuffer> _body;
+    private QpidByteBuffer _body;
 
 
     public MessageTransfer() {}
@@ -86,11 +80,11 @@ public final class MessageTransfer extends Method {
              acceptMode,
              acquireMode,
              header,
-             Collections.singletonList(QpidByteBuffer.wrap(body)),
+             QpidByteBuffer.wrap(body),
              options);
     }
 
-    public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, Collection<QpidByteBuffer> body, Option ... _options) {
+    public MessageTransfer(String destination, MessageAcceptMode acceptMode, MessageAcquireMode acquireMode, Header header, QpidByteBuffer body, Option ... _options) {
         if(destination != null) {
             setDestination(destination);
         }
@@ -210,41 +204,34 @@ public final class MessageTransfer extends Method {
         this.header = header;
     }
 
-    public final MessageTransfer header(Header header) {
+    public final MessageTransfer header(Header header)
+    {
         setHeader(header);
         return this;
     }
 
     @Override
-    public final Collection<QpidByteBuffer> getBody() {
-        if (this._body == null)
-        {
-            return null;
-        }
-        else
-        {
-            return Collections.unmodifiableCollection(_body);
-        }
+    public final QpidByteBuffer getBody()
+    {
+        return _body;
     }
 
     @Override
-    public final void setBody(Collection<QpidByteBuffer> body)
+    public final void setBody(QpidByteBuffer body)
     {
         if (body == null)
         {
             _bodySize = 0;
+            if (_body != null)
+            {
+                _body.dispose();
+            }
             _body = null;
         }
         else
         {
-            _body = new ArrayList<>(body.size());
-            int size = 0;
-            for (QpidByteBuffer buf : body)
-            {
-                size += buf.remaining();
-                _body.add(buf.duplicate());
-            }
-            _bodySize = size;
+            _body = body.duplicate();
+            _bodySize = _body.remaining();
         }
     }
 
@@ -254,36 +241,6 @@ public final class MessageTransfer extends Method {
         return _bodySize;
     }
 
-    public final MessageTransfer body(List<QpidByteBuffer> body)
-    {
-        setBody(body);
-        return this;
-    }
-
-    public final byte[] getBodyBytes() {
-        Collection<QpidByteBuffer> body = getBody();
-        byte[] bytes = new byte[getBodySize()];
-        for(QpidByteBuffer buf : body)
-        {
-            buf.duplicate().get(bytes);
-        }
-        return bytes;
-    }
-
-    public final void setBody(byte[] body)
-    {
-        setBody(Collections.singletonList(QpidByteBuffer.wrap(body)));
-    }
-
-    public final String getBodyString() {
-        return Strings.fromUTF8(getBodyBytes());
-    }
-
-    public final void setBody(String body) {
-        setBody(Strings.toUTF8(body));
-    }
-
-
     @Override
     public void write(Encoder enc)
     {
@@ -348,10 +305,8 @@ public final class MessageTransfer extends Method {
     {
         if (_body != null)
         {
-            for (QpidByteBuffer buf : _body)
-            {
-                buf.dispose();
-            }
+            _body.dispose();
+            _body = null;
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/Method.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/Method.java b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/Method.java
index 8fffac3..41d91be 100644
--- a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/Method.java
+++ b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/transport/Method.java
@@ -19,11 +19,9 @@
  */
 package org.apache.qpid.server.protocol.v0_10.transport;
 
-import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-
 import static org.apache.qpid.server.transport.util.Functions.str;
 
-import java.util.Collection;
+import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 
 /**
  * Method
@@ -126,12 +124,12 @@ public abstract class Method extends Struct implements ProtocolEvent
         throw new UnsupportedOperationException();
     }
 
-    public Collection<QpidByteBuffer> getBody()
+    public QpidByteBuffer getBody()
     {
         return null;
     }
 
-    public void setBody(Collection<QpidByteBuffer> body)
+    public void setBody(QpidByteBuffer body)
     {
         throw new UnsupportedOperationException();
     }
@@ -226,7 +224,7 @@ public abstract class Method extends Struct implements ProtocolEvent
                 str.append(st);
             }
         }
-        Collection<QpidByteBuffer> body = getBody();
+        QpidByteBuffer body = getBody();
         if (body != null)
         {
             str.append("\n  body=");

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_0_10_to_InternalTest.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_0_10_to_InternalTest.java b/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_0_10_to_InternalTest.java
index 5a28f4f..6931f9c 100644
--- a/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_0_10_to_InternalTest.java
+++ b/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_0_10_to_InternalTest.java
@@ -38,8 +38,6 @@ import java.util.UUID;
 
 import com.google.common.collect.Lists;
 import org.mockito.ArgumentCaptor;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.AMQMessageHeader;
@@ -323,15 +321,8 @@ public class MessageConverter_0_10_to_InternalTest extends QpidTestCase
         final ArgumentCaptor<Integer> sizeCaptor = ArgumentCaptor.forClass(Integer.class);
 
         when(_handle.getContent(offsetCaptor.capture(),
-                                sizeCaptor.capture())).then(new Answer<Collection<QpidByteBuffer>>()
-        {
-            @Override
-            public Collection<QpidByteBuffer> answer(final InvocationOnMock invocation) throws Throwable
-            {
-                final QpidByteBuffer view = combined.view(offsetCaptor.getValue(), sizeCaptor.getValue());
-                return Collections.singleton(view);
-            }
-        });
+                                sizeCaptor.capture())).then(invocation -> combined.view(offsetCaptor.getValue(),
+                                                                                        sizeCaptor.getValue()));
     }
 
     private void doTestTextMessage(final String originalContent, final String mimeType) throws Exception

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_Internal_to_0_10Test.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_Internal_to_0_10Test.java b/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_Internal_to_0_10Test.java
index aeb9a79..ff77f9a 100644
--- a/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_Internal_to_0_10Test.java
+++ b/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/MessageConverter_Internal_to_0_10Test.java
@@ -25,18 +25,16 @@ import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
 import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
 import java.io.ObjectOutputStream;
 import java.io.Serializable;
 import java.util.ArrayList;
-import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
 
 import com.google.common.collect.Lists;
 import com.google.common.io.ByteStreams;
 import org.mockito.ArgumentCaptor;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.AMQMessageHeader;
@@ -237,15 +235,8 @@ public class MessageConverter_Internal_to_0_10Test extends QpidTestCase
         final ArgumentCaptor<Integer> sizeCaptor = ArgumentCaptor.forClass(Integer.class);
 
         when(_handle.getContent(offsetCaptor.capture(),
-                                sizeCaptor.capture())).then(new Answer<Collection<QpidByteBuffer>>()
-        {
-            @Override
-            public Collection<QpidByteBuffer> answer(final InvocationOnMock invocation) throws Throwable
-            {
-                final QpidByteBuffer view = combined.view(offsetCaptor.getValue(), sizeCaptor.getValue());
-                return Collections.singleton(view);
-            }
-        });
+                                sizeCaptor.capture())).then(invocation -> combined.view(offsetCaptor.getValue(),
+                                                                                        sizeCaptor.getValue()));
     }
 
     private void doTest(final Serializable messageBytes,
@@ -255,23 +246,24 @@ public class MessageConverter_Internal_to_0_10Test extends QpidTestCase
     {
         final InternalMessage sourceMessage = getAmqMessage(messageBytes, mimeType);
         final MessageTransferMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent();
 
         assertArrayEquals("Unexpected content", expectedContent != null ? expectedContent : new byte[0], getBytes(content));
         assertEquals("Unexpected content type", expectedContentType, convertedMessage.getMessageHeader().getMimeType());
     }
 
-    private byte[] getBytes(final Collection<QpidByteBuffer> content) throws Exception
+    private byte[] getBytes(final QpidByteBuffer content) throws Exception
     {
-        ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        for (QpidByteBuffer buf : content)
+        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
+             InputStream contentInputStream = content.asInputStream())
         {
-            ByteStreams.copy(buf.asInputStream(), bos);
-            buf.dispose();
+            ByteStreams.copy(contentInputStream, bos);
+            content.dispose();
+            return bos.toByteArray();
         }
-        return bos.toByteArray();
     }
 
+
     private static class MySerializable implements Serializable
     {
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/PropertyConverter_0_10_to_InternalTest.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/PropertyConverter_0_10_to_InternalTest.java b/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/PropertyConverter_0_10_to_InternalTest.java
index d6a5156..40be947 100644
--- a/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/PropertyConverter_0_10_to_InternalTest.java
+++ b/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/PropertyConverter_0_10_to_InternalTest.java
@@ -395,8 +395,12 @@ public class PropertyConverter_0_10_to_InternalTest extends QpidTestCase
         if (content != null)
         {
             when(storedMessage.getContentSize()).thenReturn(content.length);
-            when(storedMessage.getContent(0, content.length)).thenReturn(Collections.singleton(QpidByteBuffer.wrap(
-                    content)));
+            when(storedMessage.getContent(0, content.length)).thenReturn(QpidByteBuffer.wrap(content));
+        }
+        else
+        {
+            when(storedMessage.getContentSize()).thenReturn(0);
+            when(storedMessage.getContent(0, 0)).thenReturn(QpidByteBuffer.emptyQpidByteBuffer());
         }
         return new MessageTransferMessage(storedMessage, null);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/PropertyConverter_Internal_to_v0_10Test.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/PropertyConverter_Internal_to_v0_10Test.java b/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/PropertyConverter_Internal_to_v0_10Test.java
index 50723df..a490df1 100644
--- a/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/PropertyConverter_Internal_to_v0_10Test.java
+++ b/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/PropertyConverter_Internal_to_v0_10Test.java
@@ -626,8 +626,8 @@ public class PropertyConverter_Internal_to_v0_10Test extends QpidTestCase
             {
                 oos.writeObject(content);
 
-                when(storedMessage.getContent(0, contentSize)).thenReturn(Collections.singletonList(QpidByteBuffer.wrap(
-                        baos.toByteArray())));
+                when(storedMessage.getContent(0, contentSize)).thenReturn(QpidByteBuffer.wrap(
+                        baos.toByteArray()));
             }
         }
         when(storedMessage.getContentSize()).thenReturn(contentSize);

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/ServerSessionTest.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/ServerSessionTest.java b/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/ServerSessionTest.java
index a7f854b..e47f0fc 100644
--- a/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/ServerSessionTest.java
+++ b/broker-plugins/amqp-0-10-protocol/src/test/java/org/apache/qpid/server/protocol/v0_10/ServerSessionTest.java
@@ -29,25 +29,26 @@ import javax.security.auth.Subject;
 
 import com.google.common.util.concurrent.Futures;
 
+import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.configuration.updater.CurrentThreadTaskExecutor;
 import org.apache.qpid.server.configuration.updater.TaskExecutor;
 import org.apache.qpid.server.configuration.updater.TaskExecutorImpl;
 import org.apache.qpid.server.logging.EventLogger;
 import org.apache.qpid.server.model.Broker;
 import org.apache.qpid.server.model.BrokerModel;
+import org.apache.qpid.server.model.BrokerTestHelper;
 import org.apache.qpid.server.model.Connection;
 import org.apache.qpid.server.model.Port;
 import org.apache.qpid.server.model.Session;
 import org.apache.qpid.server.model.Transport;
 import org.apache.qpid.server.model.VirtualHost;
 import org.apache.qpid.server.model.port.AmqpPort;
-import org.apache.qpid.server.model.BrokerTestHelper;
-import org.apache.qpid.test.utils.QpidTestCase;
 import org.apache.qpid.server.protocol.v0_10.transport.Binary;
 import org.apache.qpid.server.protocol.v0_10.transport.ExecutionErrorCode;
 import org.apache.qpid.server.protocol.v0_10.transport.ExecutionException;
 import org.apache.qpid.server.protocol.v0_10.transport.MessageTransfer;
 import org.apache.qpid.server.protocol.v0_10.transport.Method;
+import org.apache.qpid.test.utils.QpidTestCase;
 
 public class ServerSessionTest extends QpidTestCase
 {
@@ -133,7 +134,8 @@ public class ServerSessionTest extends QpidTestCase
         ServerSessionDelegate delegate = new ServerSessionDelegate();
 
         MessageTransfer xfr = new MessageTransfer();
-        xfr.setBody(new byte[2048]);
+        byte[] body1 = new byte[2048];
+        xfr.setBody(QpidByteBuffer.wrap(body1));
         delegate.messageTransfer(session, xfr);
 
         assertFalse("No methods invoked - expecting at least 1", invokedMethods.isEmpty());
@@ -145,7 +147,8 @@ public class ServerSessionTest extends QpidTestCase
 
         // test the boundary condition
 
-        xfr.setBody(new byte[1024]);
+        byte[] body = new byte[1024];
+        xfr.setBody(QpidByteBuffer.wrap(body));
         delegate.messageTransfer(session, xfr);
 
         assertTrue("Methods invoked when not expecting any", invokedMethods.isEmpty());

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQChannel.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQChannel.java b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQChannel.java
index 98aa263..b5cc43a 100644
--- a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQChannel.java
+++ b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQChannel.java
@@ -805,6 +805,7 @@ public class AMQChannel extends AbstractAMQPSession<AMQChannel, ConsumerTarget_0
         }
         finally
         {
+            dispose();
             LogMessage operationalLogMessage = cause == 0?
                     ChannelMessages.CLOSE() :
                     ChannelMessages.CLOSE_FORCED(cause, message);
@@ -2269,6 +2270,7 @@ public class AMQChannel extends AbstractAMQPSession<AMQChannel, ConsumerTarget_0
         {
             if(bodySize > _connection.getMaxMessageSize())
             {
+                properties.dispose();
                 closeChannel(ErrorCodes.MESSAGE_TOO_LARGE,
                              "Message size of " + bodySize + " greater than allowed maximum of " + _connection.getMaxMessageSize());
             }
@@ -2276,6 +2278,7 @@ public class AMQChannel extends AbstractAMQPSession<AMQChannel, ConsumerTarget_0
         }
         else
         {
+            properties.dispose();
             _connection.sendConnectionClose(ErrorCodes.COMMAND_INVALID,
                                             "Attempt to send a content header without first sending a publish frame",
                                             _channelId);
@@ -3537,5 +3540,24 @@ public class AMQChannel extends AbstractAMQPSession<AMQChannel, ConsumerTarget_0
     public void dispose()
     {
         _txCommitOkFrame.dispose();
+        final IncomingMessage currentMessage = _currentMessage;
+        if (currentMessage != null)
+        {
+            _currentMessage = null;
+            final ContentHeaderBody contentHeader = currentMessage.getContentHeader();
+            if (contentHeader != null)
+            {
+                contentHeader.dispose();
+            }
+
+            int bodyCount = currentMessage.getBodyCount();
+            if (bodyCount > 0)
+            {
+                for (int i = 0; i < bodyCount; i++)
+                {
+                    currentMessage.getContentChunk(i).dispose();
+                }
+            }
+        }
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQPConnection_0_8Impl.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQPConnection_0_8Impl.java b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQPConnection_0_8Impl.java
index d49e115..abe40f9 100644
--- a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQPConnection_0_8Impl.java
+++ b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/AMQPConnection_0_8Impl.java
@@ -394,7 +394,8 @@ public class AMQPConnection_0_8Impl
     @Override
     public boolean channelAwaitingClosure(int channelId)
     {
-        return !_closingChannelsList.isEmpty() && _closingChannelsList.containsKey(channelId);
+        return ignoreAllButCloseOk() || (!_closingChannelsList.isEmpty()
+                                         && _closingChannelsList.containsKey(channelId));
     }
 
     private void addChannel(AMQChannel channel)
@@ -411,12 +412,10 @@ public class AMQPConnection_0_8Impl
 
     private void removeChannel(int channelId)
     {
-        AMQChannel session;
         synchronized (_channelAddRemoveLock)
         {
-            session = _channelMap.remove(channelId);
+            _channelMap.remove(channelId);
         }
-        session.dispose();
     }
 
 
@@ -1288,16 +1287,18 @@ public class AMQPConnection_0_8Impl
                         public Object invoke(final Object proxy, final Method method, final Object[] args)
                                 throws Throwable
                         {
-                            if(method.getName().startsWith("receive"))
+                            if (method.getName().equals("receiveChannelCloseOk") && channelAwaitingClosure(channelId))
+                            {
+                                closeChannelOk(channelId);
+                            }
+                            else if(method.getName().startsWith("receive"))
                             {
                                 sendConnectionClose(ErrorCodes.CHANNEL_ERROR,
-                                        "Unknown channel id: " + channelId,
-                                                    channelId);
-                                return null;
+                                        "Unknown channel id: " + channelId, channelId);
                             }
                             else if(method.getName().equals("ignoreAllButCloseOk"))
                             {
-                                return false;
+                                return channelAwaitingClosure(channelId);
                             }
                             return null;
                         }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/CachedFrame.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/CachedFrame.java b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/CachedFrame.java
index 97ccaab..38a0376 100644
--- a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/CachedFrame.java
+++ b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/CachedFrame.java
@@ -50,9 +50,10 @@ class CachedFrame extends AMQDataBlock
     public long writePayload(final ByteBufferSender sender)
     {
 
-        QpidByteBuffer dup = _buffer.duplicate();
-        sender.send(dup);
-        dup.dispose();
+        try (QpidByteBuffer dup = _buffer.duplicate())
+        {
+            sender.send(dup);
+        }
         return _size;
     }
 
@@ -80,9 +81,10 @@ class CachedFrame extends AMQDataBlock
         @Override
         public void send(final QpidByteBuffer msg)
         {
-            QpidByteBuffer dup = msg.duplicate();
-            _buffer.put(dup);
-            dup.dispose();
+            try (QpidByteBuffer dup = msg.duplicate())
+            {
+                _buffer.put(dup);
+            }
         }
 
         @Override

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_Internal_to_v0_8.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_Internal_to_v0_8.java b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_Internal_to_v0_8.java
index 0a882b7..b362b2a 100644
--- a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_Internal_to_v0_8.java
+++ b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_Internal_to_v0_8.java
@@ -20,8 +20,6 @@
  */
 package org.apache.qpid.server.protocol.v0_8;
 
-import java.util.Collection;
-import java.util.Collections;
 import java.util.LinkedHashMap;
 import java.util.Map;
 
@@ -110,9 +108,9 @@ public class MessageConverter_Internal_to_v0_8 implements MessageConverter<Inter
             }
 
             @Override
-            public Collection<QpidByteBuffer> getContent(final int offset, final int length)
+            public QpidByteBuffer getContent(final int offset, final int length)
             {
-                return Collections.singleton(QpidByteBuffer.wrap(messageContent, offset, length));
+                return QpidByteBuffer.wrap(messageContent, offset, length);
             }
 
             @Override

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_v0_8_to_Internal.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_v0_8_to_Internal.java b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_v0_8_to_Internal.java
index 2cb6b9a..28efa43 100644
--- a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_v0_8_to_Internal.java
+++ b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_v0_8_to_Internal.java
@@ -67,13 +67,9 @@ public class MessageConverter_v0_8_to_Internal implements MessageConverter<AMQMe
     {
         final String mimeType = serverMessage.getMessageHeader().getMimeType();
         byte[] data = new byte[(int) serverMessage.getSize()];
-        int total = 0;
-        for(QpidByteBuffer b : serverMessage.getContent(0, (int) serverMessage.getSize()))
+        try (QpidByteBuffer content = serverMessage.getContent())
         {
-            int len = b.remaining();
-            b.get(data, total, len);
-            b.dispose();
-            total += len;
+            content.get(data);
         }
 
         String encoding = serverMessage.getMessageHeader().getEncoding();

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageFormat_0_9_1.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageFormat_0_9_1.java b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageFormat_0_9_1.java
index 02c9475..cf34cdf 100644
--- a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageFormat_0_9_1.java
+++ b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageFormat_0_9_1.java
@@ -21,14 +21,13 @@
 package org.apache.qpid.server.protocol.v0_8;
 
 import java.nio.BufferUnderflowException;
-import java.util.ArrayList;
 import java.util.List;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
+import org.apache.qpid.server.plugin.MessageFormat;
 import org.apache.qpid.server.plugin.PluggableService;
 import org.apache.qpid.server.protocol.v0_8.transport.ContentHeaderBody;
 import org.apache.qpid.server.protocol.v0_8.transport.MessagePublishInfo;
-import org.apache.qpid.server.plugin.MessageFormat;
 import org.apache.qpid.server.store.MessageHandle;
 import org.apache.qpid.server.store.MessageStore;
 import org.apache.qpid.server.store.StoredMessage;
@@ -62,58 +61,51 @@ public class MessageFormat_0_9_1 implements MessageFormat<AMQMessage>
     }
 
     @Override
-    public List<QpidByteBuffer> convertToMessageFormat(final AMQMessage message)
+    public QpidByteBuffer convertToMessageFormat(final AMQMessage message)
     {
         final MessagePublishInfo messagePublishInfo = message.getMessagePublishInfo();
         final ContentHeaderBody contentHeaderBody = message.getContentHeaderBody();
         AMQShortString exchange = messagePublishInfo.getExchange();
         AMQShortString routingKey = messagePublishInfo.getRoutingKey();
         int length =  contentHeaderBody.getSize() + (exchange == null ? 0 : exchange.length()) + (routingKey == null ? 0 : routingKey.length()) + 3;
-        QpidByteBuffer headerBuf = QpidByteBuffer.allocateDirect(length);
-        EncodingUtils.writeShortStringBytes(headerBuf, exchange);
-        EncodingUtils.writeShortStringBytes(headerBuf, routingKey);
-        byte flags = messagePublishInfo.isMandatory() ? (byte)0 : MANDATORY_MASK;
-        if(messagePublishInfo.isImmediate())
+        try (QpidByteBuffer headerBuf = QpidByteBuffer.allocateDirect(length);
+             QpidByteBuffer content = message.getContent())
         {
-            flags |= IMMEDIATE_MASK;
-        }
-        headerBuf.put(flags);
-        headerBuf.flip();
+            EncodingUtils.writeShortStringBytes(headerBuf, exchange);
+            EncodingUtils.writeShortStringBytes(headerBuf, routingKey);
+            byte flags = messagePublishInfo.isMandatory() ? (byte) 0 : MANDATORY_MASK;
+            if (messagePublishInfo.isImmediate())
+            {
+                flags |= IMMEDIATE_MASK;
+            }
+            headerBuf.put(flags);
+            headerBuf.flip();
 
-        contentHeaderBody.writePayload(headerBuf);
-        List<QpidByteBuffer> bufs = new ArrayList<>();
-        headerBuf.flip();
-        bufs.add(headerBuf);
-        bufs.addAll(message.getContent(0, (int) contentHeaderBody.getBodySize()));
+            contentHeaderBody.writePayload(headerBuf);
 
-        return bufs;
+            return QpidByteBuffer.concatenate(headerBuf, content);
+        }
     }
 
     @Override
-    public AMQMessage createMessage(final List<QpidByteBuffer> buf,
+    public AMQMessage createMessage(final QpidByteBuffer payload,
                                     final MessageStore store,
                                     final Object connectionReference)
     {
         try
         {
-            AMQShortString exchange = readShortString(buf);
-            AMQShortString routingKey = readShortString(buf);
-            byte flags = readByte(buf);
+            AMQShortString exchange = readShortString(payload);
+            AMQShortString routingKey = readShortString(payload);
+            byte flags = payload.get();
             final MessagePublishInfo publishBody = new MessagePublishInfo(exchange,
                                                                           (flags & IMMEDIATE_MASK) != 0,
                                                                           (flags & MANDATORY_MASK) != 0,
                                                                           routingKey);
-            final ContentHeaderBody contentHeaderBody = readContentBody(buf);
+            final ContentHeaderBody contentHeaderBody = readContentBody(payload);
             MessageMetaData mmd = new MessageMetaData(publishBody, contentHeaderBody);
 
             final MessageHandle<MessageMetaData> handle = store.addMessage(mmd);
-            for (QpidByteBuffer content : buf)
-            {
-                if (content.hasRemaining())
-                {
-                    handle.addContent(content);
-                }
-            }
+            handle.addContent(payload);
             final StoredMessage<MessageMetaData> storedMessage = handle.allContentAdded();
 
             return new AMQMessage(storedMessage, connectionReference);
@@ -124,48 +116,25 @@ public class MessageFormat_0_9_1 implements MessageFormat<AMQMessage>
         }
     }
 
-    private ContentHeaderBody readContentBody(final List<QpidByteBuffer> buf) throws AMQFrameDecodingException
+    private ContentHeaderBody readContentBody(final QpidByteBuffer buf) throws AMQFrameDecodingException
     {
-        long size = ((long) readInt(buf)) & 0xffffffffL;
-        final QpidByteBuffer buffer = readByteBuffer(buf, size);
-        final ContentHeaderBody contentHeaderBody = new ContentHeaderBody(buffer, size);
-        buffer.dispose();
-        return contentHeaderBody;
-    }
-
-    private QpidByteBuffer readByteBuffer(final List<QpidByteBuffer> data, final long size)
-    {
-        QpidByteBuffer result = null;
-        for(QpidByteBuffer buf : data)
+        long size = buf.getUnsignedInt();
+        try (QpidByteBuffer buffer = readByteBuffer(buf, size))
         {
-            if(result == null && buf.remaining()>= size)
+            final long newPosition = buf.position() + size;
+            if (newPosition > Integer.MAX_VALUE)
             {
-                return buf.view(0, (int)size);
-            }
-            else if(buf.hasRemaining())
-            {
-                if(result == null)
-                {
-                    result = QpidByteBuffer.allocateDirect((int)size);
-                }
-                if(buf.remaining()>result.remaining())
-                {
-                    QpidByteBuffer dup = buf.view(0, result.remaining());
-                    result.put(dup);
-                    dup.dispose();
-                }
-                else
-                {
-                    result.put(buf);
-                }
-                if(!result.hasRemaining())
-                {
-                    result.flip();
-                    return result;
-                }
+                throw new IllegalStateException(String.format("trying to advance QBB to %d which is larger than MAX_INT",
+                                                              newPosition));
             }
+            buf.position((int) newPosition);
+            return new ContentHeaderBody(buffer, size);
         }
-        throw new BufferUnderflowException();
+    }
+
+    private QpidByteBuffer readByteBuffer(final QpidByteBuffer data, final long size)
+    {
+        return data.view(0, (int)size);
     }
 
     private int readInt(final List<QpidByteBuffer> data)
@@ -194,54 +163,8 @@ public class MessageFormat_0_9_1 implements MessageFormat<AMQMessage>
         throw new BufferUnderflowException();
     }
 
-    private byte readByte(final List<QpidByteBuffer> data)
+    private AMQShortString readShortString(final QpidByteBuffer data)
     {
-        for(QpidByteBuffer buf : data)
-        {
-            if(buf.hasRemaining())
-            {
-                return buf.get();
-            }
-        }
-        throw new BufferUnderflowException();
-    }
-
-    private AMQShortString readShortString(final List<QpidByteBuffer> data)
-    {
-        for(QpidByteBuffer buf : data)
-        {
-            if(buf.hasRemaining())
-            {
-                int length = ((int)buf.get(buf.position())) & 0xff;
-                if(buf.remaining()>length)
-                {
-                    return AMQShortString.readAMQShortString(buf);
-                }
-            }
-        }
-        int length = ((int)readByte(data)) & 0xff;
-        byte[] octets = new byte[length];
-        readByteArray(octets, data);
-        return new AMQShortString(octets);
-    }
-
-    private void readByteArray(final byte[] octets, final List<QpidByteBuffer> data)
-    {
-        int offset = 0;
-        for(QpidByteBuffer buf : data)
-        {
-            final int remaining = buf.remaining();
-            if(remaining >= octets.length-offset)
-            {
-                buf.get(octets, offset, octets.length-offset);
-                return;
-            }
-            else if(remaining > 0)
-            {
-                buf.get(octets, offset, remaining);
-                offset+=remaining;
-            }
-        }
-        throw new BufferUnderflowException();
+        return AMQShortString.readAMQShortString(data);
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaData.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaData.java b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaData.java
index d5baf87..b182c8d 100644
--- a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaData.java
+++ b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaData.java
@@ -21,17 +21,15 @@
 package org.apache.qpid.server.protocol.v0_8;
 
 import java.util.Collection;
-import java.util.List;
 import java.util.Set;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
+import org.apache.qpid.server.message.AMQMessageHeader;
+import org.apache.qpid.server.plugin.MessageMetaDataType;
 import org.apache.qpid.server.protocol.v0_8.transport.AMQProtocolVersionException;
 import org.apache.qpid.server.protocol.v0_8.transport.BasicContentHeaderProperties;
 import org.apache.qpid.server.protocol.v0_8.transport.ContentHeaderBody;
 import org.apache.qpid.server.protocol.v0_8.transport.MessagePublishInfo;
-import org.apache.qpid.server.message.AMQMessageHeader;
-import org.apache.qpid.server.plugin.MessageMetaDataType;
 import org.apache.qpid.server.store.StorableMessageMetaData;
 import org.apache.qpid.server.util.ConnectionScopedRuntimeException;
 
@@ -158,35 +156,11 @@ public class MessageMetaData implements StorableMessageMetaData
     {
 
         @Override
-        public MessageMetaData createMetaData(List<QpidByteBuffer> bufs)
+        public MessageMetaData createMetaData(QpidByteBuffer buf)
         {
             try
             {
-                final int size = QpidByteBufferUtils.getInt(bufs);
-
-                final QpidByteBuffer buf;
-                final boolean disposalRequired;
-                if (bufs.size() == 1)
-                {
-                    buf = bufs.get(0);
-                    disposalRequired = false;
-                }
-                else
-                {
-                    // This should seldom happen.  For AMQP 0-8..0-91 the content header body must
-                    // fit within one frame.  If we get here we are either recovering after a reduction
-                    // in framesize or it so happens that the content header and the size/exchange/routingkey
-                    // just overfills one frame.
-                    int totalRemaining = (int) QpidByteBufferUtils.remaining(bufs);
-
-                    buf = QpidByteBuffer.allocateDirect(totalRemaining);
-                    disposalRequired = true;
-                    for (final QpidByteBuffer qpidByteBuffer : bufs)
-                    {
-                        buf.put(qpidByteBuffer);
-                    }
-                    buf.flip();
-                }
+                final int size = buf.getInt();
 
                 ContentHeaderBody chb = ContentHeaderBody.createFromBuffer(buf, size);
                 final AMQShortString exchange = AMQShortString.readAMQShortString(buf);
@@ -201,11 +175,6 @@ public class MessageMetaData implements StorableMessageMetaData
                                                (flags & MANDATORY_FLAG) != 0,
                                                routingKey);
 
-                if (disposalRequired)
-                {
-                    buf.dispose();
-                }
-
                 return new MessageMetaData(publishBody, chb, arrivalTime);
             }
             catch (AMQFrameDecodingException | AMQProtocolVersionException e)

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaDataType_0_8.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaDataType_0_8.java b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaDataType_0_8.java
index 4218317..ba42fbf 100644
--- a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaDataType_0_8.java
+++ b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/MessageMetaDataType_0_8.java
@@ -20,8 +20,6 @@
  */
 package org.apache.qpid.server.protocol.v0_8;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.ServerMessage;
 import org.apache.qpid.server.plugin.MessageMetaDataType;
@@ -42,9 +40,9 @@ public class MessageMetaDataType_0_8 implements MessageMetaDataType<MessageMetaD
     }
 
     @Override
-    public MessageMetaData createMetaData(List<QpidByteBuffer> bufs)
+    public MessageMetaData createMetaData(QpidByteBuffer buf)
     {
-        return MessageMetaData.FACTORY.createMetaData(bufs);
+        return MessageMetaData.FACTORY.createMetaData(buf);
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverterImpl.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverterImpl.java b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverterImpl.java
index c099c0d..d9465b3 100644
--- a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverterImpl.java
+++ b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/ProtocolOutputConverterImpl.java
@@ -21,27 +21,23 @@
 package org.apache.qpid.server.protocol.v0_8;
 
 import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
 
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import org.apache.qpid.server.QpidException;
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
+import org.apache.qpid.server.message.InstanceProperties;
+import org.apache.qpid.server.message.MessageContentSource;
 import org.apache.qpid.server.protocol.v0_8.transport.AMQBody;
 import org.apache.qpid.server.protocol.v0_8.transport.AMQDataBlock;
 import org.apache.qpid.server.protocol.v0_8.transport.AMQFrame;
 import org.apache.qpid.server.protocol.v0_8.transport.AMQMethodBody;
+import org.apache.qpid.server.protocol.v0_8.transport.AMQVersionAwareProtocolSession;
 import org.apache.qpid.server.protocol.v0_8.transport.BasicCancelOkBody;
 import org.apache.qpid.server.protocol.v0_8.transport.BasicContentHeaderProperties;
 import org.apache.qpid.server.protocol.v0_8.transport.ContentHeaderBody;
 import org.apache.qpid.server.protocol.v0_8.transport.MessagePublishInfo;
-import org.apache.qpid.server.protocol.v0_8.transport.AMQVersionAwareProtocolSession;
-import org.apache.qpid.server.message.InstanceProperties;
-import org.apache.qpid.server.message.MessageContentSource;
-import org.apache.qpid.server.message.ServerMessage;
-import org.apache.qpid.server.plugin.MessageConverter;
 import org.apache.qpid.server.transport.ByteBufferSender;
 import org.apache.qpid.server.util.GZIPUtils;
 
@@ -130,8 +126,7 @@ public class ProtocolOutputConverterImpl implements ProtocolOutputConverter
 
     private DisposableMessageContentSource deflateIfPossible(MessageContentSource source)
     {
-        Collection<QpidByteBuffer> contentBuffers = source.getContent(0, (int) source.getSize());
-        try
+        try (QpidByteBuffer contentBuffers = source.getContent())
         {
             return new ModifiedContentSource(QpidByteBuffer.deflate(contentBuffers));
         }
@@ -140,20 +135,12 @@ public class ProtocolOutputConverterImpl implements ProtocolOutputConverter
             LOGGER.warn("Unable to compress message payload for consumer with gzip, message will be sent as is", e);
             return null;
         }
-        finally
-        {
-            for (QpidByteBuffer contentBuffer : contentBuffers)
-            {
-                contentBuffer.dispose();
-            }
-        }
     }
 
 
     private DisposableMessageContentSource inflateIfPossible(MessageContentSource source)
     {
-        Collection<QpidByteBuffer> contentBuffers = source.getContent(0, (int) source.getSize());
-        try
+        try (QpidByteBuffer contentBuffers = source.getContent())
         {
             return new ModifiedContentSource(QpidByteBuffer.inflate(contentBuffers));
         }
@@ -162,13 +149,6 @@ public class ProtocolOutputConverterImpl implements ProtocolOutputConverter
             LOGGER.warn("Unable to decompress message payload for consumer with gzip, message will be sent as is", e);
             return null;
         }
-        finally
-        {
-            for (QpidByteBuffer contentBuffer : contentBuffers)
-            {
-                contentBuffer.dispose();
-            }
-        }
     }
 
 
@@ -255,13 +235,11 @@ public class ProtocolOutputConverterImpl implements ProtocolOutputConverter
         @Override
         public long writePayload(final ByteBufferSender sender)
         {
-            long size = 0L;
-            for(QpidByteBuffer buf : _content.getContent(_offset, _length))
+            long size;
+            try (final QpidByteBuffer content = _content.getContent(_offset, _length))
             {
-                size += buf.remaining();
-
-                sender.send(buf);
-                buf.dispose();
+                size = content.remaining();
+                sender.send(content);
             }
             return size;
         }
@@ -527,73 +505,31 @@ public class ProtocolOutputConverterImpl implements ProtocolOutputConverter
 
     private static class ModifiedContentSource implements DisposableMessageContentSource
     {
-        private final Collection<QpidByteBuffer> _buffers;
+        private final QpidByteBuffer _buffer;
         private final int _size;
 
-        public ModifiedContentSource(final Collection<QpidByteBuffer> buffers)
+        public ModifiedContentSource(final QpidByteBuffer buffer)
         {
-            _buffers = buffers;
-            int size = 0;
-            for(QpidByteBuffer buf : buffers)
-            {
-                size += buf.remaining();
-            }
-            _size = size;
+            _buffer = buffer;
+            _size = _buffer.remaining();
         }
 
         @Override
         public void dispose()
         {
-            for(QpidByteBuffer buffer : _buffers)
-            {
-                buffer.dispose();
-            }
+            _buffer.dispose();
         }
 
         @Override
-        public Collection<QpidByteBuffer> getContent(final int offset, int length)
+        public QpidByteBuffer getContent()
         {
-            Collection<QpidByteBuffer> content = new ArrayList<>(_buffers.size());
-            int pos = 0;
-            for (QpidByteBuffer buf : _buffers)
-            {
-                if (length > 0)
-                {
-                    int bufRemaining = buf.remaining();
-                    if (pos + bufRemaining <= offset)
-                    {
-                        pos += bufRemaining;
-                    }
-                    else if (pos >= offset)
-                    {
-                        buf = buf.duplicate();
-                        if (bufRemaining <= length)
-                        {
-                            length -= bufRemaining;
-                        }
-                        else
-                        {
-                            buf.limit(length);
-                            length = 0;
-                        }
-                        content.add(buf);
-                        pos+=buf.remaining();
-
-                    }
-                    else
-                    {
-                        int offsetInBuf = offset - pos;
-                        int limit = length < bufRemaining - offsetInBuf ? length : bufRemaining - offsetInBuf;
-                        final QpidByteBuffer bufView = buf.view(offsetInBuf, limit);
-                        content.add(bufView);
-                        length -= limit;
-                        pos+=limit+offsetInBuf;
-                    }
-                }
-
-            }
-            return content;
+            return getContent(0, (int) getSize());
+        }
 
+        @Override
+        public QpidByteBuffer getContent(final int offset, int length)
+        {
+            return _buffer.view(offset, length);
         }
 
         @Override

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/AMQFrame.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/AMQFrame.java b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/AMQFrame.java
index 4fde4f3..4801e52 100644
--- a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/AMQFrame.java
+++ b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/AMQFrame.java
@@ -59,19 +59,20 @@ public class AMQFrame extends AMQDataBlock implements EncodableAMQDataBlock
     @Override
     public long writePayload(final ByteBufferSender sender)
     {
-        QpidByteBuffer frameHeader = QpidByteBuffer.allocate(sender.isDirectBufferPreferred(), HEADER_SIZE);
-
-        frameHeader.put(_bodyFrame.getFrameType());
-        frameHeader.putUnsignedShort(_channel);
-        frameHeader.putUnsignedInt((long) _bodyFrame.getSize());
-        frameHeader.flip();
-        sender.send(frameHeader);
-        frameHeader.dispose();
+        try (QpidByteBuffer frameHeader = QpidByteBuffer.allocate(sender.isDirectBufferPreferred(), HEADER_SIZE))
+        {
+            frameHeader.put(_bodyFrame.getFrameType());
+            frameHeader.putUnsignedShort(_channel);
+            frameHeader.putUnsignedInt((long) _bodyFrame.getSize());
+            frameHeader.flip();
+            sender.send(frameHeader);
+        }
         long size = 8 + _bodyFrame.writePayload(sender);
 
-        final QpidByteBuffer endFrame = FRAME_END_BYTE_BUFFER.duplicate();
-        sender.send(endFrame);
-        endFrame.dispose();
+        try (QpidByteBuffer endFrame = FRAME_END_BYTE_BUFFER.duplicate())
+        {
+            sender.send(endFrame);
+        }
         return size;
     }
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/AMQMethodBodyImpl.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/AMQMethodBodyImpl.java b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/AMQMethodBodyImpl.java
index 9f1fa38..d84093f 100644
--- a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/AMQMethodBodyImpl.java
+++ b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/AMQMethodBodyImpl.java
@@ -80,13 +80,14 @@ public abstract class AMQMethodBodyImpl implements AMQMethodBody
     {
 
         final int size = getSize();
-        QpidByteBuffer buf = QpidByteBuffer.allocate(sender.isDirectBufferPreferred(), size);
-        buf.putUnsignedShort(getClazz());
-        buf.putUnsignedShort(getMethod());
-        writeMethodPayload(buf);
-        buf.flip();
-        sender.send(buf);
-        buf.dispose();
+        try (QpidByteBuffer buf = QpidByteBuffer.allocate(sender.isDirectBufferPreferred(), size))
+        {
+            buf.putUnsignedShort(getClazz());
+            buf.putUnsignedShort(getMethod());
+            writeMethodPayload(buf);
+            buf.flip();
+            sender.send(buf);
+        }
         return size;
     }
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/BasicContentHeaderProperties.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/BasicContentHeaderProperties.java b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/BasicContentHeaderProperties.java
index db74e31..c45b705 100644
--- a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/BasicContentHeaderProperties.java
+++ b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/BasicContentHeaderProperties.java
@@ -464,19 +464,21 @@ public class BasicContentHeaderProperties
     {
         if(useEncodedForm())
         {
-            final QpidByteBuffer duplicate = _encodedForm.duplicate();
-            sender.send(duplicate);
-            duplicate.dispose();
+            try (QpidByteBuffer duplicate = _encodedForm.duplicate())
+            {
+                sender.send(duplicate);
+            }
             return _encodedForm.remaining();
         }
         else
         {
             int propertyListSize = getPropertyListSize();
-            QpidByteBuffer buf = QpidByteBuffer.allocate(sender.isDirectBufferPreferred(), propertyListSize);
-            writePropertyListPayload(buf);
-            buf.flip();
-            sender.send(buf);
-            buf.dispose();
+            try (QpidByteBuffer buf = QpidByteBuffer.allocate(sender.isDirectBufferPreferred(), propertyListSize))
+            {
+                writePropertyListPayload(buf);
+                buf.flip();
+                sender.send(buf);
+            }
             return propertyListSize;
         }
 
@@ -497,9 +499,10 @@ public class BasicContentHeaderProperties
         }
         _encodedForm = buffer.view(0,size);
 
-        final QpidByteBuffer byteBuffer = _encodedForm.slice();
-        decode(byteBuffer);
-        byteBuffer.dispose();
+        try (QpidByteBuffer byteBuffer = _encodedForm.slice())
+        {
+            decode(byteBuffer);
+        }
         buffer.position(buffer.position()+size);
 
     }
@@ -520,9 +523,10 @@ public class BasicContentHeaderProperties
         {
             long length = buffer.getUnsignedInt();
 
-            QpidByteBuffer buf = buffer.view(0, (int)length);
-            _headers = new FieldTable(buf);
-            buf.dispose();
+            try (QpidByteBuffer buf = buffer.view(0, (int) length))
+            {
+                _headers = new FieldTable(buf);
+            }
             buffer.position(buffer.position()+(int)length);
         }
 
@@ -959,6 +963,7 @@ public class BasicContentHeaderProperties
         if(_headers != null)
         {
             _headers.dispose();
+            _headers = null;
         }
     }
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/ContentBody.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/ContentBody.java b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/ContentBody.java
index 88468a3..0cf0423 100644
--- a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/ContentBody.java
+++ b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/ContentBody.java
@@ -68,9 +68,10 @@ public class ContentBody implements AMQBody
     {
         if(_payload != null)
         {
-            final QpidByteBuffer duplicate = _payload.duplicate();
-            sender.send(duplicate);
-            duplicate.dispose();
+            try (QpidByteBuffer duplicate = _payload.duplicate())
+            {
+                sender.send(duplicate);
+            }
             return _payload.remaining();
         }
         else
@@ -96,15 +97,13 @@ public class ContentBody implements AMQBody
     public static void process(final QpidByteBuffer in,
                                final ChannelMethodProcessor methodProcessor, final long bodySize)
     {
-
-        QpidByteBuffer payload = in.view(0, (int) bodySize);
-
-        if(!methodProcessor.ignoreAllButCloseOk())
+        try (QpidByteBuffer payload = in.view(0, (int) bodySize))
         {
-            methodProcessor.receiveMessageContent(payload);
+            if (!methodProcessor.ignoreAllButCloseOk())
+            {
+                methodProcessor.receiveMessageContent(payload);
+            }
         }
-
-        payload.dispose();
         in.position(in.position()+(int)bodySize);
     }
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/ContentHeaderBody.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/ContentHeaderBody.java b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/ContentHeaderBody.java
index 0b55f4c..d7a70d4 100644
--- a/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/ContentHeaderBody.java
+++ b/broker-plugins/amqp-0-8-protocol/src/main/java/org/apache/qpid/server/protocol/v0_8/transport/ContentHeaderBody.java
@@ -90,14 +90,15 @@ public class ContentHeaderBody implements AMQBody
     @Override
     public long writePayload(final ByteBufferSender sender)
     {
-        QpidByteBuffer data = QpidByteBuffer.allocate(sender.isDirectBufferPreferred(), HEADER_SIZE);
-        data.putUnsignedShort(CLASS_ID);
-        data.putUnsignedShort(0);
-        data.putLong(_bodySize);
-        data.putUnsignedShort(_properties.getPropertyFlags());
-        data.flip();
-        sender.send(data);
-        data.dispose();
+        try (QpidByteBuffer data = QpidByteBuffer.allocate(sender.isDirectBufferPreferred(), HEADER_SIZE))
+        {
+            data.putUnsignedShort(CLASS_ID);
+            data.putUnsignedShort(0);
+            data.putLong(_bodySize);
+            data.putUnsignedShort(_properties.getPropertyFlags());
+            data.flip();
+            sender.send(data);
+        }
         return HEADER_SIZE + _properties.writePropertyListPayload(sender);
     }
 
@@ -167,7 +168,6 @@ public class ContentHeaderBody implements AMQBody
                                final ChannelMethodProcessor methodProcessor, final long size)
             throws AMQFrameDecodingException
     {
-
         int classId = buffer.getUnsignedShort();
         buffer.getUnsignedShort();
         long bodySize = buffer.getLong();
@@ -186,6 +186,10 @@ public class ContentHeaderBody implements AMQBody
         {
             methodProcessor.receiveMessageHeader(properties, bodySize);
         }
+        else
+        {
+            properties.dispose();
+        }
     }
 
     public void dispose()

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQDecoderTest.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQDecoderTest.java b/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQDecoderTest.java
index c96ee58..dceccdc 100644
--- a/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQDecoderTest.java
+++ b/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/AMQDecoderTest.java
@@ -30,6 +30,7 @@ import java.util.List;
 import java.util.Random;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
+import org.apache.qpid.server.protocol.ProtocolVersion;
 import org.apache.qpid.server.protocol.v0_8.transport.AMQBody;
 import org.apache.qpid.server.protocol.v0_8.transport.AMQDataBlock;
 import org.apache.qpid.server.protocol.v0_8.transport.AMQFrame;
@@ -39,14 +40,13 @@ import org.apache.qpid.server.protocol.v0_8.transport.ContentBody;
 import org.apache.qpid.server.protocol.v0_8.transport.ContentHeaderBody;
 import org.apache.qpid.server.protocol.v0_8.transport.FrameCreatingMethodProcessor;
 import org.apache.qpid.server.protocol.v0_8.transport.HeartbeatBody;
-import org.apache.qpid.server.protocol.ProtocolVersion;
-import org.apache.qpid.test.utils.QpidTestCase;
 import org.apache.qpid.server.transport.ByteBufferSender;
-import org.apache.qpid.server.util.ByteBufferUtils;
+import org.apache.qpid.test.utils.QpidTestCase;
 
 public class AMQDecoderTest extends QpidTestCase
 {
 
+    private static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.allocate(0);
     private ClientDecoder _decoder;
     private FrameCreatingMethodProcessor _methodProcessor;
 
@@ -58,15 +58,15 @@ public class AMQDecoderTest extends QpidTestCase
         _methodProcessor = new FrameCreatingMethodProcessor(ProtocolVersion.v0_91);
         _decoder = new ClientDecoder(_methodProcessor);
     }
-   
-    
+
+
     private ByteBuffer getHeartbeatBodyBuffer() throws IOException
     {
         TestSender sender = new TestSender();
         HeartbeatBody.FRAME.writePayload(sender);
-        return ByteBufferUtils.combine(sender.getSentBuffers());
+        return combine(sender.getSentBuffers());
     }
-    
+
     public void testSingleFrameDecode() throws AMQProtocolVersionException, AMQFrameDecodingException, IOException
     {
         ByteBuffer msg = getHeartbeatBodyBuffer();
@@ -94,7 +94,7 @@ public class AMQDecoderTest extends QpidTestCase
         AMQFrame frame = new AMQFrame(1, body);
         TestSender sender = new TestSender();
         frame.writePayload(sender);
-        ByteBuffer msg = ByteBufferUtils.combine(sender.getSentBuffers());
+        ByteBuffer msg = combine(sender.getSentBuffers());
 
         _decoder.decodeBuffer(msg);
         List<AMQDataBlock> frames = _methodProcessor.getProcessedMethods();
@@ -122,7 +122,7 @@ public class AMQDecoderTest extends QpidTestCase
         AMQFrame frame = new AMQFrame(1, body);
         TestSender sender = new TestSender();
         frame.writePayload(sender);
-        ByteBuffer allData = ByteBufferUtils.combine(sender.getSentBuffers());
+        ByteBuffer allData = combine(sender.getSentBuffers());
 
 
         for(int i = 0 ; i < allData.remaining(); i++)
@@ -137,9 +137,12 @@ public class AMQDecoderTest extends QpidTestCase
         {
             assertEquals(ContentBody.TYPE, ((AMQFrame) frames.get(0)).getBodyFrame().getFrameType());
             ContentBody decodedBody = (ContentBody) ((AMQFrame) frames.get(0)).getBodyFrame();
-            final ByteBuffer byteBuffer = decodedBody.getPayload().asByteBuffer().duplicate();
-            byte[] bodyBytes = new byte[byteBuffer.remaining()];
-            byteBuffer.get(bodyBytes);
+            byte[] bodyBytes;
+            try (QpidByteBuffer payloadBuffer = decodedBody.getPayload())
+            {
+                bodyBytes = new byte[payloadBuffer.remaining()];
+                payloadBuffer.get(bodyBytes);
+            }
             assertTrue("Body was corrupted", Arrays.equals(payload, bodyBytes));
         }
         else
@@ -147,7 +150,7 @@ public class AMQDecoderTest extends QpidTestCase
             fail("decode was not a frame");
         }
     }
-    
+
     public void testPartialFrameDecode() throws AMQProtocolVersionException, AMQFrameDecodingException, IOException
     {
         ByteBuffer msg = getHeartbeatBodyBuffer();
@@ -173,7 +176,7 @@ public class AMQDecoderTest extends QpidTestCase
             fail("decode was not a frame");
         }
     }
-    
+
     public void testMultipleFrameDecode() throws AMQProtocolVersionException, AMQFrameDecodingException, IOException
     {
         ByteBuffer msgA = getHeartbeatBodyBuffer();
@@ -197,13 +200,13 @@ public class AMQDecoderTest extends QpidTestCase
             }
         }
     }
-    
+
     public void testMultiplePartialFrameDecode() throws AMQProtocolVersionException, AMQFrameDecodingException, IOException
     {
         ByteBuffer msgA = getHeartbeatBodyBuffer();
         ByteBuffer msgB = getHeartbeatBodyBuffer();
         ByteBuffer msgC = getHeartbeatBodyBuffer();
-        
+
         ByteBuffer sliceA = ByteBuffer.allocate(msgA.remaining() + msgB.remaining() / 2);
         sliceA.put(msgA);
         int limit = msgB.limit();
@@ -213,7 +216,7 @@ public class AMQDecoderTest extends QpidTestCase
         sliceA.flip();
         msgB.limit(limit);
         msgB.position(pos);
-        
+
         ByteBuffer sliceB = ByteBuffer.allocate(msgB.remaining() + pos);
         sliceB.put(msgB);
         msgC.limit(pos);
@@ -245,8 +248,8 @@ public class AMQDecoderTest extends QpidTestCase
 
     private static class TestSender implements ByteBufferSender
     {
-        private final Collection<QpidByteBuffer> _sentBuffers = new ArrayList<>();
 
+        private final Collection<QpidByteBuffer> _sentBuffers = new ArrayList<>();
         @Override
         public boolean isDirectBufferPreferred()
         {
@@ -276,6 +279,32 @@ public class AMQDecoderTest extends QpidTestCase
         {
             return _sentBuffers;
         }
+
     }
 
+    private static ByteBuffer combine(Collection<QpidByteBuffer> bufs)
+    {
+        if(bufs == null || bufs.isEmpty())
+        {
+            return EMPTY_BYTE_BUFFER;
+        }
+        else
+        {
+            int size = 0;
+            boolean isDirect = false;
+            for(QpidByteBuffer buf : bufs)
+            {
+                size += buf.remaining();
+                isDirect = isDirect || buf.isDirect();
+            }
+            ByteBuffer combined = isDirect ? ByteBuffer.allocateDirect(size) : ByteBuffer.allocate(size);
+
+            for(QpidByteBuffer buf : bufs)
+            {
+                buf.copyTo(combined);
+            }
+            combined.flip();
+            return combined;
+        }
+    }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_0_8_to_InternalTest.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_0_8_to_InternalTest.java b/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_0_8_to_InternalTest.java
index 0f32481..22a0fdd 100644
--- a/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_0_8_to_InternalTest.java
+++ b/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_0_8_to_InternalTest.java
@@ -38,8 +38,6 @@ import java.util.UUID;
 
 import com.google.common.collect.Lists;
 import org.mockito.ArgumentCaptor;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.AMQMessageHeader;
@@ -321,15 +319,8 @@ public class MessageConverter_0_8_to_InternalTest extends QpidTestCase
         final ArgumentCaptor<Integer> sizeCaptor = ArgumentCaptor.forClass(Integer.class);
 
         when(_handle.getContent(offsetCaptor.capture(),
-                                sizeCaptor.capture())).then(new Answer<Collection<QpidByteBuffer>>()
-        {
-            @Override
-            public Collection<QpidByteBuffer> answer(final InvocationOnMock invocation) throws Throwable
-            {
-                final QpidByteBuffer view = combined.view(offsetCaptor.getValue(), sizeCaptor.getValue());
-                return Collections.singleton(view);
-            }
-        });
+                                sizeCaptor.capture())).then(invocation -> combined.view(offsetCaptor.getValue(),
+                                                                                        sizeCaptor.getValue()));
     }
 
     private void doTestTextMessage(final String originalContent, final String mimeType) throws Exception

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_Internal_to_0_8Test.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_Internal_to_0_8Test.java b/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_Internal_to_0_8Test.java
index 6de6ceb..fd3fac6 100644
--- a/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_Internal_to_0_8Test.java
+++ b/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MessageConverter_Internal_to_0_8Test.java
@@ -25,19 +25,16 @@ import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
 import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
 import java.io.ObjectOutputStream;
 import java.io.Serializable;
 import java.util.ArrayList;
-import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
-import java.util.UUID;
 
 import com.google.common.collect.Lists;
 import com.google.common.io.ByteStreams;
 import org.mockito.ArgumentCaptor;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.message.AMQMessageHeader;
@@ -46,7 +43,6 @@ import org.apache.qpid.server.message.internal.InternalMessageHeader;
 import org.apache.qpid.server.message.internal.InternalMessageMetaData;
 import org.apache.qpid.server.message.internal.InternalMessageMetaDataType;
 import org.apache.qpid.server.model.NamedAddressSpace;
-import org.apache.qpid.server.protocol.converter.MessageConversionException;
 import org.apache.qpid.server.protocol.v0_10.transport.mimecontentconverter.ListToAmqpListConverter;
 import org.apache.qpid.server.protocol.v0_10.transport.mimecontentconverter.MapToAmqpMapConverter;
 import org.apache.qpid.server.store.StoredMessage;
@@ -239,15 +235,8 @@ public class MessageConverter_Internal_to_0_8Test extends QpidTestCase
         final ArgumentCaptor<Integer> sizeCaptor = ArgumentCaptor.forClass(Integer.class);
 
         when(_handle.getContent(offsetCaptor.capture(),
-                                sizeCaptor.capture())).then(new Answer<Collection<QpidByteBuffer>>()
-        {
-            @Override
-            public Collection<QpidByteBuffer> answer(final InvocationOnMock invocation) throws Throwable
-            {
-                final QpidByteBuffer view = combined.view(offsetCaptor.getValue(), sizeCaptor.getValue());
-                return Collections.singleton(view);
-            }
-        });
+                                sizeCaptor.capture())).then(invocation -> combined.view(offsetCaptor.getValue(),
+                                                                                        sizeCaptor.getValue()));
     }
 
     private void doTest(final Serializable messageBytes,
@@ -257,21 +246,21 @@ public class MessageConverter_Internal_to_0_8Test extends QpidTestCase
     {
         final InternalMessage sourceMessage = getAmqMessage(messageBytes, mimeType);
         final AMQMessage convertedMessage = _converter.convert(sourceMessage, mock(NamedAddressSpace.class));
-        final Collection<QpidByteBuffer> content = convertedMessage.getContent(0, (int) convertedMessage.getSize());
+        final QpidByteBuffer content = convertedMessage.getContent();
 
         assertArrayEquals("Unexpected content", expectedContent != null ? expectedContent : new byte[0], getBytes(content));
         assertEquals("Unexpected content type", expectedContentType, convertedMessage.getMessageHeader().getMimeType());
     }
 
-    private byte[] getBytes(final Collection<QpidByteBuffer> content) throws Exception
+    private byte[] getBytes(final QpidByteBuffer content) throws Exception
     {
-        ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        for (QpidByteBuffer buf : content)
+        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
+             InputStream contentInputStream = content.asInputStream())
         {
-            ByteStreams.copy(buf.asInputStream(), bos);
-            buf.dispose();
+            ByteStreams.copy(contentInputStream, bos);
+            content.dispose();
+            return bos.toByteArray();
         }
-        return bos.toByteArray();
     }
 
     private static class MySerializable implements Serializable

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MessageMetaDataFactoryTest.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MessageMetaDataFactoryTest.java b/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MessageMetaDataFactoryTest.java
index 5d36778..6939683 100644
--- a/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MessageMetaDataFactoryTest.java
+++ b/broker-plugins/amqp-0-8-protocol/src/test/java/org/apache/qpid/server/protocol/v0_8/MessageMetaDataFactoryTest.java
@@ -20,14 +20,7 @@
 
 package org.apache.qpid.server.protocol.v0_8;
 
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferInputStream;
 import org.apache.qpid.server.protocol.v0_8.transport.BasicContentHeaderProperties;
 import org.apache.qpid.server.protocol.v0_8.transport.ContentHeaderBody;
 import org.apache.qpid.server.protocol.v0_8.transport.MessagePublishInfo;
@@ -65,7 +58,7 @@ public class MessageMetaDataFactoryTest extends QpidTestCase
             _mmd.writeToBuffer(qpidByteBuffer);
             qpidByteBuffer.flip();
 
-            MessageMetaData recreated = MessageMetaData.FACTORY.createMetaData(Collections.singletonList(qpidByteBuffer));
+            MessageMetaData recreated = MessageMetaData.FACTORY.createMetaData(qpidByteBuffer);
 
             assertEquals("Unexpected arrival time", _arrivalTime, recreated.getArrivalTime());
             assertEquals("Unexpected routing key", _routingKey, recreated.getMessagePublishInfo().getRoutingKey());
@@ -75,31 +68,6 @@ public class MessageMetaDataFactoryTest extends QpidTestCase
         }
     }
 
-    public void testUnmarshalFromMultipleBuffers() throws Exception
-    {
-        List<QpidByteBuffer> bufs = Collections.emptyList();
-        try (QpidByteBuffer qpidByteBuffer = QpidByteBuffer.allocateDirect(_mmd.getStorableSize()))
-        {
-            _mmd.writeToBuffer(qpidByteBuffer);
-            qpidByteBuffer.flip();
-
-            bufs = splitIntoSmallerBuffers(qpidByteBuffer);
-
-            final MessageMetaData recreated = MessageMetaData.FACTORY.createMetaData(bufs);
-            assertEquals("Unexpected arrival time", _arrivalTime, recreated.getArrivalTime());
-            assertEquals("Unexpected routing key", _routingKey, recreated.getMessagePublishInfo().getRoutingKey());
-            assertEquals("Unexpected content type", CONTENT_TYPE, recreated.getContentHeaderBody().getProperties().getContentTypeAsString());
-            recreated.dispose();
-        }
-        finally
-        {
-            for (final QpidByteBuffer buf : bufs)
-            {
-                buf.dispose();
-            }
-        }
-    }
-
     private MessageMetaData createTestMessageMetaData()
     {
         final MessagePublishInfo publishBody = new MessagePublishInfo(_exchange,
@@ -112,24 +80,4 @@ public class MessageMetaDataFactoryTest extends QpidTestCase
 
         return new MessageMetaData(publishBody, contentHeaderBody, _arrivalTime);
     }
-
-    private List<QpidByteBuffer> splitIntoSmallerBuffers(final QpidByteBuffer qpidByteBuffer) throws IOException
-    {
-        List<QpidByteBuffer> bufs = new ArrayList<>();
-        try (InputStream stream = new QpidByteBufferInputStream(Collections.singletonList(qpidByteBuffer)))
-        {
-            byte[] transferBuf = new byte[3];
-            int read = stream.read(transferBuf);
-            while (read != -1)
-            {
-                QpidByteBuffer buf = QpidByteBuffer.allocateDirect(read);
-                buf.put(transferBuf, 0, read);
-                buf.flip();
-                bufs.add(buf);
-                read = stream.read(transferBuf);
-            }
-        }
-        return bufs;
-    }
-
 }
\ No newline at end of file


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org


[04/10] qpid-broker-j git commit: QPID-7832: [Java Broker] Refactor store/protocol API using Collection

Posted by lq...@apache.org.
http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/FrameWriter.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/FrameWriter.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/FrameWriter.java
index 58350e6..b0f8ed0 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/FrameWriter.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/FrameWriter.java
@@ -21,10 +21,7 @@
 
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.framing.AMQFrame;
 import org.apache.qpid.server.protocol.v1_0.type.UnsignedShort;
 import org.apache.qpid.server.transport.ByteBufferSender;
@@ -43,9 +40,9 @@ public class FrameWriter
 
     public <T> int send(AMQFrame<T> frame)
     {
-        final List<QpidByteBuffer> payload = frame.getPayload();
+        final QpidByteBuffer payload = frame.getPayload();
 
-        final int payloadLength = payload == null ? 0 : (int) QpidByteBufferUtils.remaining(payload);
+        final int payloadLength = payload == null ? 0 : payload.remaining();
         final T frameBody = frame.getFrameBody();
 
         final ValueWriter<T> typeWriter = frameBody == null ? null : _registry.getValueWriter(frameBody);
@@ -59,26 +56,25 @@ public class FrameWriter
             bodySize = 8 + typeWriter.getEncodedSize();
         }
 
-        QpidByteBuffer body = QpidByteBuffer.allocate(_sender.isDirectBufferPreferred(), bodySize);
-        final int totalSize = bodySize + payloadLength;
-        body.putInt(totalSize);
-        body.put((byte)2); // DOFF
-        body.put(frame.getFrameType()); // AMQP Frame Type
-        body.putShort(UnsignedShort.valueOf(frame.getChannel()).shortValue());
-        if(typeWriter != null)
+        final int totalSize;
+        try (QpidByteBuffer body = QpidByteBuffer.allocate(_sender.isDirectBufferPreferred(), bodySize))
         {
-            typeWriter.writeToBuffer(body);
-        }
-        body.flip();
+            totalSize = bodySize + payloadLength;
+            body.putInt(totalSize);
+            body.put((byte) 2); // DOFF
+            body.put(frame.getFrameType()); // AMQP Frame Type
+            body.putShort(UnsignedShort.valueOf(frame.getChannel()).shortValue());
+            if (typeWriter != null)
+            {
+                typeWriter.writeToBuffer(body);
+            }
+            body.flip();
 
-        _sender.send(body);
-        body.dispose();
+            _sender.send(body);
+        }
         if(payload != null)
         {
-            for(QpidByteBuffer buf : payload)
-            {
-                _sender.send(buf);
-            }
+            _sender.send(payload);
         }
         return totalSize;
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/IntTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/IntTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/IntTypeConstructor.java
index 8428e00..7d4e39b 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/IntTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/IntTypeConstructor.java
@@ -20,10 +20,7 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 
@@ -42,11 +39,11 @@ public class IntTypeConstructor implements TypeConstructor<Integer>
     }
 
     @Override
-    public Integer construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public Integer construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
-        if(QpidByteBufferUtils.hasRemaining(in, 4))
+        if (in.hasRemaining(4))
         {
-            return QpidByteBufferUtils.getInt(in);
+            return in.getInt();
         }
         else
         {

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ListConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ListConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ListConstructor.java
index c5ed18d..72ef51e 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ListConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ListConstructor.java
@@ -24,7 +24,6 @@ import java.util.ArrayList;
 import java.util.List;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 
@@ -36,11 +35,11 @@ public class ListConstructor extends VariableWidthTypeConstructor<List<Object>>
     }
 
     @Override
-    public List<Object> construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public List<Object> construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
         int size;
         int count;
-        long remaining = QpidByteBufferUtils.remaining(in);
+        long remaining = (long) in.remaining();
         if (remaining < getSize() * 2)
         {
             throw new AmqpErrorException(AmqpError.DECODE_ERROR,
@@ -52,13 +51,13 @@ public class ListConstructor extends VariableWidthTypeConstructor<List<Object>>
 
         if (getSize() == 1)
         {
-            size = QpidByteBufferUtils.get(in) & 0xFF;
-            count = QpidByteBufferUtils.get(in) & 0xFF;
+            size = in.getUnsignedByte();
+            count = in.getUnsignedByte();
         }
         else
         {
-            size = QpidByteBufferUtils.getInt(in);
-            count = QpidByteBufferUtils.getInt(in);
+            size = in.getInt();
+            count = in.getInt();
         }
         remaining -= getSize();
         if (remaining < size)
@@ -72,7 +71,7 @@ public class ListConstructor extends VariableWidthTypeConstructor<List<Object>>
         return construct(in, handler, size, count);
     }
 
-    protected List<Object> construct(final List<QpidByteBuffer> in,
+    protected List<Object> construct(final QpidByteBuffer in,
                                      final ValueHandler handler,
                                      final int size,
                                      final int count)

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/LongTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/LongTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/LongTypeConstructor.java
index 70c8400..696add4 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/LongTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/LongTypeConstructor.java
@@ -20,10 +20,7 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 
@@ -42,11 +39,11 @@ public class LongTypeConstructor implements TypeConstructor<Long>
     }
 
     @Override
-    public Long construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public Long construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
-        if(QpidByteBufferUtils.hasRemaining(in, 8))
+        if (in.hasRemaining(8))
         {
-            return QpidByteBufferUtils.getLong(in);
+            return in.getLong();
         }
         else
         {

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/MapConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/MapConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/MapConstructor.java
index 058dc48..70f5ed2 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/MapConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/MapConstructor.java
@@ -21,11 +21,9 @@
 package org.apache.qpid.server.protocol.v1_0.codec;
 
 import java.util.LinkedHashMap;
-import java.util.List;
 import java.util.Map;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 
@@ -37,12 +35,12 @@ public class MapConstructor extends VariableWidthTypeConstructor<Map<Object,Obje
     }
 
     @Override
-    public Map<Object, Object> construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public Map<Object, Object> construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
         return construct(in, handler, Object.class, Object.class);
     }
 
-    public <T, S> Map<T, S> construct(final List<QpidByteBuffer> in,
+    public <T, S> Map<T, S> construct(final QpidByteBuffer in,
                                       final ValueHandler handler,
                                       Class<T> keyType,
                                       Class<S> valueType) throws AmqpErrorException
@@ -50,7 +48,7 @@ public class MapConstructor extends VariableWidthTypeConstructor<Map<Object,Obje
         int size;
         int count;
 
-        long remaining = QpidByteBufferUtils.remaining(in);
+        long remaining = (long) in.remaining();
         if (remaining < getSize() * 2)
         {
             throw new AmqpErrorException(AmqpError.DECODE_ERROR,
@@ -62,13 +60,13 @@ public class MapConstructor extends VariableWidthTypeConstructor<Map<Object,Obje
 
         if (getSize() == 1)
         {
-            size = QpidByteBufferUtils.get(in) & 0xFF;
-            count = QpidByteBufferUtils.get(in) & 0xFF;
+            size = in.getUnsignedByte();
+            count = in.getUnsignedByte();
         }
         else
         {
-            size = QpidByteBufferUtils.getInt(in);
-            count = QpidByteBufferUtils.getInt(in);
+            size = in.getInt();
+            count = in.getInt();
         }
         remaining -= getSize();
         if (remaining < size)
@@ -84,7 +82,7 @@ public class MapConstructor extends VariableWidthTypeConstructor<Map<Object,Obje
     }
 
 
-    private <T, S> Map<T, S> construct(final List<QpidByteBuffer> in,
+    private <T, S> Map<T, S> construct(final QpidByteBuffer in,
                                        final ValueHandler handler,
                                        final int size,
                                        final int count,

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/NullTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/NullTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/NullTypeConstructor.java
index 27be92c..6f8f16e 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/NullTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/NullTypeConstructor.java
@@ -19,8 +19,6 @@
 
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 
 class NullTypeConstructor implements TypeConstructor<Void>
@@ -32,7 +30,7 @@ class NullTypeConstructor implements TypeConstructor<Void>
     }
 
     @Override
-    public Void construct(final List<QpidByteBuffer> in, final ValueHandler handler)
+    public Void construct(final QpidByteBuffer in, final ValueHandler handler)
     {
         return null;
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ShortTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ShortTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ShortTypeConstructor.java
index 30e7efb..3fc0c61 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ShortTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ShortTypeConstructor.java
@@ -20,10 +20,7 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 
@@ -42,11 +39,11 @@ public class ShortTypeConstructor implements TypeConstructor<Short>
     }
 
     @Override
-    public Short construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public Short construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
-        if(QpidByteBufferUtils.hasRemaining(in, 2))
+        if (in.hasRemaining(2))
         {
-            return QpidByteBufferUtils.getShort(in);
+            return in.getShort();
         }
         else
         {

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallIntConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallIntConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallIntConstructor.java
index 41f462e..42a346b 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallIntConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallIntConstructor.java
@@ -19,10 +19,7 @@
 
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 
@@ -41,11 +38,11 @@ public class SmallIntConstructor implements TypeConstructor<Integer>
     }
 
     @Override
-    public Integer construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public Integer construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
-        if (QpidByteBufferUtils.hasRemaining(in))
+        if (in.hasRemaining())
         {
-            byte b = QpidByteBufferUtils.get(in);
+            byte b = in.get();
             return (int) b;
         }
         else

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallLongConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallLongConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallLongConstructor.java
index 44741e1..6629bff 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallLongConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallLongConstructor.java
@@ -19,10 +19,7 @@
 
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 
@@ -41,11 +38,11 @@ public class SmallLongConstructor implements TypeConstructor<Long>
     }
 
     @Override
-    public Long construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public Long construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
-        if (QpidByteBufferUtils.hasRemaining(in))
+        if (in.hasRemaining())
         {
-            byte b = QpidByteBufferUtils.get(in);
+            byte b = in.get();
             return (long) b;
         }
         else

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallUIntConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallUIntConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallUIntConstructor.java
index b080814..3009258 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallUIntConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallUIntConstructor.java
@@ -18,10 +18,7 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.UnsignedInteger;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
@@ -41,12 +38,12 @@ public class SmallUIntConstructor implements TypeConstructor<UnsignedInteger>
     }
 
     @Override
-    public UnsignedInteger construct(final List<QpidByteBuffer> in, final ValueHandler handler)
+    public UnsignedInteger construct(final QpidByteBuffer in, final ValueHandler handler)
             throws AmqpErrorException
     {
-        if (QpidByteBufferUtils.hasRemaining(in))
+        if (in.hasRemaining())
         {
-            byte b = QpidByteBufferUtils.get(in);
+            byte b = in.get();
             return UnsignedInteger.valueOf(((int) b) & 0xff);
         }
         else

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallULongConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallULongConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallULongConstructor.java
index 9e34ea9..ea3bc95 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallULongConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SmallULongConstructor.java
@@ -19,10 +19,7 @@
 
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.UnsignedLong;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
@@ -42,11 +39,11 @@ public class SmallULongConstructor implements TypeConstructor<UnsignedLong>
     }
 
     @Override
-    public UnsignedLong construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public UnsignedLong construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
-        if (QpidByteBufferUtils.hasRemaining(in))
+        if (in.hasRemaining())
         {
-            byte b = QpidByteBufferUtils.get(in);
+            byte b = in.get();
             return UnsignedLong.valueOf(((long) b) & 0xffL);
         }
         else

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/StringTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/StringTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/StringTypeConstructor.java
index b1e5b42..946dc4a 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/StringTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/StringTypeConstructor.java
@@ -22,11 +22,7 @@ package org.apache.qpid.server.protocol.v1_0.codec;
 
 import static java.nio.charset.StandardCharsets.UTF_8;
 
-import java.nio.CharBuffer;
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 
@@ -45,77 +41,32 @@ public class StringTypeConstructor extends VariableWidthTypeConstructor<String>
         super(size);
     }
 
-    private String constructFromSingleBuffer(final QpidByteBuffer in, final int size)
-    {
-        int origPosition = in.position();
-
-        QpidByteBuffer dup = in.duplicate();
-        try
-        {
-            dup.limit(dup.position() + size);
-            CharBuffer charBuf = dup.decode(UTF_8);
-
-            String str = charBuf.toString();
-
-            in.position(origPosition + size);
-
-            return str;
-        }
-        catch (IllegalArgumentException e)
-        {
-            throw new IllegalArgumentException("position: "
-                                               + dup.position()
-                                               + "size: "
-                                               + size
-                                               + " capacity: "
-                                               + dup.capacity());
-        }
-        finally
-        {
-            dup.dispose();
-        }
-    }
-
     @Override
-    public String construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public String construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
         int size;
 
-        if (!QpidByteBufferUtils.hasRemaining(in, getSize()))
+        if (!in.hasRemaining(getSize()))
         {
             throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Cannot construct string: insufficient input data");
         }
 
         if (getSize() == 1)
         {
-            size = QpidByteBufferUtils.get(in) & 0xFF;
+            size = in.getUnsignedByte();
         }
         else
         {
-            size = QpidByteBufferUtils.getInt(in);
+            size = in.getInt();
         }
 
-        if (!QpidByteBufferUtils.hasRemaining(in, size))
+        if (!in.hasRemaining(size))
         {
             throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Cannot construct string: insufficient input data");
         }
 
-        for (int i = 0; i < in.size(); i++)
-        {
-            QpidByteBuffer buf = in.get(i);
-            if (buf.hasRemaining())
-            {
-                if (buf.remaining() >= size)
-                {
-                    return constructFromSingleBuffer(buf, size);
-                }
-                break;
-            }
-        }
-
         byte[] data = new byte[size];
-        QpidByteBufferUtils.get(in, data);
-
+        in.get(data);
         return new String(data, UTF_8);
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SymbolTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SymbolTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SymbolTypeConstructor.java
index 09f467f..fcdb68d 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SymbolTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/SymbolTypeConstructor.java
@@ -20,14 +20,11 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.nio.CharBuffer;
 import java.nio.charset.Charset;
-import java.util.List;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.Symbol;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
@@ -50,85 +47,33 @@ public class SymbolTypeConstructor extends VariableWidthTypeConstructor<Symbol>
         super(size);
     }
 
-    private Symbol constructFromSingleBuffer(final QpidByteBuffer in, final int size)
-    {
-        BinaryString binaryStr;
-        if (in.hasArray())
-        {
-            binaryStr = new BinaryString(in.array(), in.arrayOffset() + in.position(), size);
-        }
-        else
-        {
-            byte[] b = new byte[in.remaining()];
-            QpidByteBuffer dup = in.duplicate();
-            dup.get(b);
-            dup.dispose();
-            binaryStr = new BinaryString(b, 0, b.length);
-        }
-
-        Symbol symbolVal = SYMBOL_MAP.get(binaryStr);
-        if (symbolVal == null)
-        {
-            QpidByteBuffer dup = in.duplicate();
-            dup.limit(in.position() + size);
-            CharBuffer charBuf = dup.decode(ASCII);
-            dup.dispose();
-
-            symbolVal = Symbol.getSymbol(charBuf.toString());
-
-            byte[] data = new byte[size];
-            in.get(data);
-            binaryStr = new BinaryString(data, 0, size);
-            SYMBOL_MAP.putIfAbsent(binaryStr, symbolVal);
-        }
-        else
-        {
-            in.position(in.position() + size);
-        }
-
-        return symbolVal;
-    }
-
     @Override
-    public Symbol construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public Symbol construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
 
         int size;
 
-        if (!QpidByteBufferUtils.hasRemaining(in, getSize()))
+        if (!in.hasRemaining(getSize()))
         {
             throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Cannot construct symbol: insufficient input data");
         }
 
         if (getSize() == 1)
         {
-            size = QpidByteBufferUtils.get(in) & 0xFF;
+            size = in.getUnsignedByte();
         }
         else
         {
-            size = QpidByteBufferUtils.getInt(in);
+            size = in.getInt();
         }
 
-        if (!QpidByteBufferUtils.hasRemaining(in, size))
+        if (!in.hasRemaining(size))
         {
             throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Cannot construct symbol: insufficient input data");
         }
 
-        for (int i = 0; i < in.size(); i++)
-        {
-            QpidByteBuffer buf = in.get(i);
-            if (buf.hasRemaining())
-            {
-                if (buf.remaining() >= size)
-                {
-                    return constructFromSingleBuffer(buf, size);
-                }
-                break;
-            }
-        }
-
         byte[] data = new byte[size];
-        QpidByteBufferUtils.get(in, data);
+        in.get(data);
         final BinaryString binaryStr = new BinaryString(data);
 
         Symbol symbolVal = SYMBOL_MAP.get(binaryStr);

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/TimestampTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/TimestampTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/TimestampTypeConstructor.java
index eae7282..d8e7097 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/TimestampTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/TimestampTypeConstructor.java
@@ -21,10 +21,8 @@
 package org.apache.qpid.server.protocol.v1_0.codec;
 
 import java.util.Date;
-import java.util.List;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 
@@ -43,11 +41,11 @@ public class TimestampTypeConstructor implements TypeConstructor<Date>
     }
 
     @Override
-    public Date construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public Date construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
-        if(QpidByteBufferUtils.hasRemaining(in, 8))
+        if (in.hasRemaining(8))
         {
-            long l = QpidByteBufferUtils.getLong(in);
+            long l = in.getLong();
             return new Date(l);
         }
         else

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/TypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/TypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/TypeConstructor.java
index ae44838..e7daa5e 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/TypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/TypeConstructor.java
@@ -20,14 +20,12 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 
 public interface TypeConstructor<T>
 {
 
-    T construct(final List<QpidByteBuffer> in, ValueHandler handler) throws AmqpErrorException;
+    T construct(final QpidByteBuffer in, ValueHandler handler) throws AmqpErrorException;
 
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UByteTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UByteTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UByteTypeConstructor.java
index e9a2bc5..f64757e 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UByteTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UByteTypeConstructor.java
@@ -20,10 +20,7 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.UnsignedByte;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
@@ -43,11 +40,11 @@ public class UByteTypeConstructor implements TypeConstructor<UnsignedByte>
     }
 
     @Override
-    public UnsignedByte construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public UnsignedByte construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
-        if(QpidByteBufferUtils.hasRemaining(in))
+        if (in.hasRemaining())
         {
-            byte b = QpidByteBufferUtils.get(in);
+            byte b = in.get();
             return UnsignedByte.valueOf(b);
         }
         else

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UIntTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UIntTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UIntTypeConstructor.java
index f8d4c21..d74ac7a 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UIntTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UIntTypeConstructor.java
@@ -20,10 +20,7 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.UnsignedInteger;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
@@ -43,12 +40,12 @@ public class UIntTypeConstructor implements TypeConstructor<UnsignedInteger>
     }
 
     @Override
-    public UnsignedInteger construct(final List<QpidByteBuffer> in, final ValueHandler handler)
+    public UnsignedInteger construct(final QpidByteBuffer in, final ValueHandler handler)
             throws AmqpErrorException
     {
-        if(QpidByteBufferUtils.hasRemaining(in, 4))
+        if (in.hasRemaining(4))
         {
-            final int i = QpidByteBufferUtils.getInt(in);
+            final int i = in.getInt();
             return UnsignedInteger.valueOf(i);
         }
         else

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ULongTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ULongTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ULongTypeConstructor.java
index 5a71935..bbe5f4f 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ULongTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ULongTypeConstructor.java
@@ -20,10 +20,7 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.UnsignedLong;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
@@ -43,11 +40,11 @@ public class ULongTypeConstructor implements TypeConstructor<UnsignedLong>
     }
 
     @Override
-    public UnsignedLong construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public UnsignedLong construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
-        if(QpidByteBufferUtils.hasRemaining(in, 8))
+        if (in.hasRemaining(8))
         {
-            long l = QpidByteBufferUtils.getLong(in);
+            long l = in.getLong();
 
             return UnsignedLong.valueOf(l);
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UShortTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UShortTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UShortTypeConstructor.java
index 8174d5b..ba5fe37 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UShortTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UShortTypeConstructor.java
@@ -20,10 +20,7 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.UnsignedShort;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
@@ -43,11 +40,11 @@ public class UShortTypeConstructor implements TypeConstructor<UnsignedShort>
     }
 
     @Override
-    public UnsignedShort construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public UnsignedShort construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
-        if(QpidByteBufferUtils.hasRemaining(in, 2))
+        if (in.hasRemaining(2))
         {
-            short s = QpidByteBufferUtils.getShort(in);
+            short s = in.getShort();
             return UnsignedShort.valueOf(s);
         }
         else

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UUIDTypeConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UUIDTypeConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UUIDTypeConstructor.java
index ce247fd..b0b6d2b 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UUIDTypeConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/UUIDTypeConstructor.java
@@ -20,11 +20,9 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
 import java.util.UUID;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 
@@ -43,12 +41,12 @@ public class UUIDTypeConstructor implements TypeConstructor<UUID>
     }
 
     @Override
-    public UUID construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public UUID construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
-        if(QpidByteBufferUtils.hasRemaining(in, 16))
+        if (in.hasRemaining(16))
         {
-            long msb = QpidByteBufferUtils.getLong(in);
-            long lsb = QpidByteBufferUtils.getLong(in);
+            long msb = in.getLong();
+            long lsb = in.getLong();
             return new UUID(msb, lsb);
         }
         else

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ValueHandler.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ValueHandler.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ValueHandler.java
index 82b05d5..0aa3a17 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ValueHandler.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ValueHandler.java
@@ -20,13 +20,7 @@
  */
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 import org.apache.qpid.server.protocol.v1_0.type.transport.ConnectionError;
@@ -90,49 +84,21 @@ public class ValueHandler implements DescribedTypeConstructorRegistry.Source
 
     public Object parse(QpidByteBuffer in) throws AmqpErrorException
     {
-        return parse(new ArrayList<>(Collections.singletonList(in)));
-    }
-
-    public Object parse(final List<QpidByteBuffer> in) throws AmqpErrorException
-    {
         TypeConstructor constructor = readConstructor(in);
         return constructor.construct(in, this);
     }
 
-
-    public TypeConstructor readConstructor(List<QpidByteBuffer> in) throws AmqpErrorException
+    public TypeConstructor readConstructor(QpidByteBuffer in) throws AmqpErrorException
     {
-        if(!QpidByteBufferUtils.hasRemaining(in))
+        if(!in.hasRemaining())
         {
             throw new AmqpErrorException(AmqpError.DECODE_ERROR, "Insufficient data - expected type, no data remaining");
         }
-        int firstBufferWithAvailable = 0;
-        if(in.size() > 1)
-        {
-            for(int i = 0; i < in.size(); i++)
-            {
-                if(in.get(i).hasRemaining())
-                {
-                    firstBufferWithAvailable = i;
-                    break;
-                }
-            }
-        }
-        byte formatCode = QpidByteBufferUtils.get(in);
+        byte formatCode = in.get();
 
         if(formatCode == DESCRIBED_TYPE)
         {
-            int[] originalPositions = new int[in.size()-firstBufferWithAvailable];
-
-            for(int i = firstBufferWithAvailable; i < in.size(); i++)
-            {
-                int position = in.get(i).position();
-                if(i==firstBufferWithAvailable)
-                {
-                    position--;
-                }
-                originalPositions[i - firstBufferWithAvailable] = position;
-            }
+            int originalPositions = in.position() - 1;
 
             Object descriptor = parse(in);
             DescribedTypeConstructor describedTypeConstructor = _describedTypeConstructorRegistry.getConstructor(descriptor);

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ZeroListConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ZeroListConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ZeroListConstructor.java
index 7dd19a1..2392fb9 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ZeroListConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ZeroListConstructor.java
@@ -33,7 +33,7 @@ class ZeroListConstructor implements TypeConstructor<List>
     }
 
     @Override
-    public List construct(final List<QpidByteBuffer> in, final ValueHandler handler)
+    public List construct(final QpidByteBuffer in, final ValueHandler handler)
     {
         return Collections.EMPTY_LIST;
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ZeroUIntConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ZeroUIntConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ZeroUIntConstructor.java
index f3d62e3..3a624f8 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ZeroUIntConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ZeroUIntConstructor.java
@@ -19,10 +19,8 @@
 
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
-import org.apache.qpid.server.protocol.v1_0.type.UnsignedInteger;
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
+import org.apache.qpid.server.protocol.v1_0.type.UnsignedInteger;
 
 class ZeroUIntConstructor implements TypeConstructor<UnsignedInteger>
 {
@@ -33,7 +31,7 @@ class ZeroUIntConstructor implements TypeConstructor<UnsignedInteger>
     }
 
     @Override
-    public UnsignedInteger construct(final List<QpidByteBuffer> in, final ValueHandler handler)
+    public UnsignedInteger construct(final QpidByteBuffer in, final ValueHandler handler)
     {
         return UnsignedInteger.ZERO;
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ZeroULongConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ZeroULongConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ZeroULongConstructor.java
index 730bd63..11e0df7 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ZeroULongConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/codec/ZeroULongConstructor.java
@@ -19,10 +19,8 @@
 
 package org.apache.qpid.server.protocol.v1_0.codec;
 
-import java.util.List;
-
-import org.apache.qpid.server.protocol.v1_0.type.UnsignedLong;
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
+import org.apache.qpid.server.protocol.v1_0.type.UnsignedLong;
 
 class ZeroULongConstructor implements TypeConstructor<UnsignedLong>
 {
@@ -33,7 +31,7 @@ class ZeroULongConstructor implements TypeConstructor<UnsignedLong>
     }
 
     @Override
-    public UnsignedLong construct(final List<QpidByteBuffer> in, final ValueHandler handler)
+    public UnsignedLong construct(final QpidByteBuffer in, final ValueHandler handler)
     {
         return UnsignedLong.ZERO;
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/framing/AMQFrame.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/framing/AMQFrame.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/framing/AMQFrame.java
index 7d0f28e..ca42eee 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/framing/AMQFrame.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/framing/AMQFrame.java
@@ -21,28 +21,26 @@
 
 package org.apache.qpid.server.protocol.v1_0.framing;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.type.FrameBody;
 
 public abstract class AMQFrame<T>
 {
     private final T _frameBody;
-    private List<QpidByteBuffer> _payload;
+    private final QpidByteBuffer _payload;
 
     AMQFrame(T frameBody)
     {
-        _frameBody = frameBody;
+        this(frameBody, null);
     }
 
-    protected AMQFrame(T frameBody, List<QpidByteBuffer> payload)
+    protected AMQFrame(T frameBody, QpidByteBuffer payload)
     {
         _frameBody = frameBody;
         _payload = payload;
     }
 
-    public List<QpidByteBuffer> getPayload()
+    public QpidByteBuffer getPayload()
     {
         return _payload;
     }
@@ -52,7 +50,7 @@ public abstract class AMQFrame<T>
         return createAMQFrame(channel, frameBody, null);
     }
 
-    public static TransportFrame createAMQFrame(int channel, FrameBody frameBody, List<QpidByteBuffer> payload)
+    public static TransportFrame createAMQFrame(int channel, FrameBody frameBody, QpidByteBuffer payload)
     {
         return new TransportFrame(channel, frameBody, payload);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/framing/FrameHandler.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/framing/FrameHandler.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/framing/FrameHandler.java
index 6dd69bd..f7e4029 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/framing/FrameHandler.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/framing/FrameHandler.java
@@ -21,7 +21,6 @@
 package org.apache.qpid.server.protocol.v1_0.framing;
 
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.Formatter;
 import java.util.List;
 
@@ -149,12 +148,11 @@ public class FrameHandler implements ProtocolHandler
                     in.position(in.position() + dataOffset - 8);
                 }
 
-                QpidByteBuffer dup = in.slice();
-                dup.limit(size - dataOffset);
-                in.position(in.position() + size - dataOffset);
-
-                try
+                try (QpidByteBuffer dup = in.slice())
                 {
+                    dup.limit(size - dataOffset);
+                    in.position(in.position() + size - dataOffset);
+
                     final boolean hasFrameBody = dup.hasRemaining();
                     Object frameBody;
                     if (hasFrameBody)
@@ -164,9 +162,10 @@ public class FrameHandler implements ProtocolHandler
                         {
                             if (frameBody instanceof Transfer)
                             {
-                                final QpidByteBuffer payload = dup.slice();
-                                ((Transfer) frameBody).setPayload(Collections.singletonList(payload));
-                                payload.dispose();
+                                try (QpidByteBuffer payload = dup.slice())
+                                {
+                                    ((Transfer) frameBody).setPayload(payload);
+                                }
                             }
                             else
                             {
@@ -208,10 +207,6 @@ public class FrameHandler implements ProtocolHandler
                 {
                     frameParsingError = ex.getError();
                 }
-                finally
-                {
-                    dup.dispose();
-                }
             }
             _connectionHandler.receive(channelFrameBodies);
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/framing/TransportFrame.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/framing/TransportFrame.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/framing/TransportFrame.java
index e29c92c..44f72dd 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/framing/TransportFrame.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/framing/TransportFrame.java
@@ -18,8 +18,6 @@
  */
 package org.apache.qpid.server.protocol.v1_0.framing;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.type.FrameBody;
 
@@ -34,7 +32,7 @@ public final class TransportFrame extends AMQFrame<FrameBody>
         _channel = channel;
     }
 
-    public TransportFrame(int channel, FrameBody frameBody, List<QpidByteBuffer> payload)
+    public TransportFrame(int channel, FrameBody frameBody, QpidByteBuffer payload)
     {
         super(frameBody, payload);
         _channel = channel;

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/messaging/SectionDecoder.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/messaging/SectionDecoder.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/messaging/SectionDecoder.java
index 34d97e4..dfe80bd 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/messaging/SectionDecoder.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/messaging/SectionDecoder.java
@@ -28,5 +28,5 @@ import org.apache.qpid.server.protocol.v1_0.type.messaging.EncodingRetainingSect
 
 public interface SectionDecoder
 {
-    List<EncodingRetainingSection<?>> parseAll(List<QpidByteBuffer> buf) throws AmqpErrorException;
+    List<EncodingRetainingSection<?>> parseAll(QpidByteBuffer buf) throws AmqpErrorException;
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/messaging/SectionDecoderImpl.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/messaging/SectionDecoderImpl.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/messaging/SectionDecoderImpl.java
index 567c300..00fde2e 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/messaging/SectionDecoderImpl.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/messaging/SectionDecoderImpl.java
@@ -23,7 +23,6 @@ import java.util.ArrayList;
 import java.util.List;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.codec.SectionDecoderRegistry;
 import org.apache.qpid.server.protocol.v1_0.codec.ValueHandler;
 import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
@@ -42,27 +41,38 @@ public class SectionDecoderImpl implements SectionDecoder
     }
 
     @Override
-    public List<EncodingRetainingSection<?>> parseAll(List<QpidByteBuffer> buf) throws AmqpErrorException
+    public List<EncodingRetainingSection<?>> parseAll(QpidByteBuffer buf) throws AmqpErrorException
     {
 
         List<EncodingRetainingSection<?>> obj = new ArrayList<>();
-        while(QpidByteBufferUtils.hasRemaining(buf))
+        try
         {
-
-            final Object parsedObject = _valueHandler.parse(buf);
-            if (parsedObject instanceof EncodingRetainingSection)
+            while (buf.hasRemaining())
             {
-                EncodingRetainingSection<?> section = (EncodingRetainingSection<?>) parsedObject;
-                obj.add(section);
+
+                final Object parsedObject = _valueHandler.parse(buf);
+                if (parsedObject instanceof EncodingRetainingSection)
+                {
+                    EncodingRetainingSection<?> section = (EncodingRetainingSection<?>) parsedObject;
+                    obj.add(section);
+                }
+                else
+                {
+                    throw new AmqpErrorException(AmqpError.DECODE_ERROR,
+                                                 String.format(
+                                                         "Invalid Message: Expected type \"section\" but found \"%s\"",
+                                                         parsedObject.getClass().getSimpleName()));
+                }
             }
-            else
+        }
+        catch (AmqpErrorException e)
+        {
+            for (EncodingRetainingSection<?> encodingRetainingSection : obj)
             {
-                throw new AmqpErrorException(AmqpError.DECODE_ERROR,
-                                             String.format("Invalid Message: Expected type \"section\" but found \"%s\"",
-                                                           parsedObject.getClass().getSimpleName()));
+                encodingRetainingSection.dispose();
             }
+            throw e;
         }
-
         return obj;
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/store/LinkStoreUtils.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/store/LinkStoreUtils.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/store/LinkStoreUtils.java
index 9db2d16..6e7ccf4 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/store/LinkStoreUtils.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/store/LinkStoreUtils.java
@@ -33,33 +33,25 @@ public class LinkStoreUtils
 
     public static Object amqpBytesToObject(final byte[] bytes)
     {
-        QpidByteBuffer qpidByteBuffer = QpidByteBuffer.wrap(bytes);
         ValueHandler valueHandler = new ValueHandler(DESCRIBED_TYPE_REGISTRY);
-        Object object;
-        try
+        try (QpidByteBuffer qpidByteBuffer = QpidByteBuffer.wrap(bytes))
         {
-            object = valueHandler.parse(qpidByteBuffer);
+            return valueHandler.parse(qpidByteBuffer);
         }
         catch (AmqpErrorException e)
         {
             throw new StoreException("Unexpected serialized data", e);
         }
-        finally
-        {
-            qpidByteBuffer.dispose();
-        }
-        return object;
     }
 
     public static byte[] objectToAmqpBytes(final Object object)
     {
         ValueWriter valueWriter = DESCRIBED_TYPE_REGISTRY.getValueWriter(object);
         int encodedSize = valueWriter.getEncodedSize();
-        QpidByteBuffer qpidByteBuffer = QpidByteBuffer.allocate(encodedSize);
-        valueWriter.writeToBuffer(qpidByteBuffer);
-
-        byte[] bytes = qpidByteBuffer.array();
-        qpidByteBuffer.dispose();
-        return bytes;
+        try (QpidByteBuffer qpidByteBuffer = QpidByteBuffer.allocate(encodedSize))
+        {
+            valueWriter.writeToBuffer(qpidByteBuffer);
+            return qpidByteBuffer.array();
+        }
     }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AbstractSection.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AbstractSection.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AbstractSection.java
index c6a7be9..d82f143 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AbstractSection.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AbstractSection.java
@@ -20,12 +20,7 @@
  */
 package org.apache.qpid.server.protocol.v1_0.type.messaging;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
-import org.apache.qpid.server.bytebuffer.QpidByteBufferUtils;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructor;
 import org.apache.qpid.server.protocol.v1_0.codec.ValueHandler;
 import org.apache.qpid.server.protocol.v1_0.messaging.SectionEncoder;
@@ -45,19 +40,14 @@ public abstract class AbstractSection<T, S extends NonEncodingRetainingSection<T
     private T _value;
 
     private S _section;
-    private List<QpidByteBuffer> _encodedForm;
+    private QpidByteBuffer _encodedForm;
     // _encodedSize is valid only when _encodedForm is non-null
     private long _encodedSize = 0;
 
-    protected AbstractSection(final List<QpidByteBuffer> encodedForm)
+    protected AbstractSection(final QpidByteBuffer encodedForm)
     {
-        _encodedForm = new ArrayList<>();
-        _encodedSize = 0;
-        for(QpidByteBuffer encodedChunk : encodedForm)
-        {
-            _encodedSize += encodedChunk.remaining();
-            _encodedForm.add(encodedChunk.duplicate());
-        }
+        _encodedForm = encodedForm.duplicate();
+        _encodedSize = encodedForm.remaining();
     }
 
     protected AbstractSection(final S section)
@@ -72,7 +62,7 @@ public abstract class AbstractSection<T, S extends NonEncodingRetainingSection<T
         _value = otherAbstractSection.getValue();
         _section = otherAbstractSection._section;
         _encodedForm = otherAbstractSection.getEncodedForm();
-        _encodedSize = QpidByteBufferUtils.remaining(_encodedForm);
+        _encodedSize = _encodedForm.remaining();
     }
 
     protected abstract DescribedTypeConstructor<S> createNonEncodingRetainingSectionConstructor();
@@ -89,15 +79,10 @@ public abstract class AbstractSection<T, S extends NonEncodingRetainingSection<T
     }
 
     @Override
-    public synchronized final List<QpidByteBuffer> getEncodedForm()
+    public synchronized final QpidByteBuffer getEncodedForm()
     {
         encodeIfNecessary();
-        List<QpidByteBuffer> returnVal = new ArrayList<>(_encodedForm.size());
-        for(int i = 0; i < _encodedForm.size(); i++)
-        {
-            returnVal.add(_encodedForm.get(i).duplicate());
-        }
-        return returnVal;
+        return _encodedForm.duplicate();
     }
 
     @Override
@@ -111,10 +96,7 @@ public abstract class AbstractSection<T, S extends NonEncodingRetainingSection<T
     public synchronized void writeTo(final QpidByteBuffer dest)
     {
         encodeIfNecessary();
-        for(QpidByteBuffer buf : _encodedForm)
-        {
-            dest.putCopyOf(buf);
-        }
+        dest.putCopyOf(_encodedForm);
     }
 
     @Override
@@ -123,10 +105,7 @@ public abstract class AbstractSection<T, S extends NonEncodingRetainingSection<T
         if (_encodedForm != null)
         {
             _section = decode(createNonEncodingRetainingSectionConstructor());
-            for (int i = 0; i < _encodedForm.size(); i++)
-            {
-                _encodedForm.get(i).dispose();
-            }
+            _encodedForm.dispose();
             _encodedForm = null;
             _encodedSize = 0;
         }
@@ -145,10 +124,7 @@ public abstract class AbstractSection<T, S extends NonEncodingRetainingSection<T
         _value = null;
         if (_encodedForm != null)
         {
-            for (int i = 0; i < _encodedForm.size(); i++)
-            {
-                _encodedForm.get(i).dispose();
-            }
+            _encodedForm.dispose();
             _encodedForm = null;
             _encodedSize = 0;
         }
@@ -157,7 +133,14 @@ public abstract class AbstractSection<T, S extends NonEncodingRetainingSection<T
     @Override
     public String toString()
     {
-        return getValue().toString();
+        if (_value == null)
+        {
+            return String.format("<Undecoded %s (%d bytes)>", getClass().getSimpleName(), _encodedSize);
+        }
+        else
+        {
+            return getValue().toString();
+        }
     }
 
     private void encodeIfNecessary()
@@ -165,41 +148,33 @@ public abstract class AbstractSection<T, S extends NonEncodingRetainingSection<T
         if (_encodedForm == null)
         {
             SectionEncoder sectionEncoder = new SectionEncoderImpl(TYPE_REGISTRY);
-            _encodedForm = Collections.singletonList(sectionEncoder.encodeObject(_section));
-            _encodedSize = QpidByteBufferUtils.remaining(_encodedForm);
+            _encodedForm = sectionEncoder.encodeObject(_section);
+            _encodedSize = _encodedForm.remaining();
         }
     }
 
     private S decode(DescribedTypeConstructor<S> constructor)
     {
-        List<QpidByteBuffer> input = getEncodedForm();
-        int[] originalPositions = new int[input.size()];
-        for(int i = 0; i < input.size(); i++)
-        {
-            originalPositions[i] = input.get(i).position();
-        }
-        int describedByte = QpidByteBufferUtils.get(input);
-        if (describedByte != ValueHandler.DESCRIBED_TYPE)
-        {
-            throw new ConnectionScopedRuntimeException("Cannot decode section",
-                                                       new AmqpErrorException(AmqpError.DECODE_ERROR,
-                                                                              "Not a described type."));
-        }
-        ValueHandler handler = new ValueHandler(TYPE_REGISTRY);
-        try
-        {
-            Object descriptor = handler.parse(input);
-            return constructor.construct(descriptor, input, originalPositions, handler).construct(input, handler);
-        }
-        catch (AmqpErrorException e)
+        try (QpidByteBuffer input = getEncodedForm())
         {
-            throw new ConnectionScopedRuntimeException("Cannot decode section", e);
-        }
-        finally
-        {
-            for (QpidByteBuffer anInput : input)
+
+            int originalPosition = input.position();
+            int describedByte = input.get();
+            if (describedByte != ValueHandler.DESCRIBED_TYPE)
+            {
+                throw new ConnectionScopedRuntimeException("Cannot decode section",
+                                                           new AmqpErrorException(AmqpError.DECODE_ERROR,
+                                                                                  "Not a described type."));
+            }
+            ValueHandler handler = new ValueHandler(TYPE_REGISTRY);
+            try
+            {
+                Object descriptor = handler.parse(input);
+                return constructor.construct(descriptor, input, originalPosition, handler).construct(input, handler);
+            }
+            catch (AmqpErrorException e)
             {
-                anInput.dispose();
+                throw new ConnectionScopedRuntimeException("Cannot decode section", e);
             }
         }
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AmqpSequenceSection.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AmqpSequenceSection.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AmqpSequenceSection.java
index 559e868..79e81fc 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AmqpSequenceSection.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AmqpSequenceSection.java
@@ -29,7 +29,7 @@ import org.apache.qpid.server.protocol.v1_0.type.messaging.codec.AmqpSequenceCon
 
 public class AmqpSequenceSection extends AbstractSection<List, AmqpSequence>
 {
-    public AmqpSequenceSection(final List<QpidByteBuffer> encodedForm)
+    public AmqpSequenceSection(final QpidByteBuffer encodedForm)
     {
         super(encodedForm);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AmqpValueSection.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AmqpValueSection.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AmqpValueSection.java
index 2b4ab35..ad99d46 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AmqpValueSection.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/AmqpValueSection.java
@@ -21,15 +21,13 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructor;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.codec.AmqpValueConstructor;
 
 public class AmqpValueSection extends AbstractSection<Object, AmqpValue>
 {
-    public AmqpValueSection(final List<QpidByteBuffer> encodedForm)
+    public AmqpValueSection(final QpidByteBuffer encodedForm)
     {
         super(encodedForm);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/ApplicationPropertiesSection.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/ApplicationPropertiesSection.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/ApplicationPropertiesSection.java
index 8dabc40..b8da5bd 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/ApplicationPropertiesSection.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/ApplicationPropertiesSection.java
@@ -21,7 +21,6 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging;
 
-import java.util.List;
 import java.util.Map;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
@@ -31,7 +30,7 @@ import org.apache.qpid.server.protocol.v1_0.type.messaging.codec.ApplicationProp
 public class ApplicationPropertiesSection extends AbstractSection<Map<String,Object>, ApplicationProperties>
 {
 
-    public ApplicationPropertiesSection(final List<QpidByteBuffer> encodedForm)
+    public ApplicationPropertiesSection(final QpidByteBuffer encodedForm)
     {
         super(encodedForm);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/DataSection.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/DataSection.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/DataSection.java
index cf07dc6..4d167f4 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/DataSection.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/DataSection.java
@@ -21,8 +21,6 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructor;
 import org.apache.qpid.server.protocol.v1_0.type.Binary;
@@ -30,7 +28,7 @@ import org.apache.qpid.server.protocol.v1_0.type.messaging.codec.DataConstructor
 
 public class DataSection extends AbstractSection<Binary, Data>
 {
-    public DataSection(final List<QpidByteBuffer> encodedForm)
+    public DataSection(final QpidByteBuffer encodedForm)
     {
         super(encodedForm);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/DeliveryAnnotationsSection.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/DeliveryAnnotationsSection.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/DeliveryAnnotationsSection.java
index 7c2ad51..86f1457 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/DeliveryAnnotationsSection.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/DeliveryAnnotationsSection.java
@@ -21,7 +21,6 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging;
 
-import java.util.List;
 import java.util.Map;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
@@ -31,7 +30,7 @@ import org.apache.qpid.server.protocol.v1_0.type.messaging.codec.DeliveryAnnotat
 
 public class DeliveryAnnotationsSection extends AbstractSection<Map<Symbol,Object>, DeliveryAnnotations>
 {
-    public DeliveryAnnotationsSection(final List<QpidByteBuffer> encodedForm)
+    public DeliveryAnnotationsSection(final QpidByteBuffer encodedForm)
     {
         super(encodedForm);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/FooterSection.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/FooterSection.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/FooterSection.java
index 01671b3..61dfe44 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/FooterSection.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/FooterSection.java
@@ -21,7 +21,6 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging;
 
-import java.util.List;
 import java.util.Map;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
@@ -31,7 +30,7 @@ import org.apache.qpid.server.protocol.v1_0.type.messaging.codec.FooterConstruct
 
 public class FooterSection extends AbstractSection<Map<Symbol,Object>, Footer>
 {
-    public FooterSection(final List<QpidByteBuffer> encodedForm)
+    public FooterSection(final QpidByteBuffer encodedForm)
     {
         super(encodedForm);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/HeaderSection.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/HeaderSection.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/HeaderSection.java
index cac9734..9f479e4 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/HeaderSection.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/HeaderSection.java
@@ -21,15 +21,13 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructor;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.codec.HeaderConstructor;
 
 public class HeaderSection extends AbstractSection<Header, Header>
 {
-    public HeaderSection(final List<QpidByteBuffer> encodedForm)
+    public HeaderSection(final QpidByteBuffer encodedForm)
     {
         super(encodedForm);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/MessageAnnotationsSection.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/MessageAnnotationsSection.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/MessageAnnotationsSection.java
index a90ce15..4f0d9a8 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/MessageAnnotationsSection.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/MessageAnnotationsSection.java
@@ -21,7 +21,6 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging;
 
-import java.util.List;
 import java.util.Map;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
@@ -31,7 +30,7 @@ import org.apache.qpid.server.protocol.v1_0.type.messaging.codec.MessageAnnotati
 
 public class MessageAnnotationsSection extends AbstractSection<Map<Symbol,Object>, MessageAnnotations>
 {
-    public MessageAnnotationsSection(final List<QpidByteBuffer> encodedForm)
+    public MessageAnnotationsSection(final QpidByteBuffer encodedForm)
     {
         super(encodedForm);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/PropertiesSection.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/PropertiesSection.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/PropertiesSection.java
index 4c2b36b..616f1fa 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/PropertiesSection.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/PropertiesSection.java
@@ -21,15 +21,13 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructor;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.codec.PropertiesConstructor;
 
 public class PropertiesSection extends AbstractSection<Properties, Properties>
 {
-    public PropertiesSection(final List<QpidByteBuffer> encodedForm)
+    public PropertiesSection(final QpidByteBuffer encodedForm)
     {
         super(encodedForm);
     }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/AbstractLazyConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/AbstractLazyConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/AbstractLazyConstructor.java
index 3b80153..59e0e25 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/AbstractLazyConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/AbstractLazyConstructor.java
@@ -20,9 +20,6 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging.codec;
 
-import java.util.ArrayList;
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.codec.TypeConstructor;
 import org.apache.qpid.server.protocol.v1_0.codec.ValueHandler;
@@ -30,47 +27,28 @@ import org.apache.qpid.server.protocol.v1_0.type.AmqpErrorException;
 
 public abstract class AbstractLazyConstructor<T> implements TypeConstructor<T>
 {
-    private final int[] _originalPositions;
+    private final int _originalPosition;
 
-    AbstractLazyConstructor(final int[] originalPositions)
+    AbstractLazyConstructor(final int originalPosition)
     {
-        _originalPositions = originalPositions;
+        _originalPosition = originalPosition;
     }
 
     @Override
-    public final T construct(final List<QpidByteBuffer> in, final ValueHandler handler) throws AmqpErrorException
+    public final T construct(final QpidByteBuffer in, final ValueHandler handler) throws AmqpErrorException
     {
         skipValue(in);
 
-        List<QpidByteBuffer> encoding = new ArrayList<>();
-        int offset = in.size() - _originalPositions.length;
-        for (int i = offset; i < in.size(); i++)
-        {
-            QpidByteBuffer buf = in.get(i);
-            if (buf.position() == _originalPositions[i - offset])
-            {
-                if (buf.hasRemaining())
-                {
-                    break;
-                }
-            }
-            else
-            {
-                QpidByteBuffer dup = buf.duplicate();
-                dup.position(_originalPositions[i - offset]);
-                dup.limit(buf.position());
-                encoding.add(dup);
-            }
-        }
-        T object = createObject(encoding, handler);
-        for (QpidByteBuffer buffer : encoding)
+        try (QpidByteBuffer encoding = in.duplicate())
         {
-            buffer.dispose();
+            encoding.position(_originalPosition);
+            encoding.limit(in.position());
+
+            return createObject(encoding, handler);
         }
-        return object;
     }
 
-    protected abstract T createObject(final List<QpidByteBuffer> encoding, final ValueHandler handler);
+    protected abstract T createObject(final QpidByteBuffer encoding, final ValueHandler handler);
 
-    protected abstract void skipValue(final List<QpidByteBuffer> in) throws AmqpErrorException;
+    protected abstract void skipValue(final QpidByteBuffer in) throws AmqpErrorException;
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/660c206d/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/AmqpSequenceSectionConstructor.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/AmqpSequenceSectionConstructor.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/AmqpSequenceSectionConstructor.java
index 6158c6a..d7cc006 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/AmqpSequenceSectionConstructor.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/type/messaging/codec/AmqpSequenceSectionConstructor.java
@@ -23,8 +23,6 @@
 
 package org.apache.qpid.server.protocol.v1_0.type.messaging.codec;
 
-import java.util.List;
-
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.codec.DescribedTypeConstructorRegistry;
 import org.apache.qpid.server.protocol.v1_0.type.Symbol;
@@ -49,7 +47,7 @@ public class AmqpSequenceSectionConstructor extends DescribedListSectionConstruc
     }
 
     @Override
-    protected AmqpSequenceSection createObject(final List<QpidByteBuffer> encodedForm)
+    protected AmqpSequenceSection createObject(final QpidByteBuffer encodedForm)
     {
         return new AmqpSequenceSection(encodedForm);
     }


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@qpid.apache.org
For additional commands, e-mail: commits-help@qpid.apache.org