You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@qpid.apache.org by or...@apache.org on 2018/01/29 14:27:09 UTC

[01/11] qpid-broker-j git commit: QPID-8032: [Broker-J][AMQP 1.0] Use asynchronous auto commit transaction for non-transactional transfers

Repository: qpid-broker-j
Updated Branches:
  refs/heads/7.0.x 0c04fdc90 -> 4e6c44d10


QPID-8032: [Broker-J][AMQP 1.0] Use asynchronous auto commit transaction for non-transactional transfers

Currently each disposition returned singly.

(cherry picked from commit bce2424df9c8fdef3d1714ff1f760f11859f298d)


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/cf30e227
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/cf30e227
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/cf30e227

Branch: refs/heads/7.0.x
Commit: cf30e227b8e05787d6a95fcd138b879823fda455
Parents: 0c04fdc
Author: Alex Rudyy <or...@apache.org>
Authored: Fri Jan 12 15:34:42 2018 +0000
Committer: Alex Rudyy <or...@apache.org>
Committed: Mon Jan 29 13:55:23 2018 +0000

----------------------------------------------------------------------
 .../protocol/v1_0/AMQPConnection_1_0.java       |   2 +
 .../protocol/v1_0/AMQPConnection_1_0Impl.java   |  75 +++++++----
 .../v1_0/AbstractReceivingLinkEndpoint.java     |   6 +-
 .../protocol/v1_0/ErrantLinkEndpoint.java       |   4 +
 .../qpid/server/protocol/v1_0/LinkEndpoint.java |   2 +
 .../protocol/v1_0/SendingLinkEndpoint.java      |   7 +-
 .../qpid/server/protocol/v1_0/Session_1_0.java  |  17 ++-
 .../v1_0/StandardReceivingLinkEndpoint.java     | 109 +++++++++++++++-
 .../TxnCoordinatorReceivingLinkEndpoint.java    |   8 ++
 .../protocol/v1_0/messaging/TransferTest.java   | 124 +++++++++++++++++++
 10 files changed, 320 insertions(+), 34 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cf30e227/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 53f47d1..665ee0a 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
@@ -84,6 +84,8 @@ public interface AMQPConnection_1_0<C extends AMQPConnection_1_0<C>> extends AMQ
     ServerTransaction getTransaction(int txnId);
     void removeTransaction(int txnId);
 
+    void receivedComplete();
+
     @DerivedAttribute(description = "If true send a final SASL challenge using a SaslChallenge performative, rather than SaslOutcome.")
     boolean getSendSaslFinalChallengeAsChallenge();
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cf30e227/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 b2384bd..9091456 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
@@ -1295,35 +1295,42 @@ public class AMQPConnection_1_0Impl extends AbstractAMQPConnection<AMQPConnectio
             {
                 int remaining;
 
-                do
+                try
                 {
-                    remaining = msg.remaining();
-
-                    switch (_connectionState)
+                    do
                     {
-                        case AWAIT_AMQP_OR_SASL_HEADER:
-                        case AWAIT_AMQP_HEADER:
-                            if (remaining >= 8)
-                            {
-                                processProtocolHeader(msg);
-                            }
-                            break;
-                        case AWAIT_SASL_INIT:
-                        case AWAIT_SASL_RESPONSE:
-                        case AWAIT_OPEN:
-                        case OPENED:
-                        case CLOSE_SENT:
-                            _frameHandler.parse(msg);
-                            break;
-                        case CLOSE_RECEIVED:
-                        case CLOSED:
-                            // ignore;
-                            break;
-                    }
+                        remaining = msg.remaining();
+
+                        switch (_connectionState)
+                        {
+                            case AWAIT_AMQP_OR_SASL_HEADER:
+                            case AWAIT_AMQP_HEADER:
+                                if (remaining >= 8)
+                                {
+                                    processProtocolHeader(msg);
+                                }
+                                break;
+                            case AWAIT_SASL_INIT:
+                            case AWAIT_SASL_RESPONSE:
+                            case AWAIT_OPEN:
+                            case OPENED:
+                            case CLOSE_SENT:
+                                _frameHandler.parse(msg);
+                                break;
+                            case CLOSE_RECEIVED:
+                            case CLOSED:
+                                // ignore;
+                                break;
+                        }
 
 
+                    }
+                    while (msg.remaining() != remaining);
+                }
+                finally
+                {
+                    receivedComplete();
                 }
-                while (msg.remaining() != remaining);
             }
             catch (IllegalArgumentException | IllegalStateException e)
             {
@@ -1345,6 +1352,26 @@ public class AMQPConnection_1_0Impl extends AbstractAMQPConnection<AMQPConnectio
 
     }
 
+    @Override
+    public void receivedComplete()
+    {
+        if (_receivingSessions != null)
+        {
+            for (final Session_1_0 session : _receivingSessions)
+            {
+                if (session != null)
+                {
+                    final AccessControlContext context = session.getAccessControllerContext();
+                    AccessController.doPrivileged((PrivilegedAction<Void>) () ->
+                    {
+                        session.receivedComplete();
+                        return null;
+                    }, context);
+                }
+            }
+        }
+    }
+
     private void processProtocolHeader(final QpidByteBuffer msg)
     {
         if(msg.remaining() >= 8)

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cf30e227/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 1579573..aec18ad 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
@@ -291,9 +291,9 @@ public abstract class AbstractReceivingLinkEndpoint<T extends BaseTarget> extend
         return _unsettled.remove(deliveryTag) != null;
     }
 
-    public void updateDisposition(final Binary deliveryTag,
-                                  final DeliveryState state,
-                                  final boolean settled)
+    void updateDisposition(final Binary deliveryTag,
+                           final DeliveryState state,
+                           final boolean settled)
     {
         if (_unsettled.containsKey(deliveryTag))
         {

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cf30e227/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ErrantLinkEndpoint.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ErrantLinkEndpoint.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ErrantLinkEndpoint.java
index 961244d..1bd9604 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ErrantLinkEndpoint.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ErrantLinkEndpoint.java
@@ -180,4 +180,8 @@ public class ErrantLinkEndpoint<S extends BaseSource, T extends BaseTarget> impl
         throw new UnsupportedOperationException("This Link is errant");
     }
 
+    @Override
+    public void receiveComplete()
+    {
+    }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cf30e227/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/LinkEndpoint.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/LinkEndpoint.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/LinkEndpoint.java
index 94e3b1e..d73319d 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/LinkEndpoint.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/LinkEndpoint.java
@@ -74,4 +74,6 @@ public interface LinkEndpoint<S extends BaseSource, T extends BaseTarget>
     SenderSettleMode getSendingSettlementMode();
 
     ReceiverSettleMode getReceivingSettlementMode();
+
+    void receiveComplete();
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cf30e227/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLinkEndpoint.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLinkEndpoint.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLinkEndpoint.java
index 095062d..ee1f800 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLinkEndpoint.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLinkEndpoint.java
@@ -609,7 +609,7 @@ public class SendingLinkEndpoint extends AbstractLinkEndpoint<Source, Target>
                && getSession().hasCreditToSend();
     }
 
-    public void updateDisposition(final Binary deliveryTag, DeliveryState state, boolean settled)
+    void updateDisposition(final Binary deliveryTag, DeliveryState state, boolean settled)
     {
         if (settled && (_unsettled.remove(deliveryTag) != null))
         {
@@ -906,6 +906,11 @@ public class SendingLinkEndpoint extends AbstractLinkEndpoint<Source, Target>
         super.detach(error, close);
     }
 
+    @Override
+    public void receiveComplete()
+    {
+    }
+
     private static class OutgoingDelivery
     {
         private final MessageInstance _messageInstance;

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cf30e227/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 e52452a..50b681d 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
@@ -182,6 +182,7 @@ public class Session_1_0 extends AbstractAMQPSession<Session_1_0, ConsumerTarget
 
     public void receiveAttach(final Attach attach)
     {
+        receivedComplete();
         if(_sessionState == SessionState.ACTIVE)
         {
             UnsignedInteger inputHandle = attach.getHandle();
@@ -210,10 +211,10 @@ public class Session_1_0 extends AbstractAMQPSession<Session_1_0, ConsumerTarget
         }
     }
 
-    void updateDisposition(final Role role,
-                                  final UnsignedInteger first,
-                                  final UnsignedInteger last,
-                                  final DeliveryState state, final boolean settled)
+    private void updateDisposition(final Role role,
+                                   final UnsignedInteger first,
+                                   final UnsignedInteger last,
+                                   final DeliveryState state, final boolean settled)
     {
 
 
@@ -319,6 +320,7 @@ public class Session_1_0 extends AbstractAMQPSession<Session_1_0, ConsumerTarget
 
     public void receiveEnd(final End end)
     {
+        receivedComplete();
         switch (_sessionState)
         {
             case END_SENT:
@@ -372,6 +374,7 @@ public class Session_1_0 extends AbstractAMQPSession<Session_1_0, ConsumerTarget
 
     public void receiveFlow(final Flow flow)
     {
+        receivedComplete();
         final SequenceNumber flowNextIncomingId = new SequenceNumber(flow.getNextIncomingId() == null
                                                                              ? _initialOutgoingId.intValue()
                                                                              : flow.getNextIncomingId().intValue());
@@ -500,6 +503,7 @@ public class Session_1_0 extends AbstractAMQPSession<Session_1_0, ConsumerTarget
 
     public void receiveDetach(final Detach detach)
     {
+        receivedComplete();
         UnsignedInteger handle = detach.getHandle();
         detach(handle, detach);
     }
@@ -1281,6 +1285,11 @@ public class Session_1_0 extends AbstractAMQPSession<Session_1_0, ConsumerTarget
         return _incomingDeliveryRegistry;
     }
 
+    void receivedComplete()
+    {
+        _associatedLinkEndpoints.forEach(linkedEnpoint -> linkedEnpoint.receiveComplete());
+    }
+
     private class EndpointCreationCallback<T extends LinkEndpoint<? extends BaseSource, ? extends BaseTarget>> implements FutureCallback<T>
     {
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cf30e227/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 7dcf31a..bc18bfb 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
@@ -25,9 +25,13 @@ import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
+import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
+import java.util.concurrent.ExecutionException;
 
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -60,17 +64,22 @@ import org.apache.qpid.server.protocol.v1_0.type.transport.Attach;
 import org.apache.qpid.server.protocol.v1_0.type.transport.Detach;
 import org.apache.qpid.server.protocol.v1_0.type.transport.Error;
 import org.apache.qpid.server.protocol.v1_0.type.transport.ReceiverSettleMode;
+import org.apache.qpid.server.txn.AsyncAutoCommitTransaction;
 import org.apache.qpid.server.txn.AutoCommitTransaction;
 import org.apache.qpid.server.txn.LocalTransaction;
 import org.apache.qpid.server.txn.ServerTransaction;
+import org.apache.qpid.server.util.ServerScopedRuntimeException;
 
 public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint<Target>
+        implements AsyncAutoCommitTransaction.FutureRecorder
 {
     private static final Logger LOGGER = LoggerFactory.getLogger(StandardReceivingLinkEndpoint.class);
     private static final String LINK = "link";
 
     private ReceivingDestination _receivingDestination;
 
+    private final LinkedList<AsyncCommand> _unfinishedCommandsQueue = new LinkedList<>();
+
     private final PublishingLink _publishingLink = new PublishingLink()
     {
         @Override
@@ -221,7 +230,7 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
                 }
                 else
                 {
-                    transaction = new AutoCommitTransaction(getAddressSpace().getMessageStore());
+                    transaction = new AsyncAutoCommitTransaction(getAddressSpace().getMessageStore(), this);
                 }
 
                 try
@@ -295,7 +304,32 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
 
                     boolean settled = shouldReceiverSettleFirst(transferReceiverSettleMode);
 
-                    updateDisposition(delivery.getDeliveryTag(), resultantState, settled);
+                    if (transaction instanceof AsyncAutoCommitTransaction)
+                    {
+                        recordFuture(Futures.immediateFuture(null), new ServerTransaction.Action()
+                        {
+                            @Override
+                            public void postCommit()
+                            {
+                                updateDisposition(delivery.getDeliveryTag(), resultantState, settled);
+                            }
+
+                            @Override
+                            public void onRollback()
+                            {
+                                //TODO: if reject is not supported, check spec behaviour
+                                Rejected rejected = new Rejected();
+                                rejected.setError(new Error(AmqpError.ILLEGAL_STATE, "Store transaction unexpectedly rolled-back"));
+                                DeliveryState state = sourceSupportedOutcomes.contains(Rejected.REJECTED_SYMBOL) ? rejected : resultantState;
+                                updateDisposition(delivery.getDeliveryTag(), state, settled);
+                            }
+                        });
+                    }
+                    else
+                    {
+                        getSession().receivedComplete();
+                        updateDisposition(delivery.getDeliveryTag(), resultantState, settled);
+                    }
 
                     getSession().getAMQPConnection().registerMessageReceived(serverMessage.getSize());
                     if (transacted)
@@ -522,4 +556,75 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
 
         attachReceived(attach);
     }
+
+    @Override
+    public void recordFuture(final ListenableFuture<Void> future, final ServerTransaction.Action action)
+    {
+        _unfinishedCommandsQueue.add(new AsyncCommand(future, action));
+    }
+
+    @Override
+    public void receiveComplete()
+    {
+        AsyncCommand cmd;
+        while((cmd = _unfinishedCommandsQueue.poll()) != null)
+        {
+            cmd.complete();
+        }
+    }
+
+    private static class AsyncCommand
+    {
+        private final ListenableFuture<Void> _future;
+        private ServerTransaction.Action _action;
+
+        public AsyncCommand(final ListenableFuture<Void> future, final ServerTransaction.Action action)
+        {
+            _future = future;
+            _action = action;
+        }
+
+        void complete()
+        {
+            boolean interrupted = false;
+            try
+            {
+                while (true)
+                {
+                    try
+                    {
+                        _future.get();
+                        break;
+                    }
+                    catch (InterruptedException e)
+                    {
+                        interrupted = true;
+                    }
+
+                }
+            }
+            catch(ExecutionException e)
+            {
+                if(e.getCause() instanceof RuntimeException)
+                {
+                    throw (RuntimeException)e.getCause();
+                }
+                else if(e.getCause() instanceof java.lang.Error)
+                {
+                    throw (java.lang.Error) e.getCause();
+                }
+                else
+                {
+                    throw new ServerScopedRuntimeException(e.getCause());
+                }
+            }
+            if(interrupted)
+            {
+                Thread.currentThread().interrupt();
+            }
+            _action.postCommit();
+            _action = null;
+        }
+    }
+
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cf30e227/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 4535ea4..cf0ddf3 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
@@ -86,6 +86,9 @@ public class TxnCoordinatorReceivingLinkEndpoint extends AbstractReceivingLinkEn
                         Object command = section.getValue();
 
                         Session_1_0 session = getSession();
+
+                        session.getConnection().receivedComplete();
+
                         if (command instanceof Declare)
                         {
                             final IdentifiedTransaction txn = session.getConnection().createIdentifiedTransaction();
@@ -258,4 +261,9 @@ public class TxnCoordinatorReceivingLinkEndpoint extends AbstractReceivingLinkEn
         setDeliveryCount(new SequenceNumber(attach.getInitialDeliveryCount().intValue()));
     }
 
+    @Override
+    public void receiveComplete()
+    {
+
+    }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/cf30e227/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 3d99408..930bf17 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
@@ -31,15 +31,22 @@ import static org.hamcrest.Matchers.is;
 import static org.hamcrest.Matchers.isOneOf;
 import static org.hamcrest.Matchers.lessThan;
 import static org.hamcrest.Matchers.not;
+import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 import static org.junit.Assume.assumeThat;
 
 import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
 import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.stream.Collectors;
+import java.util.stream.LongStream;
 import java.util.stream.Stream;
 
+import com.google.common.collect.Sets;
 import org.hamcrest.CoreMatchers;
 import org.hamcrest.core.Is;
 import org.junit.After;
@@ -57,6 +64,7 @@ import org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.Header;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.Received;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.Rejected;
+import org.apache.qpid.server.protocol.v1_0.type.transaction.Discharge;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 import org.apache.qpid.server.protocol.v1_0.type.transport.Attach;
 import org.apache.qpid.server.protocol.v1_0.type.transport.Begin;
@@ -74,6 +82,7 @@ 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.protocol.v1_0.FrameTransport;
 import org.apache.qpid.tests.protocol.v1_0.Interaction;
+import org.apache.qpid.tests.protocol.v1_0.InteractionTransactionalState;
 import org.apache.qpid.tests.protocol.v1_0.MessageDecoder;
 import org.apache.qpid.tests.protocol.v1_0.MessageEncoder;
 import org.apache.qpid.tests.protocol.SpecificationTest;
@@ -874,6 +883,121 @@ public class TransferTest extends BrokerAdminUsingTestBase
         }
     }
 
+    @Test
+    @SpecificationTest(section = "2.6.12", description = "Transferring A Message.")
+    public void transferMultipleDeliveries() throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = 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);
+            Flow flow = interaction.getLatestResponse(Flow.class);
+            assumeThat("insufficient credit for the test", flow.getLinkCredit().intValue(), is(greaterThan(2)));
+
+            interaction.transferDeliveryId(UnsignedInteger.ZERO)
+                       .transferDeliveryTag(new Binary("A".getBytes(StandardCharsets.UTF_8)))
+                       .transferPayloadData("test")
+                       .transfer()
+                       .transferDeliveryId(UnsignedInteger.ONE)
+                       .transferDeliveryTag(new Binary("B".getBytes(StandardCharsets.UTF_8)))
+                       .transferPayloadData("test")
+                       .transfer()
+                       .transferDeliveryId(UnsignedInteger.valueOf(2))
+                       .transferDeliveryTag(new Binary("C".getBytes(StandardCharsets.UTF_8)))
+                       .transferPayloadData("test")
+                       .transfer();
+
+            TreeSet<UnsignedInteger> expectedDeliveryIds = Sets.newTreeSet(Arrays.asList(UnsignedInteger.ZERO,
+                                                                                         UnsignedInteger.ONE,
+                                                                                         UnsignedInteger.valueOf(2)));
+            assertDeliveries(interaction, expectedDeliveryIds);
+
+            // verify that no unexpected performative is received by closing
+            interaction.doCloseConnection();
+        }
+    }
+
+
+    @Test
+    @SpecificationTest(section = "2.6.12", description = "Transferring A Message.")
+    public void transferMixtureOfTransactionalAndNonTransactionalDeliveries() throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = 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);
+
+            Flow flow = interaction.getLatestResponse(Flow.class);
+            assumeThat("insufficient credit for the test", flow.getLinkCredit().intValue(), is(greaterThan(2)));
+
+            final InteractionTransactionalState txnState = interaction.createTransactionalState(UnsignedInteger.ONE);
+            interaction.txnAttachCoordinatorLink(txnState)
+                       .txnDeclare(txnState);
+
+            interaction.transferDeliveryId(UnsignedInteger.ONE)
+                       .transferDeliveryTag(new Binary("A".getBytes(StandardCharsets.UTF_8)))
+                       .transferPayloadData("test")
+                       .transfer()
+                       .transferDeliveryId(UnsignedInteger.valueOf(2))
+                       .transferDeliveryTag(new Binary("B".getBytes(StandardCharsets.UTF_8)))
+                       .transferPayloadData("test")
+                       .transfer()
+                       .transferDeliveryId(UnsignedInteger.valueOf(3))
+                       .transferDeliveryTag(new Binary("C".getBytes(StandardCharsets.UTF_8)))
+                       .transferTransactionalState(txnState.getCurrentTransactionId())
+                       .transferPayloadData("test")
+                       .transfer();
+
+            final Discharge discharge = new Discharge();
+            discharge.setTxnId(txnState.getCurrentTransactionId());
+            discharge.setFail(false);
+
+            interaction.transferHandle(txnState.getHandle())
+                       .transferDeliveryId(UnsignedInteger.valueOf(4))
+                       .transferDeliveryTag(new Binary(("transaction-" + 4).getBytes(StandardCharsets.UTF_8)))
+                       .transferPayloadData(discharge).transfer();
+
+            assertDeliveries(interaction, Sets.newTreeSet(Arrays.asList(UnsignedInteger.ONE,
+                                                                        UnsignedInteger.valueOf(2),
+                                                                        UnsignedInteger.valueOf(3),
+                                                                        UnsignedInteger.valueOf(4))));
+        }
+    }
+
+    private void assertDeliveries(final Interaction interaction, final TreeSet<UnsignedInteger> expectedDeliveryIds)
+            throws Exception
+    {
+        do
+        {
+            Response<?> response = interaction.consumeResponse(Disposition.class, Flow.class).getLatestResponse();
+            if (response.getBody() instanceof Disposition)
+            {
+                Disposition disposition = (Disposition) response.getBody();
+                LongStream.rangeClosed(disposition.getFirst().longValue(),
+                                       disposition.getLast() == null
+                                               ? disposition.getFirst().longValue()
+                                               : disposition.getLast().longValue())
+                          .forEach(value -> {
+                              UnsignedInteger deliveryId = expectedDeliveryIds.first();
+                              assertThat(value, is(equalTo(deliveryId.longValue())));
+                              expectedDeliveryIds.remove(deliveryId);
+                          });
+            }
+        }
+        while (!expectedDeliveryIds.isEmpty());
+    }
+
     private byte[] createTestPaload(final long payloadSize)
     {
         if (payloadSize > 1024*1024*1024)


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


[04/11] qpid-broker-j git commit: QPID-8062: [Broker-J][AMQP 1.0] Fix handling of routing errors when target destination cannot route received message

Posted by or...@apache.org.
QPID-8062: [Broker-J][AMQP 1.0] Fix handling of routing errors when target destination cannot route received message

* close the link on receipt of unroutable message when
    the source of the link does not support the rejected outcome or
    non-transactional message has already been settled by the sender
* mark the publishing transaction as "rollback only" on receipt of
    unroutable pre-settled message

(cherry picked from commit 06b4213286305f6d05ce496ca278b73b566f24be)


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/b4e746a4
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/b4e746a4
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/b4e746a4

Branch: refs/heads/7.0.x
Commit: b4e746a4b76d7baac75c4bc04fdd93198f9fad20
Parents: ae36d90
Author: Alex Rudyy <or...@apache.org>
Authored: Wed Jan 17 16:50:43 2018 +0000
Committer: Alex Rudyy <or...@apache.org>
Committed: Mon Jan 29 13:57:14 2018 +0000

----------------------------------------------------------------------
 .../v1_0/AnonymousRelayDestination.java         |  52 ++-
 .../protocol/v1_0/NodeReceivingDestination.java |  44 +-
 .../protocol/v1_0/ReceivingDestination.java     |  11 +-
 .../v1_0/StandardReceivingLinkEndpoint.java     |  70 ++-
 .../tests/protocol/v1_0/MessageEncoder.java     |  12 +
 .../anonymousrelay/AnonymousRelayTest.java      | 440 +++++++++++++++++++
 .../protocol/v1_0/messaging/TransferTest.java   |   8 +-
 7 files changed, 571 insertions(+), 66 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b4e746a4/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AnonymousRelayDestination.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AnonymousRelayDestination.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AnonymousRelayDestination.java
index de7991c..806469b 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AnonymousRelayDestination.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AnonymousRelayDestination.java
@@ -22,6 +22,7 @@ package org.apache.qpid.server.protocol.v1_0;/*
 import static org.apache.qpid.server.protocol.v1_0.Session_1_0.DELAYED_DELIVERY;
 
 import java.util.Arrays;
+import java.util.Collections;
 
 import org.apache.qpid.server.logging.EventLogger;
 import org.apache.qpid.server.logging.messages.ExchangeMessages;
@@ -29,6 +30,8 @@ import org.apache.qpid.server.message.MessageDestination;
 import org.apache.qpid.server.message.ServerMessage;
 import org.apache.qpid.server.model.DestinationAddress;
 import org.apache.qpid.server.model.NamedAddressSpace;
+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.Outcome;
 import org.apache.qpid.server.protocol.v1_0.type.Symbol;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted;
@@ -37,6 +40,7 @@ import org.apache.qpid.server.protocol.v1_0.type.messaging.Target;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 import org.apache.qpid.server.protocol.v1_0.type.transport.Error;
 import org.apache.qpid.server.security.SecurityToken;
+import org.apache.qpid.server.txn.LocalTransaction;
 import org.apache.qpid.server.txn.ServerTransaction;
 
 public class AnonymousRelayDestination implements ReceivingDestination
@@ -70,7 +74,12 @@ public class AnonymousRelayDestination implements ReceivingDestination
     }
 
     @Override
-    public Outcome send(final ServerMessage<?> message, final ServerTransaction txn, final SecurityToken securityToken)
+    public Outcome send(final ServerMessage<?> message,
+                        final ServerTransaction txn,
+                        final SecurityToken securityToken,
+                        final boolean rejectedOutcomeSupportedBySource,
+                        final boolean deliverySettled,
+                        final Binary deliveryTag) throws AmqpErrorException
     {
         final ReceivingDestination destination;
         final String routingAddress = message.getTo();
@@ -99,12 +108,41 @@ public class AnonymousRelayDestination implements ReceivingDestination
             }
             else
             {
-                outcome = createdRejectedOutcome(AmqpError.NOT_FOUND, "Unknown destination '" + routingAddress + "'");
+                final Error notFoundError = new Error(AmqpError.NOT_FOUND,
+                                                      String.format("Unknown destination '%s'", routingAddress));
+                notFoundError.setInfo(Collections.singletonMap(DELIVERY_TAG, deliveryTag));
+
+                // If the source of the link does not support the rejected outcome,
+                // or the message has already been settled by the sender,
+                // then the routing node MUST detach the link with an error.
+                // AMQP-140: When pre-settled messages are being sent within a transaction,
+                // then the behaviour defined for transactions should take precedence
+                // (essentially marking the transaction as rollback only).
+                if (!rejectedOutcomeSupportedBySource || (deliverySettled && !(txn instanceof LocalTransaction)))
+                {
+                    throw new AmqpErrorException(notFoundError);
+                }
+                else
+                {
+                    if (deliverySettled && txn instanceof LocalTransaction)
+                    {
+                        ((LocalTransaction) txn).setRollbackOnly();
+                    }
+
+                    Rejected rejected = new Rejected();
+                    rejected.setError(notFoundError);
+                    outcome = rejected;
+                }
             }
         }
         else
         {
-            outcome = destination.send(message, txn, securityToken);
+            outcome = destination.send(message,
+                                       txn,
+                                       securityToken,
+                                       rejectedOutcomeSupportedBySource,
+                                       deliverySettled,
+                                       deliveryTag);
         }
         return outcome;
     }
@@ -127,12 +165,4 @@ public class AnonymousRelayDestination implements ReceivingDestination
     {
         return null;
     }
-
-    private Outcome createdRejectedOutcome(AmqpError errorCode, String errorMessage)
-    {
-        Rejected rejected = new Rejected();
-        final Error notFoundError = new Error(errorCode, errorMessage);
-        rejected.setError(notFoundError);
-        return rejected;
-    }
 }

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b4e746a4/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/NodeReceivingDestination.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/NodeReceivingDestination.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/NodeReceivingDestination.java
index 57ad962..6d5859f 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/NodeReceivingDestination.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/NodeReceivingDestination.java
@@ -34,6 +34,8 @@ import org.apache.qpid.server.message.RoutingResult;
 import org.apache.qpid.server.message.ServerMessage;
 import org.apache.qpid.server.model.DestinationAddress;
 import org.apache.qpid.server.model.Exchange;
+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.Outcome;
 import org.apache.qpid.server.protocol.v1_0.type.Symbol;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted;
@@ -43,12 +45,13 @@ import org.apache.qpid.server.protocol.v1_0.type.messaging.TerminusExpiryPolicy;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
 import org.apache.qpid.server.protocol.v1_0.type.transport.Error;
 import org.apache.qpid.server.security.SecurityToken;
+import org.apache.qpid.server.txn.LocalTransaction;
 import org.apache.qpid.server.txn.ServerTransaction;
 
 public class NodeReceivingDestination implements ReceivingDestination
 {
     private static final Accepted ACCEPTED = new Accepted();
-    public static final Rejected REJECTED = new Rejected();
+    private static final Rejected REJECTED = new Rejected();
     private static final Outcome[] OUTCOMES = { ACCEPTED, REJECTED};
     private final boolean _discardUnroutable;
     private final EventLogger _eventLogger;
@@ -93,7 +96,12 @@ public class NodeReceivingDestination implements ReceivingDestination
     }
 
     @Override
-    public Outcome send(final ServerMessage<?> message, final ServerTransaction txn, final SecurityToken securityToken)
+    public Outcome send(final ServerMessage<?> message,
+                        final ServerTransaction txn,
+                        final SecurityToken securityToken,
+                        final boolean rejectedOutcomeSupportedBySource,
+                        final boolean deliverySettled,
+                        final Binary deliveryTag) throws AmqpErrorException
     {
         final String routingAddress = "".equals(_routingAddress) ? getRoutingAddress(message) : _routingAddress;
         _destination.authorisePublish(securityToken, Collections.singletonMap("routingKey", routingAddress));
@@ -128,27 +136,45 @@ public class NodeReceivingDestination implements ReceivingDestination
         {
             if (!_discardUnroutable)
             {
+                final Error error;
                 if (result.isRejected())
                 {
-                    AmqpError error;
+                    AmqpError errorCode;
                     if (result.containsReject(RejectType.LIMIT_EXCEEDED))
                     {
-                        error = AmqpError.RESOURCE_LIMIT_EXCEEDED;
+                        errorCode = AmqpError.RESOURCE_LIMIT_EXCEEDED;
                     }
                     else if (result.containsReject(RejectType.PRECONDITION_FAILED))
                     {
-                        error = AmqpError.PRECONDITION_FAILED;
+                        errorCode = AmqpError.PRECONDITION_FAILED;
                     }
                     else
                     {
-                        error = AmqpError.ILLEGAL_STATE;
+                        errorCode = AmqpError.ILLEGAL_STATE;
                     }
-                    return createdRejectedOutcome(error, result.getRejectReason());
+                    error = new Error(errorCode, result.getRejectReason());
                 }
                 else
                 {
-                    return createdRejectedOutcome(AmqpError.NOT_FOUND,
-                                                  String.format("Unknown destination '%s'", routingAddress));
+                    error = new Error(AmqpError.NOT_FOUND,
+                                      String.format("Unknown destination '%s'", routingAddress));
+                }
+                error.setInfo(Collections.singletonMap(DELIVERY_TAG, deliveryTag));
+
+                if (!rejectedOutcomeSupportedBySource || (deliverySettled && !(txn instanceof LocalTransaction)))
+                {
+                    throw new AmqpErrorException(error);
+                }
+                else
+                {
+                    if (deliverySettled && txn instanceof LocalTransaction)
+                    {
+                        ((LocalTransaction) txn).setRollbackOnly();
+                    }
+
+                    Rejected rejected = new Rejected();
+                    rejected.setError(error);
+                    return rejected;
                 }
             }
             else

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b4e746a4/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingDestination.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingDestination.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingDestination.java
index a6a910f..5abd825 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingDestination.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingDestination.java
@@ -22,6 +22,8 @@ package org.apache.qpid.server.protocol.v1_0;
 
 import org.apache.qpid.server.message.MessageDestination;
 import org.apache.qpid.server.message.ServerMessage;
+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.Outcome;
 import org.apache.qpid.server.protocol.v1_0.type.Symbol;
 import org.apache.qpid.server.security.SecurityToken;
@@ -29,7 +31,7 @@ import org.apache.qpid.server.txn.ServerTransaction;
 
 public interface ReceivingDestination
 {
-
+    Symbol DELIVERY_TAG = Symbol.valueOf("delivery-tag");
     Symbol REJECT_UNROUTABLE = Symbol.valueOf("REJECT_UNROUTABLE");
     Symbol DISCARD_UNROUTABLE = Symbol.valueOf("DISCARD_UNROUTABLE");
 
@@ -37,7 +39,12 @@ public interface ReceivingDestination
 
     Outcome[] getOutcomes();
 
-    Outcome send(final ServerMessage<?> message, final ServerTransaction txn, final SecurityToken securityToken);
+    Outcome send(final ServerMessage<?> message,
+                 final ServerTransaction txn,
+                 final SecurityToken securityToken,
+                 final boolean rejectedOutcomeSupportedBySource,
+                 final boolean deliverySettled,
+                 final Binary deliveryTag) throws AmqpErrorException;
 
     int getCredit();
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b4e746a4/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 bc9dd57..a565f7f 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
@@ -54,7 +54,6 @@ import org.apache.qpid.server.protocol.v1_0.type.DeliveryState;
 import org.apache.qpid.server.protocol.v1_0.type.Outcome;
 import org.apache.qpid.server.protocol.v1_0.type.Symbol;
 import org.apache.qpid.server.protocol.v1_0.type.UnsignedInteger;
-import org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.Rejected;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.Source;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.Target;
@@ -80,7 +79,8 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
     private static final Logger LOGGER = LoggerFactory.getLogger(StandardReceivingLinkEndpoint.class);
     private static final String LINK = "link";
 
-    private ReceivingDestination _receivingDestination;
+    private volatile ReceivingDestination _receivingDestination;
+    private volatile boolean _rejectedOutcomeSupportedBySource;
 
     private final LinkedList<AsyncCommand> _unfinishedCommandsQueue = new LinkedList<>();
 
@@ -247,13 +247,11 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
                            .checkAuthorizedMessagePrincipal(serverMessage.getMessageHeader().getUserId());
 
                     Outcome outcome;
-                    Source source = getSource();
                     if (serverMessage.isPersistent() && !getAddressSpace().getMessageStore().isPersistent())
                     {
                         final Error preconditionFailedError = new Error(AmqpError.PRECONDITION_FAILED,
                                                                         "Non-durable message store cannot accept durable message.");
-                        if (source.getOutcomes() != null && Arrays.asList(source.getOutcomes())
-                                                                  .contains(Rejected.REJECTED_SYMBOL))
+                        if (_rejectedOutcomeSupportedBySource)
                         {
                             final Rejected rejected = new Rejected();
                             rejected.setError(preconditionFailedError);
@@ -267,52 +265,44 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
                     }
                     else
                     {
-                        outcome = getReceivingDestination().send(serverMessage, transaction,
-                                                                 session.getSecurityToken());
-                    }
-
-                    DeliveryState resultantState;
-
-                    final List<Symbol> sourceSupportedOutcomes = new ArrayList<>();
-                    if (source.getOutcomes() != null)
-                    {
-                        sourceSupportedOutcomes.addAll(Arrays.asList(source.getOutcomes()));
-                    }
-                    else if (source.getDefaultOutcome() == null)
-                    {
-                        sourceSupportedOutcomes.add(Accepted.ACCEPTED_SYMBOL);
-                    }
-
-                    boolean transacted = transactionId != null && transaction instanceof LocalTransaction;
-                    if (sourceSupportedOutcomes.contains(outcome.getSymbol()))
-                    {
-                        if (transactionId == null)
+                        try
                         {
-                            resultantState = outcome;
+                            outcome = getReceivingDestination().send(serverMessage,
+                                                                     transaction,
+                                                                     session.getSecurityToken(),
+                                                                     _rejectedOutcomeSupportedBySource,
+                                                                     delivery.isSettled(),
+                                                                     delivery.getDeliveryTag());
                         }
-                        else
+                        catch (AmqpErrorException e)
                         {
-                            TransactionalState transactionalState = new TransactionalState();
-                            transactionalState.setOutcome(outcome);
-                            transactionalState.setTxnId(transactionId);
-                            resultantState = transactionalState;
+                            return e.getError();
                         }
                     }
+
+                    Outcome sourceDefaultOutcome = getSource().getDefaultOutcome();
+                    boolean defaultOutcome = sourceDefaultOutcome != null &&
+                                             sourceDefaultOutcome.getSymbol().equals(outcome.getSymbol());
+                    DeliveryState resultantState;
+                    if (transactionId == null)
+                    {
+                        resultantState = defaultOutcome ? null : outcome;
+                    }
                     else
                     {
-                        if(transacted && source.getDefaultOutcome() != null
-                           && outcome.getSymbol() != source.getDefaultOutcome().getSymbol())
-                        {
-                            ((LocalTransaction) transaction).setRollbackOnly();
-                        }
-                        resultantState = null;
+                        TransactionalState transactionalState = new TransactionalState();
+                        transactionalState.setOutcome(defaultOutcome ? null : outcome);
+                        transactionalState.setTxnId(transactionId);
+                        resultantState = transactionalState;
                     }
 
                     boolean settled = shouldReceiverSettleFirst(transferReceiverSettleMode);
 
                     if (transaction instanceof AsyncAutoCommitTransaction)
                     {
-                        _pendingDispositions.add(new PendingDispositionHolder(delivery.getDeliveryTag(), resultantState, settled));
+                        _pendingDispositions.add(new PendingDispositionHolder(delivery.getDeliveryTag(),
+                                                                              resultantState,
+                                                                              settled));
                     }
                     else
                     {
@@ -321,7 +311,7 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
                     }
 
                     getSession().getAMQPConnection().registerMessageReceived(serverMessage.getSize());
-                    if (transacted)
+                    if (transactionId != null)
                     {
                         getSession().getAMQPConnection().registerTransactedMessageReceived();
                     }
@@ -456,6 +446,8 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
             }
         }
         getLink().setTermini(source, target);
+        _rejectedOutcomeSupportedBySource =
+                source.getOutcomes() != null && Arrays.asList(source.getOutcomes()).contains(Rejected.REJECTED_SYMBOL);
     }
 
     public ReceivingDestination getReceivingDestination()

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b4e746a4/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 37e327e..0849376 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
@@ -28,9 +28,11 @@ import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.AmqpValue;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.EncodingRetainingSection;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.Header;
+import org.apache.qpid.server.protocol.v1_0.type.messaging.Properties;
 
 public class MessageEncoder
 {
+    private Properties _properties;
     private Header _header;
     private List<String> _data = new LinkedList<>();
 
@@ -44,6 +46,11 @@ public class MessageEncoder
         _header = header;
     }
 
+    public void setProperties(final Properties properties)
+    {
+        _properties = properties;
+    }
+
     public QpidByteBuffer getPayload()
     {
         List<QpidByteBuffer> payload = new ArrayList<>();
@@ -52,6 +59,11 @@ public class MessageEncoder
             payload.add(_header.createEncodingRetainingSection().getEncodedForm());
         }
 
+        if (_properties != null)
+        {
+            payload.add(_properties.createEncodingRetainingSection().getEncodedForm());
+        }
+
         if (_data.isEmpty())
         {
             throw new IllegalStateException("Message should have at least one data section");

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b4e746a4/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousrelay/AnonymousRelayTest.java
----------------------------------------------------------------------
diff --git a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousrelay/AnonymousRelayTest.java b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousrelay/AnonymousRelayTest.java
new file mode 100644
index 0000000..c3c69d1
--- /dev/null
+++ b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousrelay/AnonymousRelayTest.java
@@ -0,0 +1,440 @@
+/*
+ *
+ * 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.tests.protocol.v1_0.extensions.anonymousrelay;
+
+
+import static org.hamcrest.CoreMatchers.hasItem;
+import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assume.assumeThat;
+
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+
+import org.junit.Before;
+import org.junit.Test;
+
+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.DeliveryState;
+import org.apache.qpid.server.protocol.v1_0.type.Symbol;
+import org.apache.qpid.server.protocol.v1_0.type.UnsignedInteger;
+import org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted;
+import org.apache.qpid.server.protocol.v1_0.type.messaging.Properties;
+import org.apache.qpid.server.protocol.v1_0.type.messaging.Rejected;
+import org.apache.qpid.server.protocol.v1_0.type.messaging.Target;
+import org.apache.qpid.server.protocol.v1_0.type.transaction.Coordinator;
+import org.apache.qpid.server.protocol.v1_0.type.transaction.Discharge;
+import org.apache.qpid.server.protocol.v1_0.type.transaction.TransactionError;
+import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
+import org.apache.qpid.server.protocol.v1_0.type.transport.Attach;
+import org.apache.qpid.server.protocol.v1_0.type.transport.Begin;
+import org.apache.qpid.server.protocol.v1_0.type.transport.Detach;
+import org.apache.qpid.server.protocol.v1_0.type.transport.Disposition;
+import org.apache.qpid.server.protocol.v1_0.type.transport.Error;
+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.Role;
+import org.apache.qpid.tests.protocol.Response;
+import org.apache.qpid.tests.protocol.SpecificationTest;
+import org.apache.qpid.tests.protocol.v1_0.FrameTransport;
+import org.apache.qpid.tests.protocol.v1_0.Interaction;
+import org.apache.qpid.tests.protocol.v1_0.InteractionTransactionalState;
+import org.apache.qpid.tests.protocol.v1_0.MessageEncoder;
+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 AnonymousRelayTest extends BrokerAdminUsingTestBase
+{
+    private static final Symbol ANONYMOUS_RELAY = Symbol.valueOf("ANONYMOUS-RELAY");
+    private static final String TEST_MESSAGE_CONTENT = "test";
+    private InetSocketAddress _brokerAddress;
+
+    @Before
+    public void setUp()
+    {
+        final BrokerAdmin brokerAdmin = getBrokerAdmin();
+        brokerAdmin.createQueue(BrokerAdmin.TEST_QUEUE_NAME);
+        _brokerAddress = brokerAdmin.getBrokerAddress(BrokerAdmin.PortType.ANONYMOUS_AMQP);
+    }
+
+    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2. Sending A Message",
+            description = "Messages sent over links into a routing node will be"
+                          + " forwarded to the node referenced in the to field of properties of the message"
+                          + " just as if a direct link has been established to that node.")
+    @Test
+    public void transferPreSettledToExistingDestination() throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
+
+            interaction.begin()
+                       .consumeResponse(Begin.class)
+
+                       .attachRole(Role.SENDER)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+
+                       .transferPayload(generateMessagePayloadToDestination(BrokerAdmin.TEST_QUEUE_NAME))
+                       .transferSettled(Boolean.TRUE)
+                       .transfer()
+                       .sync();
+
+            Object receivedMessage = Utils.receiveMessage(_brokerAddress, BrokerAdmin.TEST_QUEUE_NAME);
+            assertThat(receivedMessage, is(equalTo(TEST_MESSAGE_CONTENT)));
+        }
+    }
+
+    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2.2 Routing Errors",
+            description = "It is possible that a message sent to a routing node has an address in the to field"
+                          + " of properties which, if used in the address field of target of an attach,"
+                          + " would result in an unsuccessful link establishment (for example,"
+                          + " if the address cannot be resolved to a node). In this case the routing node"
+                          + " MUST communicate the error back to the sender of the message."
+                          + " [...] the message has already been settled by the sender,"
+                          + " then the routing node MUST detach the link with an error.")
+    @Test
+    public void transferPreSettledToUnknownDestination() throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
+
+            interaction.begin()
+                       .consumeResponse(Begin.class)
+
+                       .attachRole(Role.SENDER)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+
+                       .transferPayload(generateMessagePayloadToDestination("Unknown"))
+                       .transferSettled(Boolean.TRUE)
+                       .transfer();
+
+            Detach detach = interaction.consumeResponse().getLatestResponse(Detach.class);
+            Error error = detach.getError();
+            assertThat(error, is(notNullValue()));
+            assertThat(error.getCondition(), is(equalTo(AmqpError.NOT_FOUND)));
+        }
+    }
+
+    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2.2 Routing Errors",
+            description = "It is possible that a message sent to a routing node has an address in the to field"
+                          + " of properties which, if used in the address field of target of an attach,"
+                          + " would result in an unsuccessful link establishment (for example,"
+                          + " if the address cannot be resolved to a node). In this case the routing node"
+                          + " MUST communicate the error back to the sender of the message."
+                          + " If the source of the link supports the rejected outcome,"
+                          + " and the message has not already been settled by the sender, then the routing node"
+                          + " MUST reject the message.")
+    @Test
+    public void transferUnsettledToUnknownDestinationWhenRejectedOutcomeSupportedBySource() throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
+
+            interaction.begin()
+                       .consumeResponse(Begin.class)
+
+                       .attachRole(Role.SENDER)
+                       .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL, Rejected.REJECTED_SYMBOL)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+
+                       .transferPayload(generateMessagePayloadToDestination("Unknown"))
+                       .transfer()
+                       .consumeResponse();
+
+            Disposition disposition = interaction.getLatestResponse(Disposition.class);
+
+            assertThat(disposition.getSettled(), is(true));
+
+            DeliveryState dispositionState = disposition.getState();
+            assertThat(dispositionState, is(instanceOf(Rejected.class)));
+
+            Rejected rejected = (Rejected)dispositionState;
+            Error error = rejected.getError();
+            assertThat(error, is(notNullValue()));
+            assertThat(error.getCondition(), is(equalTo(AmqpError.NOT_FOUND)));
+        }
+    }
+
+    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2.2 Routing Errors",
+            description = "It is possible that a message sent to a routing node has an address in the to field"
+                          + " of properties which, if used in the address field of target of an attach,"
+                          + " would result in an unsuccessful link establishment (for example,"
+                          + " if the address cannot be resolved to a node). In this case the routing node"
+                          + " MUST communicate the error back to the sender of the message."
+                          + " [...]"
+                          + " If the source of the link does not support the rejected outcome,"
+                          + " [...] then the routing node MUST detach the link with an error.")
+    @Test
+    public void transferUnsettledToUnknownDestinationWhenRejectedOutcomeNotSupportedBySource() throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
+
+            interaction.begin()
+                       .consumeResponse(Begin.class)
+
+                       .attachRole(Role.SENDER)
+                       .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+
+                       .transferPayload(generateMessagePayloadToDestination("Unknown"))
+                       .transfer();
+
+            Detach detach = interaction.consumeResponse().getLatestResponse(Detach.class);
+            Error error = detach.getError();
+            assertThat(error, is(notNullValue()));
+            assertThat(error.getCondition(), is(equalTo(AmqpError.NOT_FOUND)));
+        }
+    }
+
+    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2. Sending A Message",
+            description = "Messages sent over links into a routing node will be"
+                          + " forwarded to the node referenced in the to field of properties of the message"
+                          + " just as if a direct link has been established to that node.")
+    @Test
+    public void transferPreSettledInTransactionToExistingDestination() throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
+            final UnsignedInteger linkHandle = UnsignedInteger.ONE;
+            final InteractionTransactionalState txnState = interaction.createTransactionalState(UnsignedInteger.ZERO);
+            interaction.begin()
+                       .consumeResponse(Begin.class)
+
+                       .txnAttachCoordinatorLink(txnState)
+                       .txnDeclare(txnState)
+
+                       .attachRole(Role.SENDER)
+                       .attachHandle(linkHandle)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+
+                       .transferHandle(linkHandle)
+                       .transferPayload(generateMessagePayloadToDestination(BrokerAdmin.TEST_QUEUE_NAME))
+                       .transferTransactionalState(txnState.getCurrentTransactionId())
+                       .transferSettled(Boolean.TRUE)
+                       .transfer()
+
+                       .txnDischarge(txnState, false);
+
+            Object receivedMessage = Utils.receiveMessage(_brokerAddress, BrokerAdmin.TEST_QUEUE_NAME);
+            assertThat(receivedMessage, is(equalTo(TEST_MESSAGE_CONTENT)));
+        }
+    }
+
+    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2.2 Routing Errors",
+            description = "It is possible that a message sent to a routing node has an address in the to field"
+                          + " of properties which, if used in the address field of target of an attach,"
+                          + " would result in an unsuccessful link establishment (for example,"
+                          + " if the address cannot be resolved to a node). In this case the routing node"
+                          + " MUST communicate the error back to the sender of the message."
+                          + " [...]"
+                          + " <Not in spec yet>"
+                          + " AMQP-140"
+                          + " In this case the behaviour defined for transactions (of essentially marking"
+                          + " the transaction as rollback only) should take precedence. "
+                          + ""
+                          + " AMQP spec 4.3 Discharging a Transaction"
+                          + " If the coordinator is unable to complete the discharge, the coordinator MUST convey"
+                          + " the error to the controller as a transaction-error. If the source for the link to"
+                          + " the coordinator supports the rejected outcome, then the message MUST be rejected"
+                          + " with this outcome carrying the transaction-error.")
+    @Test
+    public void transferPreSettledInTransactionToUnknownDestinationWhenRejectOutcomeSupportedByTxController()
+            throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final UnsignedInteger linkHandle = UnsignedInteger.ONE;
+            final Interaction interaction =
+                    openInteractionWithAnonymousRelayCapability(transport);
+
+            final InteractionTransactionalState txnState = interaction.createTransactionalState(UnsignedInteger.ZERO);
+            interaction.begin()
+                       .consumeResponse(Begin.class)
+
+                       // attaching coordinator link with supported outcomes Accept and Reject
+                       .txnAttachCoordinatorLink(txnState)
+                       .txnDeclare(txnState)
+
+                       .attachRole(Role.SENDER)
+                       .attachHandle(linkHandle)
+                       .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL, Rejected.REJECTED_SYMBOL)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+
+                       .transferHandle(linkHandle)
+                       .transferPayload(generateMessagePayloadToDestination("Unknown"))
+                       .transferTransactionalState(txnState.getCurrentTransactionId())
+                       .transferSettled(Boolean.TRUE)
+                       .transferDeliveryId(UnsignedInteger.valueOf(1))
+                       .transfer();
+
+            final Discharge discharge = new Discharge();
+            discharge.setTxnId(txnState.getCurrentTransactionId());
+            discharge.setFail(false);
+            interaction.transferHandle(txnState.getHandle())
+                       .transferDeliveryId(UnsignedInteger.valueOf(2))
+                       .transferSettled(Boolean.FALSE)
+                       .transferDeliveryTag(new Binary(("transaction-" + 2).getBytes(StandardCharsets.UTF_8)))
+                       .transferPayloadData(discharge).transfer();
+
+            Disposition dischargeTransactionDisposition = null;
+            Flow coordinatorFlow = null;
+            do
+            {
+                interaction.consumeResponse(Disposition.class, Flow.class);
+                Response<?> response = interaction.getLatestResponse();
+                if (response.getBody() instanceof Disposition)
+                {
+                    dischargeTransactionDisposition = (Disposition) response.getBody();
+                }
+                if (response.getBody() instanceof Flow)
+                {
+                    final Flow flowResponse = (Flow) response.getBody();
+                    if (flowResponse.getHandle().equals(txnState.getHandle()))
+                    {
+                        coordinatorFlow = flowResponse;
+                    }
+                }
+            } while (dischargeTransactionDisposition == null || coordinatorFlow == null);
+
+            assertThat(dischargeTransactionDisposition.getSettled(), is(equalTo(true)));
+            assertThat(dischargeTransactionDisposition.getState(), is(instanceOf(Rejected.class)));
+
+            Rejected rejected = (Rejected) dischargeTransactionDisposition.getState();
+            Error error = rejected.getError();
+
+            assertThat(error, is(notNullValue()));
+            assertThat(error.getCondition(), is(equalTo(TransactionError.TRANSACTION_ROLLBACK)));
+        }
+    }
+
+    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2.2 Routing Errors",
+            description = "It is possible that a message sent to a routing node has an address in the to field"
+                          + " of properties which, if used in the address field of target of an attach,"
+                          + " would result in an unsuccessful link establishment (for example,"
+                          + " if the address cannot be resolved to a node). In this case the routing node"
+                          + " MUST communicate the error back to the sender of the message."
+                          + " [...]"
+                          + " <Not in spec yet>"
+                          + " AMQP-140"
+                          + ""
+                          + " AMQP spec 4.3 Discharging a Transaction"
+                          + " If the coordinator is unable to complete the discharge, the coordinator MUST convey"
+                          + " the error to the controller as a transaction-error."
+                          + " [...]"
+                          + " If the source does not support the rejected outcome, the transactional resource MUST"
+                          + " detach the link to the coordinator, with the detach performative carrying"
+                          + " the transaction-error")
+    @Test
+    public void transferPreSettledInTransactionToUnknownDestinationWhenRejectOutcomeNotSupportedByTxController()
+            throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final UnsignedInteger linkHandle = UnsignedInteger.ONE;
+            final Interaction interaction =
+                    openInteractionWithAnonymousRelayCapability(transport);
+
+            final InteractionTransactionalState txnState = interaction.createTransactionalState(UnsignedInteger.ZERO);
+
+            interaction.begin()
+                       .consumeResponse(Begin.class)
+
+                       .attachRole(Role.SENDER)
+                       .attachName("testTransactionCoordinator-" + txnState.getHandle())
+                       .attachHandle(txnState.getHandle())
+                       .attachInitialDeliveryCount(UnsignedInteger.ZERO)
+                       .attachTarget(new Coordinator())
+                       .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+                       .txnDeclare(txnState)
+
+                       .attachRole(Role.SENDER)
+                       .attachHandle(linkHandle)
+                       .attachTarget(new Target())
+                       .attachName("link-" + linkHandle)
+                       .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL, Rejected.REJECTED_SYMBOL)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+
+                       .transferHandle(linkHandle)
+                       .transferPayload(generateMessagePayloadToDestination("Unknown"))
+                       .transferTransactionalState(txnState.getCurrentTransactionId())
+                       .transferSettled(Boolean.TRUE)
+                       .transfer();
+
+            final Discharge discharge = new Discharge();
+            discharge.setTxnId(txnState.getCurrentTransactionId());
+            discharge.setFail(false);
+
+            interaction.transferHandle(txnState.getHandle())
+                       .transferSettled(Boolean.FALSE)
+                       .transferDeliveryId(UnsignedInteger.valueOf(4))
+                       .transferDeliveryTag(new Binary(("transaction-" + 4).getBytes(StandardCharsets.UTF_8)))
+                       .transferPayloadData(discharge).transfer();
+
+            Detach transactionCoordinatorDetach = interaction.consumeResponse().getLatestResponse(Detach.class);
+            Error transactionCoordinatorDetachError = transactionCoordinatorDetach.getError();
+            assertThat(transactionCoordinatorDetachError, is(notNullValue()));
+            assertThat(transactionCoordinatorDetachError.getCondition(), is(equalTo(TransactionError.TRANSACTION_ROLLBACK)));
+        }
+    }
+
+
+    private Interaction openInteractionWithAnonymousRelayCapability(final FrameTransport transport) throws Exception
+    {
+        final Interaction interaction = transport.newInteraction();
+        interaction.negotiateProtocol().consumeResponse()
+                   .openDesiredCapabilities(ANONYMOUS_RELAY)
+                   .open().consumeResponse(Open.class);
+
+        Open open = interaction.getLatestResponse(Open.class);
+        assumeThat(Arrays.asList(open.getOfferedCapabilities()), hasItem(ANONYMOUS_RELAY));
+        return interaction;
+    }
+
+    private QpidByteBuffer generateMessagePayloadToDestination(final String destinationName)
+    {
+        MessageEncoder messageEncoder = new MessageEncoder();
+        final Properties properties = new Properties();
+        properties.setTo(destinationName);
+        messageEncoder.setProperties(properties);
+        messageEncoder.addData(TEST_MESSAGE_CONTENT);
+        return messageEncoder.getPayload();
+    }
+}

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/b4e746a4/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 930bf17..2574910 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
@@ -31,7 +31,6 @@ import static org.hamcrest.Matchers.is;
 import static org.hamcrest.Matchers.isOneOf;
 import static org.hamcrest.Matchers.lessThan;
 import static org.hamcrest.Matchers.not;
-import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 import static org.junit.Assume.assumeThat;
 
@@ -39,7 +38,6 @@ import java.net.InetSocketAddress;
 import java.nio.charset.StandardCharsets;
 import java.util.Arrays;
 import java.util.List;
-import java.util.Set;
 import java.util.TreeSet;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.stream.Collectors;
@@ -80,13 +78,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.protocol.Response;
+import org.apache.qpid.tests.protocol.SpecificationTest;
 import org.apache.qpid.tests.protocol.v1_0.FrameTransport;
 import org.apache.qpid.tests.protocol.v1_0.Interaction;
 import org.apache.qpid.tests.protocol.v1_0.InteractionTransactionalState;
 import org.apache.qpid.tests.protocol.v1_0.MessageDecoder;
 import org.apache.qpid.tests.protocol.v1_0.MessageEncoder;
-import org.apache.qpid.tests.protocol.SpecificationTest;
-import org.apache.qpid.tests.protocol.Response;
 import org.apache.qpid.tests.utils.BrokerAdmin;
 import org.apache.qpid.tests.utils.BrokerAdminUsingTestBase;
 
@@ -259,6 +257,7 @@ public class TransferTest extends BrokerAdminUsingTestBase
                        .open()
                        .begin()
                        .attachRole(Role.SENDER)
+                       .attachTargetAddress(BrokerAdmin.TEST_QUEUE_NAME)
                        .attach()
                        .transferPayloadData("testData")
                        .transferSettled(true)
@@ -273,7 +272,6 @@ public class TransferTest extends BrokerAdminUsingTestBase
             interaction.consumeResponse().getLatestResponse(Begin.class);
             interaction.consumeResponse().getLatestResponse(Attach.class);
             interaction.consumeResponse().getLatestResponse(Flow.class);
-            //interaction.consumeResponse(null, Disposition.class, Detach.class, End.class);
             interaction.consumeResponse().getLatestResponse(Close.class);
         }
     }


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


[03/11] qpid-broker-j git commit: QPID-8032: [Broker-J][AMQP 1.0] Fix defect in coalescing loop

Posted by or...@apache.org.
QPID-8032: [Broker-J][AMQP 1.0] Fix defect in coalescing loop

(cherry picked from commit 562714536e68e06c01827a3e9217eb31ce0964ae)


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/ae36d901
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/ae36d901
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/ae36d901

Branch: refs/heads/7.0.x
Commit: ae36d9018e5062e351a1fa5fe47b8d7436d8641c
Parents: 16beefd
Author: Alex Rudyy <or...@apache.org>
Authored: Thu Jan 18 11:06:28 2018 +0000
Committer: Alex Rudyy <or...@apache.org>
Committed: Mon Jan 29 13:55:51 2018 +0000

----------------------------------------------------------------------
 .../server/protocol/v1_0/StandardReceivingLinkEndpoint.java | 9 +++------
 1 file changed, 3 insertions(+), 6 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/ae36d901/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 fe5c4db..bc9dd57 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
@@ -581,17 +581,14 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
                 {
                     disposition = itr.next();
 
-                    if (current.isSettled() == disposition.isSettled() &&
-                        Objects.equals(current.getResultantState(), disposition.getResultantState()))
-                    {
-                        deliveryTags.add(disposition.getDeliveryTag());
-                    }
-                    else
+                    if (current.isSettled() != disposition.isSettled() ||
+                        !Objects.equals(current.getResultantState(), disposition.getResultantState()))
                     {
                         updateDispositions(deliveryTags, current.getResultantState(), current.isSettled());
                         deliveryTags.clear();
                         current = disposition;
                     }
+                    deliveryTags.add(disposition.getDeliveryTag());
                 }
                 if (!deliveryTags.isEmpty())
                 {


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


[08/11] qpid-broker-j git commit: QPID-8079: [Broker-J] Ensure that actions associated with AsyncCommand are rolled back if the underlying future completes unsucessfully

Posted by or...@apache.org.
QPID-8079: [Broker-J] Ensure that actions associated with AsyncCommand are rolled back if the underlying future completes unsucessfully

(cherry picked from commit 5fa398cfc2141d6ec090df3464f5bcbf63d7b023)


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/02cf0ff1
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/02cf0ff1
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/02cf0ff1

Branch: refs/heads/7.0.x
Commit: 02cf0ff16722cab8a6678f5af4472ee4b678f6bd
Parents: 1d8d0bc
Author: Keith Wall <kw...@apache.org>
Authored: Tue Jan 16 11:50:09 2018 +0000
Committer: Alex Rudyy <or...@apache.org>
Committed: Mon Jan 29 14:02:27 2018 +0000

----------------------------------------------------------------------
 .../server/txn/AsyncAutoCommitTransaction.java  |  4 +-
 .../apache/qpid/server/txn/AsyncCommand.java    | 98 ++++++++++++++++++++
 .../server/protocol/v0_10/ServerSession.java    | 62 +------------
 .../qpid/server/protocol/v0_8/AMQChannel.java   | 57 +-----------
 .../v1_0/StandardReceivingLinkEndpoint.java     | 57 +-----------
 5 files changed, 103 insertions(+), 175 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/02cf0ff1/broker-core/src/main/java/org/apache/qpid/server/txn/AsyncAutoCommitTransaction.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/txn/AsyncAutoCommitTransaction.java b/broker-core/src/main/java/org/apache/qpid/server/txn/AsyncAutoCommitTransaction.java
index 1f65aa3..32e3a6c 100755
--- a/broker-core/src/main/java/org/apache/qpid/server/txn/AsyncAutoCommitTransaction.java
+++ b/broker-core/src/main/java/org/apache/qpid/server/txn/AsyncAutoCommitTransaction.java
@@ -212,7 +212,7 @@ public class AsyncAutoCommitTransaction implements ServerTransaction
 
                 txn = _messageStore.newTransaction();
                 enqueueRecord = txn.enqueueMessage(queue, message);
-                future = txn.commitTranAsync((Void) null);
+                future = txn.commitTranAsync(null);
                 txn = null;
             }
             else
@@ -232,7 +232,7 @@ public class AsyncAutoCommitTransaction implements ServerTransaction
                 @Override
                 public void onRollback()
                 {
-                    underlying.postCommit(enqueueRecord);
+                    underlying.onRollback();
                 }
             }, message.isPersistent());
             postTransactionAction = null;

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/02cf0ff1/broker-core/src/main/java/org/apache/qpid/server/txn/AsyncCommand.java
----------------------------------------------------------------------
diff --git a/broker-core/src/main/java/org/apache/qpid/server/txn/AsyncCommand.java b/broker-core/src/main/java/org/apache/qpid/server/txn/AsyncCommand.java
new file mode 100644
index 0000000..29ce605
--- /dev/null
+++ b/broker-core/src/main/java/org/apache/qpid/server/txn/AsyncCommand.java
@@ -0,0 +1,98 @@
+/*
+ * 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.txn;
+
+import java.util.concurrent.ExecutionException;
+
+import com.google.common.util.concurrent.ListenableFuture;
+
+import org.apache.qpid.server.util.ServerScopedRuntimeException;
+
+public class AsyncCommand
+{
+    private final ListenableFuture<Void> _future;
+    private ServerTransaction.Action _action;
+
+    public AsyncCommand(final ListenableFuture<Void> future, final ServerTransaction.Action action)
+    {
+        _future = future;
+        _action = action;
+    }
+
+    public void complete()
+    {
+        boolean interrupted = false;
+        boolean success = false;
+        try
+        {
+            while (true)
+            {
+                try
+                {
+                    _future.get();
+                    break;
+                }
+                catch (InterruptedException e)
+                {
+                    interrupted = true;
+                }
+
+            }
+            success = true;
+        }
+        catch(ExecutionException e)
+        {
+            if(e.getCause() instanceof RuntimeException)
+            {
+                throw (RuntimeException)e.getCause();
+            }
+            else if(e.getCause() instanceof Error)
+            {
+                throw (Error) e.getCause();
+            }
+            else
+            {
+                throw new ServerScopedRuntimeException(e.getCause());
+            }
+        }
+        finally
+        {
+            if(interrupted)
+            {
+                Thread.currentThread().interrupt();
+            }
+            if (success)
+            {
+                _action.postCommit();
+            }
+            else
+            {
+                _action.onRollback();
+            }
+            _action = null;
+        }
+    }
+
+    public boolean isReadyForCompletion()
+    {
+        return _future.isDone();
+    }
+}

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/02cf0ff1/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSession.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSession.java b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSession.java
index f2bb0cc..b224fa6 100644
--- a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSession.java
+++ b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSession.java
@@ -56,7 +56,6 @@ import java.util.SortedMap;
 import java.util.UUID;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentSkipListMap;
-import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Semaphore;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
@@ -68,6 +67,7 @@ import com.google.common.util.concurrent.ListenableFuture;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import org.apache.qpid.server.txn.AsyncCommand;
 import org.apache.qpid.server.logging.LogMessage;
 import org.apache.qpid.server.logging.LogSubject;
 import org.apache.qpid.server.logging.messages.ChannelMessages;
@@ -97,7 +97,6 @@ import org.apache.qpid.server.txn.SuspendAndFailDtxException;
 import org.apache.qpid.server.txn.TimeoutDtxException;
 import org.apache.qpid.server.txn.UnknownDtxBranchException;
 import org.apache.qpid.server.util.Action;
-import org.apache.qpid.server.util.ServerScopedRuntimeException;
 
 public class ServerSession extends SessionInvoker
         implements LogSubject, AsyncAutoCommitTransaction.FutureRecorder
@@ -1636,65 +1635,6 @@ public class ServerSession extends SessionInvoker
         _unfinishedCommandsQueue.add(new AsyncCommand(future, action));
     }
 
-    private static class AsyncCommand
-    {
-        private final ListenableFuture<Void> _future;
-        private ServerTransaction.Action _action;
-
-        public AsyncCommand(final ListenableFuture<Void> future, final ServerTransaction.Action action)
-        {
-            _future = future;
-            _action = action;
-        }
-
-        void complete()
-        {
-            boolean interrupted = false;
-            try
-            {
-                while (true)
-                {
-                    try
-                    {
-                        _future.get();
-                        break;
-                    }
-                    catch (InterruptedException e)
-                    {
-                        interrupted = true;
-                    }
-
-                }
-            }
-            catch(ExecutionException e)
-            {
-                if(e.getCause() instanceof RuntimeException)
-                {
-                    throw (RuntimeException)e.getCause();
-                }
-                else if(e.getCause() instanceof Error)
-                {
-                    throw (Error) e.getCause();
-                }
-                else
-                {
-                    throw new ServerScopedRuntimeException(e.getCause());
-                }
-            }
-            if(interrupted)
-            {
-                Thread.currentThread().interrupt();
-            }
-            _action.postCommit();
-            _action = null;
-        }
-
-        boolean isReadyForCompletion()
-        {
-            return _future.isDone();
-        }
-    }
-
     public void setModelObject(final Session_0_10 session)
     {
         _modelObject = session;

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/02cf0ff1/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 a12b483..70de9cc 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
@@ -38,7 +38,6 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.UUID;
-import java.util.concurrent.ExecutionException;
 import java.util.concurrent.atomic.AtomicBoolean;
 
 import javax.security.auth.Subject;
@@ -95,10 +94,10 @@ import org.apache.qpid.server.store.StoredMessage;
 import org.apache.qpid.server.store.TransactionLogResource;
 import org.apache.qpid.server.transport.AMQPConnection;
 import org.apache.qpid.server.txn.AsyncAutoCommitTransaction;
+import org.apache.qpid.server.txn.AsyncCommand;
 import org.apache.qpid.server.txn.LocalTransaction;
 import org.apache.qpid.server.txn.ServerTransaction;
 import org.apache.qpid.server.util.Action;
-import org.apache.qpid.server.util.ServerScopedRuntimeException;
 import org.apache.qpid.server.virtualhost.MessageDestinationIsAlternateException;
 import org.apache.qpid.server.virtualhost.RequiredExchangeException;
 import org.apache.qpid.server.virtualhost.ReservedExchangeNameException;
@@ -1611,60 +1610,6 @@ public class AMQChannel extends AbstractAMQPSession<AMQChannel, ConsumerTarget_0
         }
     }
 
-    private static class AsyncCommand
-    {
-        private final ListenableFuture<Void> _future;
-        private ServerTransaction.Action _action;
-
-        public AsyncCommand(final ListenableFuture<Void> future, final ServerTransaction.Action action)
-        {
-            _future = future;
-            _action = action;
-        }
-
-        void complete()
-        {
-            boolean interrupted = false;
-            try
-            {
-                while (true)
-                {
-                    try
-                    {
-                        _future.get();
-                        break;
-                    }
-                    catch (InterruptedException e)
-                    {
-                        interrupted = true;
-                    }
-
-                }
-            }
-            catch(ExecutionException e)
-            {
-                if(e.getCause() instanceof RuntimeException)
-                {
-                    throw (RuntimeException)e.getCause();
-                }
-                else if(e.getCause() instanceof Error)
-                {
-                    throw (Error) e.getCause();
-                }
-                else
-                {
-                    throw new ServerScopedRuntimeException(e.getCause());
-                }
-            }
-            if(interrupted)
-            {
-                Thread.currentThread().interrupt();
-            }
-            _action.postCommit();
-            _action = null;
-        }
-    }
-
     @Override
     public long getTransactionStartTimeLong()
     {

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/02cf0ff1/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 aebff2e..2d2b206 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
@@ -33,7 +33,6 @@ import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
-import java.util.concurrent.ExecutionException;
 
 import com.google.common.util.concurrent.ListenableFuture;
 import org.slf4j.Logger;
@@ -69,10 +68,10 @@ import org.apache.qpid.server.protocol.v1_0.type.transport.Detach;
 import org.apache.qpid.server.protocol.v1_0.type.transport.Error;
 import org.apache.qpid.server.protocol.v1_0.type.transport.ReceiverSettleMode;
 import org.apache.qpid.server.txn.AsyncAutoCommitTransaction;
+import org.apache.qpid.server.txn.AsyncCommand;
 import org.apache.qpid.server.txn.AutoCommitTransaction;
 import org.apache.qpid.server.txn.LocalTransaction;
 import org.apache.qpid.server.txn.ServerTransaction;
-import org.apache.qpid.server.util.ServerScopedRuntimeException;
 
 public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint<Target>
         implements AsyncAutoCommitTransaction.FutureRecorder
@@ -618,60 +617,6 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
         }
     }
 
-    private static class AsyncCommand
-    {
-        private final ListenableFuture<Void> _future;
-        private ServerTransaction.Action _action;
-
-        public AsyncCommand(final ListenableFuture<Void> future, final ServerTransaction.Action action)
-        {
-            _future = future;
-            _action = action;
-        }
-
-        void complete()
-        {
-            boolean interrupted = false;
-            try
-            {
-                while (true)
-                {
-                    try
-                    {
-                        _future.get();
-                        break;
-                    }
-                    catch (InterruptedException e)
-                    {
-                        interrupted = true;
-                    }
-
-                }
-            }
-            catch(ExecutionException e)
-            {
-                if(e.getCause() instanceof RuntimeException)
-                {
-                    throw (RuntimeException)e.getCause();
-                }
-                else if(e.getCause() instanceof java.lang.Error)
-                {
-                    throw (java.lang.Error) e.getCause();
-                }
-                else
-                {
-                    throw new ServerScopedRuntimeException(e.getCause());
-                }
-            }
-            if(interrupted)
-            {
-                Thread.currentThread().interrupt();
-            }
-            _action.postCommit();
-            _action = null;
-        }
-    }
-
     private static class PendingDispositionHolder
     {
         private final Binary _deliveryTag;


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


[10/11] qpid-broker-j git commit: QPID-8032 : [Broker-J][AMQP 1.0] Add protocol tests for receiving of multiple messages

Posted by or...@apache.org.
QPID-8032 : [Broker-J][AMQP 1.0] Add protocol tests for receiving of multiple messages

(cherry picked from commit a627b2742a893c9873483dee7c4ad1cb7d8428cd)


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/c24f1b73
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/c24f1b73
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/c24f1b73

Branch: refs/heads/7.0.x
Commit: c24f1b737d5735c9caeddcb114f6eda999afc28c
Parents: f608040
Author: Alex Rudyy <or...@apache.org>
Authored: Tue Jan 23 22:17:14 2018 +0000
Committer: Alex Rudyy <or...@apache.org>
Committed: Mon Jan 29 14:03:52 2018 +0000

----------------------------------------------------------------------
 .../qpid/tests/protocol/v1_0/Interaction.java   |  35 +++-
 .../protocol/v1_0/messaging/TransferTest.java   | 161 +++++++++++++++++++
 2 files changed, 189 insertions(+), 7 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/c24f1b73/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 5898cf6..0a9f882 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
@@ -28,7 +28,9 @@ import static org.hamcrest.Matchers.is;
 
 import java.nio.charset.StandardCharsets;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collections;
+import java.util.HashSet;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
@@ -872,6 +874,13 @@ public class Interaction extends AbstractInteraction<Interaction>
         return this;
     }
 
+
+    public Interaction dispositionLast(final UnsignedInteger last)
+    {
+        _disposition.setLast(last);
+        return this;
+    }
+
     public Interaction dispositionFirstFromLatestDelivery()
     {
         _disposition.setFirst(_latestDeliveryId);
@@ -1040,14 +1049,19 @@ public class Interaction extends AbstractInteraction<Interaction>
         return UnsignedInteger.valueOf(_deliveryIdCounter++);
     }
 
-    public Interaction receiveDelivery() throws Exception
+    public Interaction receiveDelivery(Class<?>... ignore) throws Exception
     {
         sync();
-        _latestDelivery = receiveAllTransfers();
+        _latestDelivery = receiveAllTransfers(ignore);
         _latestDeliveryId = _latestDelivery.size() > 0 ? _latestDelivery.get(0).getDeliveryId() : null;
         return this;
     }
 
+    public UnsignedInteger getLatestDeliveryId()
+    {
+        return _latestDeliveryId;
+    }
+
     public Interaction decodeLatestDelivery() throws AmqpErrorException
     {
         MessageDecoder messageDecoder = new MessageDecoder();
@@ -1071,15 +1085,22 @@ public class Interaction extends AbstractInteraction<Interaction>
         return _decodedLatestDelivery;
     }
 
-    private List<Transfer> receiveAllTransfers() throws Exception
+    private List<Transfer> receiveAllTransfers(final Class<?>... ignore) throws Exception
     {
         List<Transfer> transfers = new ArrayList<>();
-        boolean hasMore;
+        boolean hasMore = true;
         do
         {
-            Transfer responseTransfer = consumeResponse().getLatestResponse(Transfer.class);
-            hasMore = Boolean.TRUE.equals(responseTransfer.getMore());
-            transfers.add(responseTransfer);
+            Set<Class<?>> responseTypesSet = new HashSet<>(Arrays.asList(ignore));
+            responseTypesSet.add(Transfer.class);
+            Class<?>[] responseTypes = responseTypesSet.toArray(new Class<?>[responseTypesSet.size()]);
+            Response<?> latestResponse = consumeResponse(responseTypes).getLatestResponse();
+            if (latestResponse.getBody() instanceof Transfer)
+            {
+                Transfer responseTransfer = (Transfer) latestResponse.getBody();
+                hasMore = Boolean.TRUE.equals(responseTransfer.getMore());
+                transfers.add(responseTransfer);
+            }
         }
         while (hasMore);
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/c24f1b73/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 2574910..68d7179 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
@@ -85,6 +85,7 @@ import org.apache.qpid.tests.protocol.v1_0.Interaction;
 import org.apache.qpid.tests.protocol.v1_0.InteractionTransactionalState;
 import org.apache.qpid.tests.protocol.v1_0.MessageDecoder;
 import org.apache.qpid.tests.protocol.v1_0.MessageEncoder;
+import org.apache.qpid.tests.protocol.v1_0.Utils;
 import org.apache.qpid.tests.utils.BrokerAdmin;
 import org.apache.qpid.tests.utils.BrokerAdminUsingTestBase;
 
@@ -536,6 +537,8 @@ public class TransferTest extends BrokerAdminUsingTestBase
 
             interaction.consumeResponse(null, Flow.class);
 
+
+
         }
     }
 
@@ -973,6 +976,164 @@ public class TransferTest extends BrokerAdminUsingTestBase
         }
     }
 
+    @Test
+    @SpecificationTest(section = "2.6.12", description = "Transferring A Message.")
+    public void receiveMultipleDeliveries() throws Exception
+    {
+        int numberOfMessages = 4;
+        for (int i = 0; i < numberOfMessages; i++)
+        {
+            getBrokerAdmin().putMessageOnQueue(BrokerAdmin.TEST_QUEUE_NAME, TEST_MESSAGE_DATA + "_" + i);
+        }
+
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = transport.newInteraction()
+                                                     .negotiateProtocol().consumeResponse()
+                                                     .open().consumeResponse()
+                                                     .begin().consumeResponse()
+                                                     .attachRole(Role.RECEIVER)
+                                                     .attachSourceAddress(BrokerAdmin.TEST_QUEUE_NAME)
+                                                     .attachRcvSettleMode(ReceiverSettleMode.FIRST)
+                                                     .attach().consumeResponse()
+                                                     .flowIncomingWindow(UnsignedInteger.valueOf(numberOfMessages))
+                                                     .flowNextIncomingId(UnsignedInteger.ZERO)
+                                                     .flowOutgoingWindow(UnsignedInteger.ZERO)
+                                                     .flowNextOutgoingId(UnsignedInteger.ZERO)
+                                                     .flowLinkCredit(UnsignedInteger.valueOf(numberOfMessages))
+                                                     .flowHandleFromLinkHandle()
+                                                     .flow();
+
+            for (int i = 0; i < numberOfMessages; i++)
+            {
+                interaction.receiveDelivery(Flow.class).decodeLatestDelivery();
+                Object data = interaction.getDecodedLatestDelivery();
+                assertThat(data, Is.is(CoreMatchers.equalTo(TEST_MESSAGE_DATA + "_" + i)));
+                assertThat(interaction.getLatestDeliveryId(), Is.is(equalTo(UnsignedInteger.valueOf(i))));
+            }
+
+            interaction.dispositionSettled(true)
+                       .dispositionRole(Role.RECEIVER)
+                       .dispositionFirst(UnsignedInteger.ZERO)
+                       .dispositionLast(interaction.getLatestDeliveryId())
+                       .dispositionState(new Accepted())
+                       .disposition();
+
+            // make sure sure the disposition is handled by making drain request
+            interaction.flowLinkCredit(UnsignedInteger.ZERO)
+                       .flowDrain(Boolean.TRUE)
+                       .flow()
+                       .consumeResponse(Flow.class);
+
+            if (getBrokerAdmin().isQueueDepthSupported())
+            {
+                assertThat(getBrokerAdmin().getQueueDepthMessages(BrokerAdmin.TEST_QUEUE_NAME), is(equalTo(0)));
+            }
+        }
+
+        String messageText = TEST_MESSAGE_DATA + "_" + 4;
+        getBrokerAdmin().putMessageOnQueue(BrokerAdmin.TEST_QUEUE_NAME, messageText);
+        Object receivedMessage = Utils.receiveMessage(_brokerAddress, BrokerAdmin.TEST_QUEUE_NAME);
+        assertThat(receivedMessage, is(equalTo(messageText)));
+    }
+
+    @Test
+    @SpecificationTest(section = "2.6.12", description = "Transferring A Message.")
+    public void receiveMixtureOfTransactionalAndNonTransactionalDeliveries() throws Exception
+    {
+        int numberOfMessages = 4;
+        for (int i = 0; i < numberOfMessages; i++)
+        {
+            getBrokerAdmin().putMessageOnQueue(BrokerAdmin.TEST_QUEUE_NAME, TEST_MESSAGE_DATA + "_" + i);
+        }
+
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = transport.newInteraction()
+                                                     .negotiateProtocol().consumeResponse()
+                                                     .open().consumeResponse()
+                                                     .begin().consumeResponse()
+                                                     .attachRole(Role.RECEIVER)
+                                                     .attachSourceAddress(BrokerAdmin.TEST_QUEUE_NAME)
+                                                     .attachRcvSettleMode(ReceiverSettleMode.FIRST)
+                                                     .attachHandle(UnsignedInteger.ZERO)
+                                                     .attach().consumeResponse()
+                                                     .flowIncomingWindow(UnsignedInteger.valueOf(numberOfMessages))
+                                                     .flowNextIncomingId(UnsignedInteger.ZERO)
+                                                     .flowOutgoingWindow(UnsignedInteger.ZERO)
+                                                     .flowNextOutgoingId(UnsignedInteger.ZERO)
+                                                     .flowLinkCredit(UnsignedInteger.valueOf(numberOfMessages))
+                                                     .flowHandleFromLinkHandle()
+                                                     .flow();
+
+            for (int i = 0; i < numberOfMessages; i++)
+            {
+                interaction.receiveDelivery(Flow.class).decodeLatestDelivery();
+                Object data = interaction.getDecodedLatestDelivery();
+                assertThat(data, Is.is(CoreMatchers.equalTo(TEST_MESSAGE_DATA + "_" + i)));
+                assertThat(interaction.getLatestDeliveryId(), Is.is(equalTo(UnsignedInteger.valueOf(i))));
+            }
+
+            final InteractionTransactionalState txnState = interaction.createTransactionalState(UnsignedInteger.ONE);
+            interaction.txnAttachCoordinatorLink(txnState)
+                       .txnDeclare(txnState);
+
+            interaction.dispositionSettled(true)
+                       .dispositionRole(Role.RECEIVER)
+                       .dispositionFirst(UnsignedInteger.ZERO)
+                       .dispositionLast(UnsignedInteger.ONE)
+                       .dispositionState(new Accepted())
+                       .disposition()
+                       .dispositionSettled(true)
+                       .dispositionRole(Role.RECEIVER)
+                       .dispositionFirst(UnsignedInteger.valueOf(2))
+                       .dispositionLast(UnsignedInteger.valueOf(3))
+                       .dispositionTransactionalState(txnState.getCurrentTransactionId(), new Accepted())
+                       .disposition();
+
+
+            final Discharge discharge = new Discharge();
+            discharge.setTxnId(txnState.getCurrentTransactionId());
+            discharge.setFail(false);
+
+            interaction.transferHandle(txnState.getHandle())
+                       .transferDeliveryId(UnsignedInteger.valueOf(4))
+                       .transferDeliveryTag(new Binary(("transaction-" + 4).getBytes(StandardCharsets.UTF_8)))
+                       .transferPayloadData(discharge)
+                       .transfer();
+
+            Disposition declareTransactionDisposition = null;
+            Flow coordinatorFlow = null;
+            do
+            {
+                interaction.consumeResponse(Disposition.class, Flow.class);
+                Response<?> response = interaction.getLatestResponse();
+                if (response.getBody() instanceof Disposition)
+                {
+                    declareTransactionDisposition = (Disposition) response.getBody();
+                }
+                if (response.getBody() instanceof Flow)
+                {
+                    final Flow flowResponse = (Flow) response.getBody();
+                    if (flowResponse.getHandle().equals(txnState.getHandle()))
+                    {
+                        coordinatorFlow = flowResponse;
+                    }
+                }
+            } while(declareTransactionDisposition == null || coordinatorFlow == null);
+
+            if (getBrokerAdmin().isQueueDepthSupported())
+            {
+                assertThat(getBrokerAdmin().getQueueDepthMessages(BrokerAdmin.TEST_QUEUE_NAME), is(equalTo(0)));
+            }
+        }
+
+        String messageText = TEST_MESSAGE_DATA + "_" + 4;
+        getBrokerAdmin().putMessageOnQueue(BrokerAdmin.TEST_QUEUE_NAME, messageText);
+        Object receivedMessage = Utils.receiveMessage(_brokerAddress, BrokerAdmin.TEST_QUEUE_NAME);
+        assertThat(receivedMessage, is(equalTo(messageText)));
+    }
+
     private void assertDeliveries(final Interaction interaction, final TreeSet<UnsignedInteger> expectedDeliveryIds)
             throws Exception
     {


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


[11/11] qpid-broker-j git commit: QPID-8032 : [Broker-J] Address review comments

Posted by or...@apache.org.
QPID-8032 : [Broker-J] Address review comments

(cherry picked from commit c6cde241692c8840ad2c36e6ce4645be60d8adb7)


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/4e6c44d1
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/4e6c44d1
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/4e6c44d1

Branch: refs/heads/7.0.x
Commit: 4e6c44d10d459b9dd0b55c2d4c0bb1347c014d5c
Parents: c24f1b73
Author: Alex Rudyy <or...@apache.org>
Authored: Wed Jan 24 13:21:59 2018 +0000
Committer: Alex Rudyy <or...@apache.org>
Committed: Mon Jan 29 14:04:12 2018 +0000

----------------------------------------------------------------------
 .../org/apache/qpid/server/protocol/v0_10/ServerSession.java   | 6 +++---
 .../java/org/apache/qpid/server/protocol/v0_8/AMQChannel.java  | 4 ++--
 2 files changed, 5 insertions(+), 5 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/4e6c44d1/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSession.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSession.java b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSession.java
index b224fa6..e2211dd 100644
--- a/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSession.java
+++ b/broker-plugins/amqp-0-10-protocol/src/main/java/org/apache/qpid/server/protocol/v0_10/ServerSession.java
@@ -45,16 +45,17 @@ import java.text.MessageFormat;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.Deque;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
-import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.SortedMap;
 import java.util.UUID;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedDeque;
 import java.util.concurrent.ConcurrentSkipListMap;
 import java.util.concurrent.Semaphore;
 import java.util.concurrent.atomic.AtomicBoolean;
@@ -109,6 +110,7 @@ public class ServerSession extends SessionInvoker
     private static final int UNFINISHED_COMMAND_QUEUE_THRESHOLD = 500;
 
     private final Set<Object> _blockingEntities = Collections.synchronizedSet(new HashSet<>());
+    private final Deque<AsyncCommand> _unfinishedCommandsQueue = new ConcurrentLinkedDeque<>();
 
     private final AtomicBoolean _blocking = new AtomicBoolean(false);
     private final AtomicInteger _outstandingCredit = new AtomicInteger(UNLIMITED_CREDIT);
@@ -1596,8 +1598,6 @@ public class ServerSession extends SessionInvoker
         return _blocking.get();
     }
 
-    private final LinkedList<AsyncCommand> _unfinishedCommandsQueue = new LinkedList<AsyncCommand>();
-
     public void completeAsyncCommands()
     {
         AsyncCommand cmd;

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/4e6c44d1/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 70de9cc..e106a3f 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
@@ -33,11 +33,11 @@ import java.util.EnumSet;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.LinkedHashMap;
-import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.UUID;
+import java.util.concurrent.ConcurrentLinkedQueue;
 import java.util.concurrent.atomic.AtomicBoolean;
 
 import javax.security.auth.Subject;
@@ -155,7 +155,7 @@ public class AMQChannel extends AbstractAMQPSession<AMQChannel, ConsumerTarget_0
 
     private final MessageStore _messageStore;
 
-    private final LinkedList<AsyncCommand> _unfinishedCommandsQueue = new LinkedList<AsyncCommand>();
+    private final java.util.Queue<AsyncCommand> _unfinishedCommandsQueue = new ConcurrentLinkedQueue<>();
 
     private final UnacknowledgedMessageMap _unacknowledgedMessageMap;
 


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


[06/11] qpid-broker-j git commit: QPID-8062: [Broker-J][AMQP 1.0] Add additional tests

Posted by or...@apache.org.
QPID-8062: [Broker-J][AMQP 1.0] Add additional tests


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/42807eff
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/42807eff
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/42807eff

Branch: refs/heads/7.0.x
Commit: 42807eff86c3389c263874576a92a31f73ab104c
Parents: 2495d19
Author: Keith Wall <kw...@apache.org>
Authored: Thu Jan 18 14:41:54 2018 +0000
Committer: Alex Rudyy <or...@apache.org>
Committed: Mon Jan 29 13:57:56 2018 +0000

----------------------------------------------------------------------
 .../anonymousrelay/AnonymousRelayTest.java      | 470 ----------------
 .../AnonymousTerminusTest.java                  | 560 +++++++++++++++++++
 2 files changed, 560 insertions(+), 470 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/42807eff/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousrelay/AnonymousRelayTest.java
----------------------------------------------------------------------
diff --git a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousrelay/AnonymousRelayTest.java b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousrelay/AnonymousRelayTest.java
deleted file mode 100644
index 4fc18dd..0000000
--- a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousrelay/AnonymousRelayTest.java
+++ /dev/null
@@ -1,470 +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.tests.protocol.v1_0.extensions.anonymousrelay;
-
-
-import static org.hamcrest.CoreMatchers.hasItem;
-import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.hamcrest.CoreMatchers.notNullValue;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assume.assumeThat;
-
-import java.net.InetSocketAddress;
-import java.nio.charset.StandardCharsets;
-import java.util.Arrays;
-
-import org.junit.Before;
-import org.junit.Test;
-
-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.DeliveryState;
-import org.apache.qpid.server.protocol.v1_0.type.Symbol;
-import org.apache.qpid.server.protocol.v1_0.type.UnsignedInteger;
-import org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted;
-import org.apache.qpid.server.protocol.v1_0.type.messaging.Properties;
-import org.apache.qpid.server.protocol.v1_0.type.messaging.Rejected;
-import org.apache.qpid.server.protocol.v1_0.type.messaging.Target;
-import org.apache.qpid.server.protocol.v1_0.type.transaction.Coordinator;
-import org.apache.qpid.server.protocol.v1_0.type.transaction.Discharge;
-import org.apache.qpid.server.protocol.v1_0.type.transaction.TransactionError;
-import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
-import org.apache.qpid.server.protocol.v1_0.type.transport.Attach;
-import org.apache.qpid.server.protocol.v1_0.type.transport.Begin;
-import org.apache.qpid.server.protocol.v1_0.type.transport.Detach;
-import org.apache.qpid.server.protocol.v1_0.type.transport.Disposition;
-import org.apache.qpid.server.protocol.v1_0.type.transport.Error;
-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.Role;
-import org.apache.qpid.tests.protocol.Response;
-import org.apache.qpid.tests.protocol.SpecificationTest;
-import org.apache.qpid.tests.protocol.v1_0.FrameTransport;
-import org.apache.qpid.tests.protocol.v1_0.Interaction;
-import org.apache.qpid.tests.protocol.v1_0.InteractionTransactionalState;
-import org.apache.qpid.tests.protocol.v1_0.MessageEncoder;
-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 AnonymousRelayTest extends BrokerAdminUsingTestBase
-{
-    private static final Symbol ANONYMOUS_RELAY = Symbol.valueOf("ANONYMOUS-RELAY");
-    private static final Symbol DELIVERY_TAG = Symbol.valueOf("delivery-tag");
-    private static final String TEST_MESSAGE_CONTENT = "test";
-    private InetSocketAddress _brokerAddress;
-    private Binary _deliveryTag;
-
-    @Before
-    public void setUp()
-    {
-        final BrokerAdmin brokerAdmin = getBrokerAdmin();
-        brokerAdmin.createQueue(BrokerAdmin.TEST_QUEUE_NAME);
-        _brokerAddress = brokerAdmin.getBrokerAddress(BrokerAdmin.PortType.ANONYMOUS_AMQP);
-        _deliveryTag = new Binary("testTag".getBytes(StandardCharsets.UTF_8));
-    }
-
-    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2. Sending A Message",
-            description = "Messages sent over links into a routing node will be"
-                          + " forwarded to the node referenced in the to field of properties of the message"
-                          + " just as if a direct link has been established to that node.")
-    @Test
-    public void transferPreSettledToExistingDestination() throws Exception
-    {
-        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
-        {
-            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
-
-            interaction.begin()
-                       .consumeResponse(Begin.class)
-
-                       .attachRole(Role.SENDER)
-                       .attach().consumeResponse(Attach.class)
-                       .consumeResponse(Flow.class)
-
-                       .transferPayload(generateMessagePayloadToDestination(BrokerAdmin.TEST_QUEUE_NAME))
-                       .transferSettled(Boolean.TRUE)
-                       .transferDeliveryTag(_deliveryTag)
-                       .transfer()
-                       .sync();
-
-            Object receivedMessage = Utils.receiveMessage(_brokerAddress, BrokerAdmin.TEST_QUEUE_NAME);
-            assertThat(receivedMessage, is(equalTo(TEST_MESSAGE_CONTENT)));
-        }
-    }
-
-    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2.2 Routing Errors",
-            description = "It is possible that a message sent to a routing node has an address in the to field"
-                          + " of properties which, if used in the address field of target of an attach,"
-                          + " would result in an unsuccessful link establishment (for example,"
-                          + " if the address cannot be resolved to a node). In this case the routing node"
-                          + " MUST communicate the error back to the sender of the message."
-                          + " [...] the message has already been settled by the sender,"
-                          + " then the routing node MUST detach the link with an error."
-                          + " [...] the info field of error MUST contain an entry with symbolic key delivery-tag"
-                          + " and binary value of the delivery-tag of the message which caused the failure.")
-    @Test
-    public void transferPreSettledToUnknownDestination() throws Exception
-    {
-        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
-        {
-            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
-
-            interaction.begin()
-                       .consumeResponse(Begin.class)
-
-                       .attachRole(Role.SENDER)
-                       .attach().consumeResponse(Attach.class)
-                       .consumeResponse(Flow.class)
-
-                       .transferPayload(generateMessagePayloadToDestination("Unknown"))
-                       .transferSettled(Boolean.TRUE)
-                       .transferDeliveryTag(_deliveryTag)
-                       .transfer();
-
-            Detach detach = interaction.consumeResponse().getLatestResponse(Detach.class);
-            Error error = detach.getError();
-            assertThat(error, is(notNullValue()));
-            assertThat(error.getCondition(), is(equalTo(AmqpError.NOT_FOUND)));
-            assertThat(error.getInfo(), is(notNullValue()));
-            assertThat(error.getInfo().get(DELIVERY_TAG), is(equalTo(_deliveryTag)));
-        }
-    }
-
-    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2.2 Routing Errors",
-            description = "It is possible that a message sent to a routing node has an address in the to field"
-                          + " of properties which, if used in the address field of target of an attach,"
-                          + " would result in an unsuccessful link establishment (for example,"
-                          + " if the address cannot be resolved to a node). In this case the routing node"
-                          + " MUST communicate the error back to the sender of the message."
-                          + " If the source of the link supports the rejected outcome,"
-                          + " and the message has not already been settled by the sender, then the routing node"
-                          + " MUST reject the message."
-                          + " [...] the info field of error MUST contain an entry with symbolic key delivery-tag"
-                          + " and binary value of the delivery-tag of the message which caused the failure.")
-    @Test
-    public void transferUnsettledToUnknownDestinationWhenRejectedOutcomeSupportedBySource() throws Exception
-    {
-        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
-        {
-            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
-
-            interaction.begin()
-                       .consumeResponse(Begin.class)
-
-                       .attachRole(Role.SENDER)
-                       .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL, Rejected.REJECTED_SYMBOL)
-                       .attach().consumeResponse(Attach.class)
-                       .consumeResponse(Flow.class)
-
-                       .transferPayload(generateMessagePayloadToDestination("Unknown"))
-                       .transferDeliveryTag(_deliveryTag)
-                       .transfer()
-                       .consumeResponse();
-
-            Disposition disposition = interaction.getLatestResponse(Disposition.class);
-
-            assertThat(disposition.getSettled(), is(true));
-
-            DeliveryState dispositionState = disposition.getState();
-            assertThat(dispositionState, is(instanceOf(Rejected.class)));
-
-            Rejected rejected = (Rejected)dispositionState;
-            Error error = rejected.getError();
-            assertThat(error, is(notNullValue()));
-            assertThat(error.getCondition(), is(equalTo(AmqpError.NOT_FOUND)));
-            assertThat(error.getInfo(), is(notNullValue()));
-            assertThat(error.getInfo().get(DELIVERY_TAG), is(equalTo(_deliveryTag)));
-        }
-    }
-
-    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2.2 Routing Errors",
-            description = "It is possible that a message sent to a routing node has an address in the to field"
-                          + " of properties which, if used in the address field of target of an attach,"
-                          + " would result in an unsuccessful link establishment (for example,"
-                          + " if the address cannot be resolved to a node). In this case the routing node"
-                          + " MUST communicate the error back to the sender of the message."
-                          + " [...]"
-                          + " If the source of the link does not support the rejected outcome,"
-                          + " [...] then the routing node MUST detach the link with an error."
-                          + " [...] the info field of error MUST contain an entry with symbolic key delivery-tag"
-                          + " and binary value of the delivery-tag of the message which caused the failure.")
-    @Test
-    public void transferUnsettledToUnknownDestinationWhenRejectedOutcomeNotSupportedBySource() throws Exception
-    {
-        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
-        {
-            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
-
-            interaction.begin()
-                       .consumeResponse(Begin.class)
-
-                       .attachRole(Role.SENDER)
-                       .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL)
-                       .attach().consumeResponse(Attach.class)
-                       .consumeResponse(Flow.class)
-
-                       .transferPayload(generateMessagePayloadToDestination("Unknown"))
-                       .transferDeliveryTag(_deliveryTag)
-                       .transfer();
-
-            Detach detach = interaction.consumeResponse().getLatestResponse(Detach.class);
-            Error error = detach.getError();
-            assertThat(error, is(notNullValue()));
-            assertThat(error.getCondition(), is(equalTo(AmqpError.NOT_FOUND)));
-            assertThat(error.getInfo(), is(notNullValue()));
-            assertThat(error.getInfo().get(DELIVERY_TAG), is(equalTo(_deliveryTag)));
-        }
-    }
-
-    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2. Sending A Message",
-            description = "Messages sent over links into a routing node will be"
-                          + " forwarded to the node referenced in the to field of properties of the message"
-                          + " just as if a direct link has been established to that node.")
-    @Test
-    public void transferPreSettledInTransactionToExistingDestination() throws Exception
-    {
-        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
-        {
-            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
-            final UnsignedInteger linkHandle = UnsignedInteger.ONE;
-            final InteractionTransactionalState txnState = interaction.createTransactionalState(UnsignedInteger.ZERO);
-            interaction.begin()
-                       .consumeResponse(Begin.class)
-
-                       .txnAttachCoordinatorLink(txnState)
-                       .txnDeclare(txnState)
-
-                       .attachRole(Role.SENDER)
-                       .attachHandle(linkHandle)
-                       .attach().consumeResponse(Attach.class)
-                       .consumeResponse(Flow.class)
-
-                       .transferHandle(linkHandle)
-                       .transferPayload(generateMessagePayloadToDestination(BrokerAdmin.TEST_QUEUE_NAME))
-                       .transferDeliveryTag(_deliveryTag)
-                       .transferTransactionalState(txnState.getCurrentTransactionId())
-                       .transferSettled(Boolean.TRUE)
-                       .transfer()
-
-                       .txnDischarge(txnState, false);
-
-            Object receivedMessage = Utils.receiveMessage(_brokerAddress, BrokerAdmin.TEST_QUEUE_NAME);
-            assertThat(receivedMessage, is(equalTo(TEST_MESSAGE_CONTENT)));
-        }
-    }
-
-    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2.2 Routing Errors",
-            description = "It is possible that a message sent to a routing node has an address in the to field"
-                          + " of properties which, if used in the address field of target of an attach,"
-                          + " would result in an unsuccessful link establishment (for example,"
-                          + " if the address cannot be resolved to a node). In this case the routing node"
-                          + " MUST communicate the error back to the sender of the message."
-                          + " [...]"
-                          + " <Not in spec yet>"
-                          + " AMQP-140"
-                          + " If a message cannot be routed to the destination implied in the \"to:\" field,"
-                          + " and the source does not allow for the rejected outcome"
-                          + " [...] when messages are being sent within a transaction and have been sent pre-settled."
-                          + " In this case the behaviour defined for transactions (of essentially marking"
-                          + " the transaction as rollback only) should take precedence. "
-                            + ""
-                          + " AMQP spec 4.3 Discharging a Transaction"
-                          + " If the coordinator is unable to complete the discharge, the coordinator MUST convey"
-                          + " the error to the controller as a transaction-error. If the source for the link to"
-                          + " the coordinator supports the rejected outcome, then the message MUST be rejected"
-                          + " with this outcome carrying the transaction-error.")
-    @Test
-    public void transferPreSettledInTransactionToUnknownDestinationWhenRejectOutcomeSupportedByTxController()
-            throws Exception
-    {
-        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
-        {
-            final UnsignedInteger linkHandle = UnsignedInteger.ONE;
-            final Interaction interaction =
-                    openInteractionWithAnonymousRelayCapability(transport);
-
-            final InteractionTransactionalState txnState = interaction.createTransactionalState(UnsignedInteger.ZERO);
-            interaction.begin()
-                       .consumeResponse(Begin.class)
-
-                       // attaching coordinator link with supported outcomes Accepted and Rejected
-                       .txnAttachCoordinatorLink(txnState)
-                       .txnDeclare(txnState)
-
-                       .attachRole(Role.SENDER)
-                       .attachHandle(linkHandle)
-                       .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL, Rejected.REJECTED_SYMBOL)
-                       .attach().consumeResponse(Attach.class)
-                       .consumeResponse(Flow.class)
-
-                       .transferHandle(linkHandle)
-                       .transferPayload(generateMessagePayloadToDestination("Unknown"))
-                       .transferDeliveryTag(_deliveryTag)
-                       .transferTransactionalState(txnState.getCurrentTransactionId())
-                       .transferSettled(Boolean.TRUE)
-                       .transferDeliveryId(UnsignedInteger.valueOf(1))
-                       .transfer();
-
-            final Discharge discharge = new Discharge();
-            discharge.setTxnId(txnState.getCurrentTransactionId());
-            discharge.setFail(false);
-            interaction.transferHandle(txnState.getHandle())
-                       .transferDeliveryId(UnsignedInteger.valueOf(2))
-                       .transferSettled(Boolean.FALSE)
-                       .transferDeliveryTag(new Binary(("transaction-" + 2).getBytes(StandardCharsets.UTF_8)))
-                       .transferPayloadData(discharge).transfer();
-
-            Disposition dischargeTransactionDisposition = null;
-            Flow coordinatorFlow = null;
-            do
-            {
-                interaction.consumeResponse(Disposition.class, Flow.class);
-                Response<?> response = interaction.getLatestResponse();
-                if (response.getBody() instanceof Disposition)
-                {
-                    dischargeTransactionDisposition = (Disposition) response.getBody();
-                }
-                if (response.getBody() instanceof Flow)
-                {
-                    final Flow flowResponse = (Flow) response.getBody();
-                    if (flowResponse.getHandle().equals(txnState.getHandle()))
-                    {
-                        coordinatorFlow = flowResponse;
-                    }
-                }
-            } while (dischargeTransactionDisposition == null || coordinatorFlow == null);
-
-            assertThat(dischargeTransactionDisposition.getSettled(), is(equalTo(true)));
-            assertThat(dischargeTransactionDisposition.getState(), is(instanceOf(Rejected.class)));
-
-            Rejected rejected = (Rejected) dischargeTransactionDisposition.getState();
-            Error error = rejected.getError();
-
-            assertThat(error, is(notNullValue()));
-            assertThat(error.getCondition(), is(equalTo(TransactionError.TRANSACTION_ROLLBACK)));
-        }
-    }
-
-    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2.2 Routing Errors",
-            description = "It is possible that a message sent to a routing node has an address in the to field"
-                          + " of properties which, if used in the address field of target of an attach,"
-                          + " would result in an unsuccessful link establishment (for example,"
-                          + " if the address cannot be resolved to a node). In this case the routing node"
-                          + " MUST communicate the error back to the sender of the message."
-                          + " [...]"
-                          + " <Not in spec yet>"
-                          + " AMQP-140"
-                          + " If a message cannot be routed to the destination implied in the \"to:\" field,"
-                          + " and the source does not allow for the rejected outcome"
-                          + " [...] when messages are being sent within a transaction and have been sent pre-settled."
-                          + " In this case the behaviour defined for transactions (of essentially marking"
-                          + " the transaction as rollback only) should take precedence. "
-                          + ""
-                          + " AMQP spec 4.3 Discharging a Transaction"
-                          + " If the coordinator is unable to complete the discharge, the coordinator MUST convey"
-                          + " the error to the controller as a transaction-error."
-                          + " [...]"
-                          + " If the source does not support the rejected outcome, the transactional resource MUST"
-                          + " detach the link to the coordinator, with the detach performative carrying"
-                          + " the transaction-error")
-    @Test
-    public void transferPreSettledInTransactionToUnknownDestinationWhenRejectOutcomeNotSupportedByTxController()
-            throws Exception
-    {
-        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
-        {
-            final UnsignedInteger linkHandle = UnsignedInteger.ONE;
-            final Interaction interaction =
-                    openInteractionWithAnonymousRelayCapability(transport);
-
-            final InteractionTransactionalState txnState = interaction.createTransactionalState(UnsignedInteger.ZERO);
-
-            interaction.begin()
-                       .consumeResponse(Begin.class)
-
-                       .attachRole(Role.SENDER)
-                       .attachName("testTransactionCoordinator-" + txnState.getHandle())
-                       .attachHandle(txnState.getHandle())
-                       .attachInitialDeliveryCount(UnsignedInteger.ZERO)
-                       .attachTarget(new Coordinator())
-                       .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL)
-                       .attach().consumeResponse(Attach.class)
-                       .consumeResponse(Flow.class)
-                       .txnDeclare(txnState)
-
-                       .attachRole(Role.SENDER)
-                       .attachHandle(linkHandle)
-                       .attachTarget(new Target())
-                       .attachName("link-" + linkHandle)
-                       .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL, Rejected.REJECTED_SYMBOL)
-                       .attach().consumeResponse(Attach.class)
-                       .consumeResponse(Flow.class)
-
-                       .transferHandle(linkHandle)
-                       .transferPayload(generateMessagePayloadToDestination("Unknown"))
-                       .transferDeliveryTag(_deliveryTag)
-                       .transferTransactionalState(txnState.getCurrentTransactionId())
-                       .transferSettled(Boolean.TRUE)
-                       .transfer();
-
-            final Discharge discharge = new Discharge();
-            discharge.setTxnId(txnState.getCurrentTransactionId());
-            discharge.setFail(false);
-
-            interaction.transferHandle(txnState.getHandle())
-                       .transferSettled(Boolean.FALSE)
-                       .transferDeliveryId(UnsignedInteger.valueOf(4))
-                       .transferDeliveryTag(new Binary(("transaction-" + 4).getBytes(StandardCharsets.UTF_8)))
-                       .transferPayloadData(discharge).transfer();
-
-            Detach transactionCoordinatorDetach = interaction.consumeResponse().getLatestResponse(Detach.class);
-            Error transactionCoordinatorDetachError = transactionCoordinatorDetach.getError();
-            assertThat(transactionCoordinatorDetachError, is(notNullValue()));
-            assertThat(transactionCoordinatorDetachError.getCondition(), is(equalTo(TransactionError.TRANSACTION_ROLLBACK)));
-        }
-    }
-
-
-    private Interaction openInteractionWithAnonymousRelayCapability(final FrameTransport transport) throws Exception
-    {
-        final Interaction interaction = transport.newInteraction();
-        interaction.negotiateProtocol().consumeResponse()
-                   .openDesiredCapabilities(ANONYMOUS_RELAY)
-                   .open().consumeResponse(Open.class);
-
-        Open open = interaction.getLatestResponse(Open.class);
-        assumeThat(Arrays.asList(open.getOfferedCapabilities()), hasItem(ANONYMOUS_RELAY));
-        return interaction;
-    }
-
-    private QpidByteBuffer generateMessagePayloadToDestination(final String destinationName)
-    {
-        MessageEncoder messageEncoder = new MessageEncoder();
-        final Properties properties = new Properties();
-        properties.setTo(destinationName);
-        messageEncoder.setProperties(properties);
-        messageEncoder.addData(TEST_MESSAGE_CONTENT);
-        return messageEncoder.getPayload();
-    }
-}

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/42807eff/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousterminus/AnonymousTerminusTest.java
----------------------------------------------------------------------
diff --git a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousterminus/AnonymousTerminusTest.java b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousterminus/AnonymousTerminusTest.java
new file mode 100644
index 0000000..d837e38
--- /dev/null
+++ b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousterminus/AnonymousTerminusTest.java
@@ -0,0 +1,560 @@
+/*
+ *
+ * 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.tests.protocol.v1_0.extensions.anonymousterminus;
+
+
+import static org.hamcrest.CoreMatchers.hasItem;
+import static org.hamcrest.CoreMatchers.instanceOf;
+import static org.hamcrest.CoreMatchers.notNullValue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assume.assumeThat;
+
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+
+import org.junit.Before;
+import org.junit.Test;
+
+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.DeliveryState;
+import org.apache.qpid.server.protocol.v1_0.type.Symbol;
+import org.apache.qpid.server.protocol.v1_0.type.UnsignedInteger;
+import org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted;
+import org.apache.qpid.server.protocol.v1_0.type.messaging.Properties;
+import org.apache.qpid.server.protocol.v1_0.type.messaging.Rejected;
+import org.apache.qpid.server.protocol.v1_0.type.messaging.Target;
+import org.apache.qpid.server.protocol.v1_0.type.transaction.Coordinator;
+import org.apache.qpid.server.protocol.v1_0.type.transaction.Discharge;
+import org.apache.qpid.server.protocol.v1_0.type.transaction.TransactionError;
+import org.apache.qpid.server.protocol.v1_0.type.transaction.TransactionalState;
+import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
+import org.apache.qpid.server.protocol.v1_0.type.transport.Attach;
+import org.apache.qpid.server.protocol.v1_0.type.transport.Begin;
+import org.apache.qpid.server.protocol.v1_0.type.transport.Detach;
+import org.apache.qpid.server.protocol.v1_0.type.transport.Disposition;
+import org.apache.qpid.server.protocol.v1_0.type.transport.Error;
+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.Role;
+import org.apache.qpid.tests.protocol.Response;
+import org.apache.qpid.tests.protocol.SpecificationTest;
+import org.apache.qpid.tests.protocol.v1_0.FrameTransport;
+import org.apache.qpid.tests.protocol.v1_0.Interaction;
+import org.apache.qpid.tests.protocol.v1_0.InteractionTransactionalState;
+import org.apache.qpid.tests.protocol.v1_0.MessageEncoder;
+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 AnonymousTerminusTest extends BrokerAdminUsingTestBase
+{
+    private static final Symbol ANONYMOUS_RELAY = Symbol.valueOf("ANONYMOUS-RELAY");
+    private static final Symbol DELIVERY_TAG = Symbol.valueOf("delivery-tag");
+    private static final String TEST_MESSAGE_CONTENT = "test";
+    private InetSocketAddress _brokerAddress;
+    private Binary _deliveryTag;
+
+    @Before
+    public void setUp()
+    {
+        final BrokerAdmin brokerAdmin = getBrokerAdmin();
+        brokerAdmin.createQueue(BrokerAdmin.TEST_QUEUE_NAME);
+        _brokerAddress = brokerAdmin.getBrokerAddress(BrokerAdmin.PortType.ANONYMOUS_AMQP);
+        _deliveryTag = new Binary("testTag".getBytes(StandardCharsets.UTF_8));
+    }
+
+    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2. Sending A Message",
+            description = "Messages sent over links into a routing node will be"
+                          + " forwarded to the node referenced in the to field of properties of the message"
+                          + " just as if a direct link has been established to that node.")
+    @Test
+    public void transferPreSettledToKnownDestination() throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
+
+            interaction.begin()
+                       .consumeResponse(Begin.class)
+
+                       .attachRole(Role.SENDER)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+
+                       .transferPayload(generateMessagePayloadToDestination(BrokerAdmin.TEST_QUEUE_NAME))
+                       .transferSettled(Boolean.TRUE)
+                       .transferDeliveryTag(_deliveryTag)
+                       .transfer()
+                       .sync();
+
+            Object receivedMessage = Utils.receiveMessage(_brokerAddress, BrokerAdmin.TEST_QUEUE_NAME);
+            assertThat(receivedMessage, is(equalTo(TEST_MESSAGE_CONTENT)));
+        }
+    }
+
+    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2.2 Routing Errors",
+            description = "It is possible that a message sent to a routing node has an address in the to field"
+                          + " of properties which, if used in the address field of target of an attach,"
+                          + " would result in an unsuccessful link establishment (for example,"
+                          + " if the address cannot be resolved to a node). In this case the routing node"
+                          + " MUST communicate the error back to the sender of the message."
+                          + " [...] the message has already been settled by the sender,"
+                          + " then the routing node MUST detach the link with an error."
+                          + " [...] the info field of error MUST contain an entry with symbolic key delivery-tag"
+                          + " and binary value of the delivery-tag of the message which caused the failure.")
+    @Test
+    public void transferPreSettledToUnknownDestination() throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
+
+            interaction.begin()
+                       .consumeResponse(Begin.class)
+
+                       .attachRole(Role.SENDER)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+
+                       .transferPayload(generateMessagePayloadToDestination("Unknown"))
+                       .transferSettled(Boolean.TRUE)
+                       .transferDeliveryTag(_deliveryTag)
+                       .transfer();
+
+            Detach detach = interaction.consumeResponse().getLatestResponse(Detach.class);
+            Error error = detach.getError();
+            assertThat(error, is(notNullValue()));
+            assertThat(error.getCondition(), is(equalTo(AmqpError.NOT_FOUND)));
+            assertThat(error.getInfo(), is(notNullValue()));
+            assertThat(error.getInfo().get(DELIVERY_TAG), is(equalTo(_deliveryTag)));
+        }
+    }
+
+    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2.2 Routing Errors",
+            description = "It is possible that a message sent to a routing node has an address in the to field"
+                          + " of properties which, if used in the address field of target of an attach,"
+                          + " would result in an unsuccessful link establishment (for example,"
+                          + " if the address cannot be resolved to a node). In this case the routing node"
+                          + " MUST communicate the error back to the sender of the message."
+                          + " If the source of the link supports the rejected outcome,"
+                          + " and the message has not already been settled by the sender, then the routing node"
+                          + " MUST reject the message."
+                          + " [...] the info field of error MUST contain an entry with symbolic key delivery-tag"
+                          + " and binary value of the delivery-tag of the message which caused the failure.")
+    @Test
+    public void transferUnsettledToUnknownDestinationWhenRejectedOutcomeSupportedBySource() throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
+
+            interaction.begin()
+                       .consumeResponse(Begin.class)
+
+                       .attachRole(Role.SENDER)
+                       .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL, Rejected.REJECTED_SYMBOL)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+
+                       .transferPayload(generateMessagePayloadToDestination("Unknown"))
+                       .transferDeliveryTag(_deliveryTag)
+                       .transfer()
+                       .consumeResponse();
+
+            Disposition disposition = interaction.getLatestResponse(Disposition.class);
+
+            assertThat(disposition.getSettled(), is(true));
+
+            DeliveryState dispositionState = disposition.getState();
+            assertThat(dispositionState, is(instanceOf(Rejected.class)));
+
+            Rejected rejected = (Rejected)dispositionState;
+            Error error = rejected.getError();
+            assertThat(error, is(notNullValue()));
+            assertThat(error.getCondition(), is(equalTo(AmqpError.NOT_FOUND)));
+            assertThat(error.getInfo(), is(notNullValue()));
+            assertThat(error.getInfo().get(DELIVERY_TAG), is(equalTo(_deliveryTag)));
+        }
+    }
+
+    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2.2 Routing Errors",
+            description = "It is possible that a message sent to a routing node has an address in the to field"
+                          + " of properties which, if used in the address field of target of an attach,"
+                          + " would result in an unsuccessful link establishment (for example,"
+                          + " if the address cannot be resolved to a node). In this case the routing node"
+                          + " MUST communicate the error back to the sender of the message."
+                          + " [...]"
+                          + " If the source of the link does not support the rejected outcome,"
+                          + " [...] then the routing node MUST detach the link with an error."
+                          + " [...] the info field of error MUST contain an entry with symbolic key delivery-tag"
+                          + " and binary value of the delivery-tag of the message which caused the failure.")
+    @Test
+    public void transferUnsettledToUnknownDestinationWhenRejectedOutcomeNotSupportedBySource() throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
+
+            interaction.begin()
+                       .consumeResponse(Begin.class)
+
+                       .attachRole(Role.SENDER)
+                       .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+
+                       .transferPayload(generateMessagePayloadToDestination("Unknown"))
+                       .transferDeliveryTag(_deliveryTag)
+                       .transfer();
+
+            Detach detach = interaction.consumeResponse().getLatestResponse(Detach.class);
+            Error error = detach.getError();
+            assertThat(error, is(notNullValue()));
+            assertThat(error.getCondition(), is(equalTo(AmqpError.NOT_FOUND)));
+            assertThat(error.getInfo(), is(notNullValue()));
+            assertThat(error.getInfo().get(DELIVERY_TAG), is(equalTo(_deliveryTag)));
+        }
+    }
+
+    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2. Sending A Message",
+            description = "Messages sent over links into a routing node will be"
+                          + " forwarded to the node referenced in the to field of properties of the message"
+                          + " just as if a direct link has been established to that node.")
+    @Test
+    public void transferPreSettledInTransactionToKnownDestination() throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
+            final UnsignedInteger linkHandle = UnsignedInteger.ONE;
+            final InteractionTransactionalState txnState = interaction.createTransactionalState(UnsignedInteger.ZERO);
+            interaction.begin()
+                       .consumeResponse(Begin.class)
+
+                       .txnAttachCoordinatorLink(txnState)
+                       .txnDeclare(txnState)
+
+                       .attachRole(Role.SENDER)
+                       .attachHandle(linkHandle)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+
+                       .transferHandle(linkHandle)
+                       .transferPayload(generateMessagePayloadToDestination(BrokerAdmin.TEST_QUEUE_NAME))
+                       .transferDeliveryTag(_deliveryTag)
+                       .transferTransactionalState(txnState.getCurrentTransactionId())
+                       .transferSettled(Boolean.TRUE)
+                       .transfer()
+
+                       .txnDischarge(txnState, false);
+
+            Object receivedMessage = Utils.receiveMessage(_brokerAddress, BrokerAdmin.TEST_QUEUE_NAME);
+            assertThat(receivedMessage, is(equalTo(TEST_MESSAGE_CONTENT)));
+        }
+    }
+
+    @Test
+    public void transferUnsettledInTransactionToKnownDestination() throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
+            final UnsignedInteger linkHandle = UnsignedInteger.ONE;
+            final InteractionTransactionalState txnState = interaction.createTransactionalState(UnsignedInteger.ZERO);
+            interaction.begin()
+                       .consumeResponse(Begin.class)
+
+                       .txnAttachCoordinatorLink(txnState)
+                       .txnDeclare(txnState)
+
+                       .attachRole(Role.SENDER)
+                       .attachHandle(linkHandle)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+
+                       .transferHandle(linkHandle)
+                       .transferPayload(generateMessagePayloadToDestination(BrokerAdmin.TEST_QUEUE_NAME))
+                       .transferDeliveryTag(_deliveryTag)
+                       .transferTransactionalState(txnState.getCurrentTransactionId())
+                       .transferSettled(Boolean.FALSE)
+                       .transfer();
+
+            Disposition disposition = interaction.consumeResponse().getLatestResponse(Disposition.class);
+
+            assertThat(disposition.getSettled(), is(true));
+
+            DeliveryState dispositionState = disposition.getState();
+            assertThat(dispositionState, is(instanceOf(TransactionalState.class)));
+
+            final TransactionalState receivedTxnState = (TransactionalState) dispositionState;
+            assertThat(receivedTxnState.getOutcome(), is(instanceOf(Accepted.class)));
+
+            interaction.txnDischarge(txnState, false);
+
+            Object receivedMessage = Utils.receiveMessage(_brokerAddress, BrokerAdmin.TEST_QUEUE_NAME);
+            assertThat(receivedMessage, is(equalTo(TEST_MESSAGE_CONTENT)));
+        }
+    }
+
+    @Test
+    public void transferUnsettledInTransactionToUnknownDestinationRejectedOutcomeSupportedBySource() throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
+            final UnsignedInteger linkHandle = UnsignedInteger.ONE;
+            final InteractionTransactionalState txnState = interaction.createTransactionalState(UnsignedInteger.ZERO);
+            interaction.begin()
+                       .consumeResponse(Begin.class)
+
+                       .txnAttachCoordinatorLink(txnState)
+                       .txnDeclare(txnState)
+
+                       .attachRole(Role.SENDER)
+                       .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL, Rejected.REJECTED_SYMBOL)
+                       .attachHandle(linkHandle)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+
+                       .transferHandle(linkHandle)
+                       .transferPayload(generateMessagePayloadToDestination("Unknown"))
+                       .transferDeliveryTag(_deliveryTag)
+                       .transferTransactionalState(txnState.getCurrentTransactionId())
+                       .transferSettled(Boolean.FALSE)
+                       .transfer();
+
+            Disposition disposition = interaction.consumeResponse().getLatestResponse(Disposition.class);
+
+            assertThat(disposition.getSettled(), is(true));
+
+            DeliveryState dispositionState = disposition.getState();
+            assertThat(dispositionState, is(instanceOf(TransactionalState.class)));
+
+            final TransactionalState receivedTxnState = (TransactionalState) dispositionState;
+            assertThat(receivedTxnState.getOutcome(), is(instanceOf(Rejected.class)));
+
+            final Error rejectedError = ((Rejected) receivedTxnState.getOutcome()).getError();
+            assertThat(rejectedError.getCondition(), is(equalTo(AmqpError.NOT_FOUND)));
+            assertThat(rejectedError.getInfo(), is(notNullValue()));
+            assertThat(rejectedError.getInfo().get(DELIVERY_TAG), is(equalTo(_deliveryTag)));
+
+            interaction.txnDischarge(txnState, false);
+        }
+    }
+
+    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2.2 Routing Errors",
+            description = "It is possible that a message sent to a routing node has an address in the to field"
+                          + " of properties which, if used in the address field of target of an attach,"
+                          + " would result in an unsuccessful link establishment (for example,"
+                          + " if the address cannot be resolved to a node). In this case the routing node"
+                          + " MUST communicate the error back to the sender of the message."
+                          + " [...]"
+                          + " <Not in spec yet>"
+                          + " AMQP-140"
+                          + " If a message cannot be routed to the destination implied in the \"to:\" field,"
+                          + " and the source does not allow for the rejected outcome"
+                          + " [...] when messages are being sent within a transaction and have been sent pre-settled."
+                          + " In this case the behaviour defined for transactions (of essentially marking"
+                          + " the transaction as rollback only) should take precedence. "
+                            + ""
+                          + " AMQP spec 4.3 Discharging a Transaction"
+                          + " If the coordinator is unable to complete the discharge, the coordinator MUST convey"
+                          + " the error to the controller as a transaction-error. If the source for the link to"
+                          + " the coordinator supports the rejected outcome, then the message MUST be rejected"
+                          + " with this outcome carrying the transaction-error.")
+    @Test
+    public void transferPreSettledInTransactionToUnknownDestinationWhenRejectOutcomeSupportedByTxController()
+            throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final UnsignedInteger linkHandle = UnsignedInteger.ONE;
+            final Interaction interaction =
+                    openInteractionWithAnonymousRelayCapability(transport);
+
+            final InteractionTransactionalState txnState = interaction.createTransactionalState(UnsignedInteger.ZERO);
+            interaction.begin()
+                       .consumeResponse(Begin.class)
+
+                       // attaching coordinator link with supported outcomes Accepted and Rejected
+                       .txnAttachCoordinatorLink(txnState)
+                       .txnDeclare(txnState)
+
+                       .attachRole(Role.SENDER)
+                       .attachHandle(linkHandle)
+                       .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL, Rejected.REJECTED_SYMBOL)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+
+                       .transferHandle(linkHandle)
+                       .transferPayload(generateMessagePayloadToDestination("Unknown"))
+                       .transferDeliveryTag(_deliveryTag)
+                       .transferTransactionalState(txnState.getCurrentTransactionId())
+                       .transferSettled(Boolean.TRUE)
+                       .transferDeliveryId(UnsignedInteger.valueOf(1))
+                       .transfer();
+
+            final Discharge discharge = new Discharge();
+            discharge.setTxnId(txnState.getCurrentTransactionId());
+            discharge.setFail(false);
+            interaction.transferHandle(txnState.getHandle())
+                       .transferDeliveryId(UnsignedInteger.valueOf(2))
+                       .transferSettled(Boolean.FALSE)
+                       .transferDeliveryTag(new Binary(("transaction-" + 2).getBytes(StandardCharsets.UTF_8)))
+                       .transferPayloadData(discharge).transfer();
+
+            Disposition dischargeTransactionDisposition = null;
+            Flow coordinatorFlow = null;
+            do
+            {
+                interaction.consumeResponse(Disposition.class, Flow.class);
+                Response<?> response = interaction.getLatestResponse();
+                if (response.getBody() instanceof Disposition)
+                {
+                    dischargeTransactionDisposition = (Disposition) response.getBody();
+                }
+                if (response.getBody() instanceof Flow)
+                {
+                    final Flow flowResponse = (Flow) response.getBody();
+                    if (flowResponse.getHandle().equals(txnState.getHandle()))
+                    {
+                        coordinatorFlow = flowResponse;
+                    }
+                }
+            } while (dischargeTransactionDisposition == null || coordinatorFlow == null);
+
+            assertThat(dischargeTransactionDisposition.getSettled(), is(equalTo(true)));
+            assertThat(dischargeTransactionDisposition.getState(), is(instanceOf(Rejected.class)));
+
+            Rejected rejected = (Rejected) dischargeTransactionDisposition.getState();
+            Error error = rejected.getError();
+
+            assertThat(error, is(notNullValue()));
+            assertThat(error.getCondition(), is(equalTo(TransactionError.TRANSACTION_ROLLBACK)));
+        }
+    }
+
+    @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2.2 Routing Errors",
+            description = "It is possible that a message sent to a routing node has an address in the to field"
+                          + " of properties which, if used in the address field of target of an attach,"
+                          + " would result in an unsuccessful link establishment (for example,"
+                          + " if the address cannot be resolved to a node). In this case the routing node"
+                          + " MUST communicate the error back to the sender of the message."
+                          + " [...]"
+                          + " <Not in spec yet>"
+                          + " AMQP-140"
+                          + " If a message cannot be routed to the destination implied in the \"to:\" field,"
+                          + " and the source does not allow for the rejected outcome"
+                          + " [...] when messages are being sent within a transaction and have been sent pre-settled."
+                          + " In this case the behaviour defined for transactions (of essentially marking"
+                          + " the transaction as rollback only) should take precedence. "
+                          + ""
+                          + " AMQP spec 4.3 Discharging a Transaction"
+                          + " If the coordinator is unable to complete the discharge, the coordinator MUST convey"
+                          + " the error to the controller as a transaction-error."
+                          + " [...]"
+                          + " If the source does not support the rejected outcome, the transactional resource MUST"
+                          + " detach the link to the coordinator, with the detach performative carrying"
+                          + " the transaction-error")
+    @Test
+    public void transferPreSettledInTransactionToUnknownDestinationWhenRejectOutcomeNotSupportedByTxController()
+            throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final UnsignedInteger linkHandle = UnsignedInteger.ONE;
+            final Interaction interaction =
+                    openInteractionWithAnonymousRelayCapability(transport);
+
+            final InteractionTransactionalState txnState = interaction.createTransactionalState(UnsignedInteger.ZERO);
+
+            interaction.begin()
+                       .consumeResponse(Begin.class)
+
+                       .attachRole(Role.SENDER)
+                       .attachName("testTransactionCoordinator-" + txnState.getHandle())
+                       .attachHandle(txnState.getHandle())
+                       .attachInitialDeliveryCount(UnsignedInteger.ZERO)
+                       .attachTarget(new Coordinator())
+                       .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+                       .txnDeclare(txnState)
+
+                       .attachRole(Role.SENDER)
+                       .attachHandle(linkHandle)
+                       .attachTarget(new Target())
+                       .attachName("link-" + linkHandle)
+                       .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL, Rejected.REJECTED_SYMBOL)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+
+                       .transferHandle(linkHandle)
+                       .transferPayload(generateMessagePayloadToDestination("Unknown"))
+                       .transferDeliveryTag(_deliveryTag)
+                       .transferTransactionalState(txnState.getCurrentTransactionId())
+                       .transferSettled(Boolean.TRUE)
+                       .transfer();
+
+            final Discharge discharge = new Discharge();
+            discharge.setTxnId(txnState.getCurrentTransactionId());
+            discharge.setFail(false);
+
+            interaction.transferHandle(txnState.getHandle())
+                       .transferSettled(Boolean.FALSE)
+                       .transferDeliveryId(UnsignedInteger.valueOf(4))
+                       .transferDeliveryTag(new Binary(("transaction-" + 4).getBytes(StandardCharsets.UTF_8)))
+                       .transferPayloadData(discharge).transfer();
+
+            Detach transactionCoordinatorDetach = interaction.consumeResponse().getLatestResponse(Detach.class);
+            Error transactionCoordinatorDetachError = transactionCoordinatorDetach.getError();
+            assertThat(transactionCoordinatorDetachError, is(notNullValue()));
+            assertThat(transactionCoordinatorDetachError.getCondition(), is(equalTo(TransactionError.TRANSACTION_ROLLBACK)));
+        }
+    }
+
+
+    private Interaction openInteractionWithAnonymousRelayCapability(final FrameTransport transport) throws Exception
+    {
+        final Interaction interaction = transport.newInteraction();
+        interaction.negotiateProtocol().consumeResponse()
+                   .openDesiredCapabilities(ANONYMOUS_RELAY)
+                   .open().consumeResponse(Open.class);
+
+        Open open = interaction.getLatestResponse(Open.class);
+        assumeThat(Arrays.asList(open.getOfferedCapabilities()), hasItem(ANONYMOUS_RELAY));
+        return interaction;
+    }
+
+    private QpidByteBuffer generateMessagePayloadToDestination(final String destinationName)
+    {
+        MessageEncoder messageEncoder = new MessageEncoder();
+        final Properties properties = new Properties();
+        properties.setTo(destinationName);
+        messageEncoder.setProperties(properties);
+        messageEncoder.addData(TEST_MESSAGE_CONTENT);
+        return messageEncoder.getPayload();
+    }
+}


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


[07/11] qpid-broker-j git commit: QPID-8062: [Broker-J][AMQP 1.0] Add more tests

Posted by or...@apache.org.
QPID-8062: [Broker-J][AMQP 1.0] Add more tests

(cherry picked from commit 8cf9f1d31aef411f0fd20055e34d37de7c50098b)


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/1d8d0bcb
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/1d8d0bcb
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/1d8d0bcb

Branch: refs/heads/7.0.x
Commit: 1d8d0bcba435405fde632ff1d869b30e2f0529a0
Parents: 42807ef
Author: Alex Rudyy <or...@apache.org>
Authored: Tue Jan 23 17:42:04 2018 +0000
Committer: Alex Rudyy <or...@apache.org>
Committed: Mon Jan 29 13:58:19 2018 +0000

----------------------------------------------------------------------
 .../AnonymousTerminusTest.java                  | 105 +++++++++++++++----
 1 file changed, 85 insertions(+), 20 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/1d8d0bcb/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousterminus/AnonymousTerminusTest.java
----------------------------------------------------------------------
diff --git a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousterminus/AnonymousTerminusTest.java b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousterminus/AnonymousTerminusTest.java
index d837e38..1878950 100644
--- a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousterminus/AnonymousTerminusTest.java
+++ b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousterminus/AnonymousTerminusTest.java
@@ -37,6 +37,7 @@ import org.junit.Before;
 import org.junit.Test;
 
 import org.apache.qpid.server.bytebuffer.QpidByteBuffer;
+import org.apache.qpid.server.protocol.v1_0.SequenceNumber;
 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.Symbol;
@@ -319,7 +320,7 @@ public class AnonymousTerminusTest extends BrokerAdminUsingTestBase
     }
 
     @Test
-    public void transferUnsettledInTransactionToUnknownDestinationRejectedOutcomeSupportedBySource() throws Exception
+    public void transferUnsettledInTransactionToUnknownDestinationWhenRejectedOutcomeSupportedBySource() throws Exception
     {
         try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
         {
@@ -364,6 +365,65 @@ public class AnonymousTerminusTest extends BrokerAdminUsingTestBase
         }
     }
 
+    @Test
+    public void transferUnsettledInTransactionToUnknownDestinationWhenRejectedOutcomeNotSupportedBySource() throws Exception
+    {
+        try (FrameTransport transport = new FrameTransport(_brokerAddress).connect())
+        {
+            final Interaction interaction = openInteractionWithAnonymousRelayCapability(transport);
+            final UnsignedInteger linkHandle = UnsignedInteger.ONE;
+            final InteractionTransactionalState txnState = interaction.createTransactionalState(UnsignedInteger.ZERO);
+            interaction.begin()
+                       .consumeResponse(Begin.class)
+
+                       .txnAttachCoordinatorLink(txnState)
+                       .txnDeclare(txnState)
+
+                       .attachRole(Role.SENDER)
+                       .attachSourceOutcomes(Accepted.ACCEPTED_SYMBOL)
+                       .attachHandle(linkHandle)
+                       .attach().consumeResponse(Attach.class)
+                       .consumeResponse(Flow.class)
+
+                       .transferHandle(linkHandle)
+                       .transferPayload(generateMessagePayloadToDestination("Unknown"))
+                       .transferDeliveryId(UnsignedInteger.valueOf(1))
+                       .transferDeliveryTag(_deliveryTag)
+                       .transferTransactionalState(txnState.getCurrentTransactionId())
+                       .transferSettled(Boolean.FALSE)
+                       .transfer();
+
+            Detach senderLinkDetach = interaction.consumeResponse().getLatestResponse(Detach.class);
+            Error senderLinkDetachError = senderLinkDetach.getError();
+            assertThat(senderLinkDetachError, is(notNullValue()));
+            assertThat(senderLinkDetachError.getCondition(), is(equalTo(AmqpError.NOT_FOUND)));
+            assertThat(senderLinkDetachError.getInfo(), is(notNullValue()));
+            assertThat(senderLinkDetachError.getInfo().get(DELIVERY_TAG), is(equalTo(_deliveryTag)));
+
+            final Discharge discharge = new Discharge();
+            discharge.setTxnId(txnState.getCurrentTransactionId());
+            discharge.setFail(false);
+
+            interaction.transferHandle(txnState.getHandle())
+                       .transferSettled(Boolean.FALSE)
+                       .transferDeliveryId(UnsignedInteger.valueOf(2))
+                       .transferDeliveryTag(new Binary(("transaction-" + 2).getBytes(StandardCharsets.UTF_8)))
+                       .transferPayloadData(discharge).transfer();
+
+            Disposition dischargeTransactionDisposition =
+                    getDispositionForDeliveryId(interaction, UnsignedInteger.valueOf(2));
+
+            assertThat(dischargeTransactionDisposition.getSettled(), is(equalTo(true)));
+            assertThat(dischargeTransactionDisposition.getState(), is(instanceOf(Rejected.class)));
+
+            Rejected rejected = (Rejected) dischargeTransactionDisposition.getState();
+            Error error = rejected.getError();
+
+            assertThat(error, is(notNullValue()));
+            assertThat(error.getCondition(), is(equalTo(TransactionError.TRANSACTION_ROLLBACK)));
+        }
+    }
+
     @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2.2 Routing Errors",
             description = "It is possible that a message sent to a routing node has an address in the to field"
                           + " of properties which, if used in the address field of target of an attach,"
@@ -425,25 +485,8 @@ public class AnonymousTerminusTest extends BrokerAdminUsingTestBase
                        .transferDeliveryTag(new Binary(("transaction-" + 2).getBytes(StandardCharsets.UTF_8)))
                        .transferPayloadData(discharge).transfer();
 
-            Disposition dischargeTransactionDisposition = null;
-            Flow coordinatorFlow = null;
-            do
-            {
-                interaction.consumeResponse(Disposition.class, Flow.class);
-                Response<?> response = interaction.getLatestResponse();
-                if (response.getBody() instanceof Disposition)
-                {
-                    dischargeTransactionDisposition = (Disposition) response.getBody();
-                }
-                if (response.getBody() instanceof Flow)
-                {
-                    final Flow flowResponse = (Flow) response.getBody();
-                    if (flowResponse.getHandle().equals(txnState.getHandle()))
-                    {
-                        coordinatorFlow = flowResponse;
-                    }
-                }
-            } while (dischargeTransactionDisposition == null || coordinatorFlow == null);
+            Disposition dischargeTransactionDisposition =
+                    getDispositionForDeliveryId(interaction, UnsignedInteger.valueOf(2));
 
             assertThat(dischargeTransactionDisposition.getSettled(), is(equalTo(true)));
             assertThat(dischargeTransactionDisposition.getState(), is(instanceOf(Rejected.class)));
@@ -535,6 +578,28 @@ public class AnonymousTerminusTest extends BrokerAdminUsingTestBase
         }
     }
 
+    private Disposition getDispositionForDeliveryId(final Interaction interaction,
+                                                    final UnsignedInteger deliveryId) throws Exception
+    {
+        Disposition dischargeTransactionDisposition = null;
+
+        SequenceNumber id = new SequenceNumber(deliveryId.intValue());
+        do
+        {
+            Response<?> response = interaction.consumeResponse(Disposition.class, Flow.class).getLatestResponse();
+            if (response.getBody() instanceof Disposition)
+            {
+                Disposition disposition = (Disposition) response.getBody();
+                UnsignedInteger first = disposition.getFirst();
+                UnsignedInteger last = disposition.getLast() == null ? disposition.getFirst() : disposition.getLast();
+                if (new SequenceNumber(first.intValue()).compareTo(id) >= 0 && new SequenceNumber(last.intValue()).compareTo(id) <=0)
+                {
+                    dischargeTransactionDisposition = disposition;
+                }
+            }
+        } while (dischargeTransactionDisposition == null);
+        return dischargeTransactionDisposition;
+    }
 
     private Interaction openInteractionWithAnonymousRelayCapability(final FrameTransport transport) throws Exception
     {


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


[09/11] qpid-broker-j git commit: QPID-8032 : [Broker-J][AMQP 1.0] Use asynchronous auto commit transaction for non-transactional message dequeuing

Posted by or...@apache.org.
QPID-8032 : [Broker-J][AMQP 1.0] Use asynchronous auto commit transaction for non-transactional message dequeuing

(cherry picked from commit a1ed9978f756268fc86de8af02e5d7fad13a65a2)


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/f608040e
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/f608040e
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/f608040e

Branch: refs/heads/7.0.x
Commit: f608040edb5089a3813f3cb116f59803cef4d171
Parents: 02cf0ff
Author: Alex Rudyy <or...@apache.org>
Authored: Tue Jan 23 14:04:11 2018 +0000
Committer: Alex Rudyy <or...@apache.org>
Committed: Mon Jan 29 14:02:49 2018 +0000

----------------------------------------------------------------------
 .../protocol/v1_0/ConsumerTarget_1_0.java       |  3 +--
 .../protocol/v1_0/SendingLinkEndpoint.java      | 25 ++++++++++++++++++++
 .../v1_0/StandardReceivingLinkEndpoint.java     | 10 ++++----
 3 files changed, 31 insertions(+), 7 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/f608040e/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 fec4c6d..4798815 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
@@ -58,7 +58,6 @@ import org.apache.qpid.server.protocol.v1_0.type.transport.Transfer;
 import org.apache.qpid.server.store.TransactionLogResource;
 import org.apache.qpid.server.transport.AMQPConnection;
 import org.apache.qpid.server.transport.ProtocolEngine;
-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.ServerScopedRuntimeException;
@@ -427,7 +426,7 @@ class ConsumerTarget_1_0 extends AbstractConsumerTarget<ConsumerTarget_1_0>
             else if (state instanceof Outcome)
             {
                 outcome = (Outcome) state;
-                txn = new AutoCommitTransaction(getSession().getConnection().getAddressSpace().getMessageStore());
+                txn = _linkEndpoint.getAsyncAutoCommitTransaction();
             }
             else
             {

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/f608040e/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLinkEndpoint.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLinkEndpoint.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLinkEndpoint.java
index ee1f800..4ab25a7 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLinkEndpoint.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/SendingLinkEndpoint.java
@@ -31,8 +31,10 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
 import java.util.regex.Pattern;
 
+import com.google.common.util.concurrent.ListenableFuture;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -76,6 +78,8 @@ import org.apache.qpid.server.protocol.v1_0.type.transport.Error;
 import org.apache.qpid.server.protocol.v1_0.type.transport.Flow;
 import org.apache.qpid.server.protocol.v1_0.type.transport.Role;
 import org.apache.qpid.server.protocol.v1_0.type.transport.Transfer;
+import org.apache.qpid.server.txn.AsyncAutoCommitTransaction;
+import org.apache.qpid.server.txn.AsyncCommand;
 import org.apache.qpid.server.txn.AutoCommitTransaction;
 import org.apache.qpid.server.txn.ServerTransaction;
 import org.apache.qpid.server.util.Action;
@@ -83,6 +87,7 @@ import org.apache.qpid.server.util.ConnectionScopedRuntimeException;
 import org.apache.qpid.server.virtualhost.QueueManagingVirtualHost;
 
 public class SendingLinkEndpoint extends AbstractLinkEndpoint<Source, Target>
+        implements AsyncAutoCommitTransaction.FutureRecorder
 {
     private static final Logger LOGGER = LoggerFactory.getLogger(SendingLinkEndpoint.class);
     private static final Symbol PRIORITY = Symbol.valueOf("priority");
@@ -91,6 +96,8 @@ public class SendingLinkEndpoint extends AbstractLinkEndpoint<Source, Target>
     private final List<Binary> _resumeAcceptedTransfers = new ArrayList<>();
     private final List<MessageInstance> _resumeFullTransfers = new ArrayList<>();
     private final Map<Binary, OutgoingDelivery> _unsettled = new ConcurrentHashMap<>();
+    private final AsyncAutoCommitTransaction _asyncAutoCommitTransaction;
+    private final java.util.Queue<AsyncCommand> _unfinishedCommandsQueue = new ConcurrentLinkedQueue<>();
 
     // TODO: QPID-7845 : remove after implementation of link resuming
     private final Action<Session_1_0> _cleanUpUnsettledDeliveryTask = object -> cleanUpUnsettledDeliveries();
@@ -110,6 +117,8 @@ public class SendingLinkEndpoint extends AbstractLinkEndpoint<Source, Target>
         setDeliveryCount(new SequenceNumber(0));
         setAvailable(UnsignedInteger.valueOf(0));
         setCapabilities(Collections.singletonList(AMQPConnection_1_0.SHARED_SUBSCRIPTIONS));
+        _asyncAutoCommitTransaction =
+                new AsyncAutoCommitTransaction(getSession().getConnection().getAddressSpace().getMessageStore(), this);
     }
 
     @Override
@@ -602,6 +611,11 @@ public class SendingLinkEndpoint extends AbstractLinkEndpoint<Source, Target>
         return session == null ? null : session.getTransaction(transactionId);
     }
 
+    AsyncAutoCommitTransaction getAsyncAutoCommitTransaction()
+    {
+        return _asyncAutoCommitTransaction;
+    }
+
     public boolean hasCreditToSend()
     {
         UnsignedInteger linkCredit = getLinkCredit();
@@ -909,6 +923,17 @@ public class SendingLinkEndpoint extends AbstractLinkEndpoint<Source, Target>
     @Override
     public void receiveComplete()
     {
+        AsyncCommand cmd;
+        while((cmd = _unfinishedCommandsQueue.poll()) != null)
+        {
+            cmd.complete();
+        }
+    }
+
+    @Override
+    public void recordFuture(final ListenableFuture<Void> future, final ServerTransaction.Action action)
+    {
+        _unfinishedCommandsQueue.add(new AsyncCommand(future, action));
     }
 
     private static class OutgoingDelivery

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/f608040e/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 2d2b206..91ab75b 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
@@ -28,11 +28,11 @@ import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.LinkedHashSet;
-import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
+import java.util.concurrent.ConcurrentLinkedQueue;
 
 import com.google.common.util.concurrent.ListenableFuture;
 import org.slf4j.Logger;
@@ -81,13 +81,13 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
     private static final Accepted ACCEPTED = new Accepted();
     private static final String LINK = "link";
 
+    private final java.util.Queue<AsyncCommand> _unfinishedCommandsQueue = new ConcurrentLinkedQueue<>();
+    private final Set<PendingDispositionHolder> _pendingDispositions =
+            Collections.synchronizedSet(new LinkedHashSet<>());
+
     private volatile ReceivingDestination _receivingDestination;
     private volatile boolean _rejectedOutcomeSupportedBySource;
 
-    private final LinkedList<AsyncCommand> _unfinishedCommandsQueue = new LinkedList<>();
-
-    private final Set<PendingDispositionHolder> _pendingDispositions = new LinkedHashSet<>();
-
     private final PublishingLink _publishingLink = new PublishingLink()
     {
         @Override


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


[05/11] qpid-broker-j git commit: QPID-8062: [Broker-J][AMQP 1.0] Move responsibility to create outcome for received message from ReceivingDestination into a caller of ReceivingDestination#send()

Posted by or...@apache.org.
QPID-8062: [Broker-J][AMQP 1.0] Move responsibility to create outcome for received message from ReceivingDestination into a caller of ReceivingDestination#send()

(cherry picked from commit b5a0d32806ed5d07853adc287537d53cd3a7791f)


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/2495d194
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/2495d194
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/2495d194

Branch: refs/heads/7.0.x
Commit: 2495d194989110d383df7d2a44a92e90cb8c48bf
Parents: b4e746a
Author: Alex Rudyy <or...@apache.org>
Authored: Thu Jan 18 12:03:42 2018 +0000
Committer: Alex Rudyy <or...@apache.org>
Committed: Mon Jan 29 13:57:40 2018 +0000

----------------------------------------------------------------------
 .../v1_0/AnonymousRelayDestination.java         | 62 +++-----------------
 .../protocol/v1_0/NodeReceivingDestination.java | 62 +++-----------------
 .../protocol/v1_0/ReceivingDestination.java     | 15 +----
 .../v1_0/StandardReceivingLinkEndpoint.java     | 40 ++++++++++---
 .../v1_0/UnroutableMessageException.java        | 39 ++++++++++++
 .../anonymousrelay/AnonymousRelayTest.java      | 40 +++++++++++--
 6 files changed, 126 insertions(+), 132 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/2495d194/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AnonymousRelayDestination.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AnonymousRelayDestination.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AnonymousRelayDestination.java
index 806469b..00c0588 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AnonymousRelayDestination.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/AnonymousRelayDestination.java
@@ -22,7 +22,6 @@ package org.apache.qpid.server.protocol.v1_0;/*
 import static org.apache.qpid.server.protocol.v1_0.Session_1_0.DELAYED_DELIVERY;
 
 import java.util.Arrays;
-import java.util.Collections;
 
 import org.apache.qpid.server.logging.EventLogger;
 import org.apache.qpid.server.logging.messages.ExchangeMessages;
@@ -30,17 +29,10 @@ import org.apache.qpid.server.message.MessageDestination;
 import org.apache.qpid.server.message.ServerMessage;
 import org.apache.qpid.server.model.DestinationAddress;
 import org.apache.qpid.server.model.NamedAddressSpace;
-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.Outcome;
 import org.apache.qpid.server.protocol.v1_0.type.Symbol;
-import org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted;
-import org.apache.qpid.server.protocol.v1_0.type.messaging.Rejected;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.Target;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
-import org.apache.qpid.server.protocol.v1_0.type.transport.Error;
 import org.apache.qpid.server.security.SecurityToken;
-import org.apache.qpid.server.txn.LocalTransaction;
 import org.apache.qpid.server.txn.ServerTransaction;
 
 public class AnonymousRelayDestination implements ReceivingDestination
@@ -68,18 +60,9 @@ public class AnonymousRelayDestination implements ReceivingDestination
     }
 
     @Override
-    public Outcome[] getOutcomes()
-    {
-        return new Outcome[0];
-    }
-
-    @Override
-    public Outcome send(final ServerMessage<?> message,
-                        final ServerTransaction txn,
-                        final SecurityToken securityToken,
-                        final boolean rejectedOutcomeSupportedBySource,
-                        final boolean deliverySettled,
-                        final Binary deliveryTag) throws AmqpErrorException
+    public void send(final ServerMessage<?> message,
+                     final ServerTransaction txn,
+                     final SecurityToken securityToken) throws UnroutableMessageException
     {
         final ReceivingDestination destination;
         final String routingAddress = message.getTo();
@@ -98,53 +81,24 @@ public class AnonymousRelayDestination implements ReceivingDestination
             destination = null;
         }
 
-        final Outcome outcome;
         if (destination == null)
         {
             if (_discardUnroutable)
             {
                 _eventLogger.message(ExchangeMessages.DISCARDMSG("", routingAddress));
-                outcome = new Accepted();
             }
             else
             {
-                final Error notFoundError = new Error(AmqpError.NOT_FOUND,
-                                                      String.format("Unknown destination '%s'", routingAddress));
-                notFoundError.setInfo(Collections.singletonMap(DELIVERY_TAG, deliveryTag));
-
-                // If the source of the link does not support the rejected outcome,
-                // or the message has already been settled by the sender,
-                // then the routing node MUST detach the link with an error.
-                // AMQP-140: When pre-settled messages are being sent within a transaction,
-                // then the behaviour defined for transactions should take precedence
-                // (essentially marking the transaction as rollback only).
-                if (!rejectedOutcomeSupportedBySource || (deliverySettled && !(txn instanceof LocalTransaction)))
-                {
-                    throw new AmqpErrorException(notFoundError);
-                }
-                else
-                {
-                    if (deliverySettled && txn instanceof LocalTransaction)
-                    {
-                        ((LocalTransaction) txn).setRollbackOnly();
-                    }
-
-                    Rejected rejected = new Rejected();
-                    rejected.setError(notFoundError);
-                    outcome = rejected;
-                }
+                throw new UnroutableMessageException(AmqpError.NOT_FOUND,
+                                                     String.format("Unknown destination '%s'", routingAddress));
             }
         }
         else
         {
-            outcome = destination.send(message,
-                                       txn,
-                                       securityToken,
-                                       rejectedOutcomeSupportedBySource,
-                                       deliverySettled,
-                                       deliveryTag);
+            destination.send(message,
+                             txn,
+                             securityToken);
         }
-        return outcome;
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/2495d194/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/NodeReceivingDestination.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/NodeReceivingDestination.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/NodeReceivingDestination.java
index 6d5859f..ee3839c 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/NodeReceivingDestination.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/NodeReceivingDestination.java
@@ -34,25 +34,15 @@ import org.apache.qpid.server.message.RoutingResult;
 import org.apache.qpid.server.message.ServerMessage;
 import org.apache.qpid.server.model.DestinationAddress;
 import org.apache.qpid.server.model.Exchange;
-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.Outcome;
 import org.apache.qpid.server.protocol.v1_0.type.Symbol;
-import org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted;
-import org.apache.qpid.server.protocol.v1_0.type.messaging.Rejected;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.TerminusDurability;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.TerminusExpiryPolicy;
 import org.apache.qpid.server.protocol.v1_0.type.transport.AmqpError;
-import org.apache.qpid.server.protocol.v1_0.type.transport.Error;
 import org.apache.qpid.server.security.SecurityToken;
-import org.apache.qpid.server.txn.LocalTransaction;
 import org.apache.qpid.server.txn.ServerTransaction;
 
 public class NodeReceivingDestination implements ReceivingDestination
 {
-    private static final Accepted ACCEPTED = new Accepted();
-    private static final Rejected REJECTED = new Rejected();
-    private static final Outcome[] OUTCOMES = { ACCEPTED, REJECTED};
     private final boolean _discardUnroutable;
     private final EventLogger _eventLogger;
 
@@ -90,18 +80,9 @@ public class NodeReceivingDestination implements ReceivingDestination
     }
 
     @Override
-    public Outcome[] getOutcomes()
-    {
-        return OUTCOMES;
-    }
-
-    @Override
-    public Outcome send(final ServerMessage<?> message,
-                        final ServerTransaction txn,
-                        final SecurityToken securityToken,
-                        final boolean rejectedOutcomeSupportedBySource,
-                        final boolean deliverySettled,
-                        final Binary deliveryTag) throws AmqpErrorException
+    public void send(final ServerMessage<?> message,
+                     final ServerTransaction txn,
+                     final SecurityToken securityToken) throws UnroutableMessageException
     {
         final String routingAddress = "".equals(_routingAddress) ? getRoutingAddress(message) : _routingAddress;
         _destination.authorisePublish(securityToken, Collections.singletonMap("routingKey", routingAddress));
@@ -136,10 +117,10 @@ public class NodeReceivingDestination implements ReceivingDestination
         {
             if (!_discardUnroutable)
             {
-                final Error error;
+                final String errorMessage;
+                final AmqpError errorCode;
                 if (result.isRejected())
                 {
-                    AmqpError errorCode;
                     if (result.containsReject(RejectType.LIMIT_EXCEEDED))
                     {
                         errorCode = AmqpError.RESOURCE_LIMIT_EXCEEDED;
@@ -152,37 +133,20 @@ public class NodeReceivingDestination implements ReceivingDestination
                     {
                         errorCode = AmqpError.ILLEGAL_STATE;
                     }
-                    error = new Error(errorCode, result.getRejectReason());
-                }
-                else
-                {
-                    error = new Error(AmqpError.NOT_FOUND,
-                                      String.format("Unknown destination '%s'", routingAddress));
-                }
-                error.setInfo(Collections.singletonMap(DELIVERY_TAG, deliveryTag));
-
-                if (!rejectedOutcomeSupportedBySource || (deliverySettled && !(txn instanceof LocalTransaction)))
-                {
-                    throw new AmqpErrorException(error);
+                    errorMessage = result.getRejectReason();
                 }
                 else
                 {
-                    if (deliverySettled && txn instanceof LocalTransaction)
-                    {
-                        ((LocalTransaction) txn).setRollbackOnly();
-                    }
-
-                    Rejected rejected = new Rejected();
-                    rejected.setError(error);
-                    return rejected;
+                    errorCode = AmqpError.NOT_FOUND;
+                    errorMessage = String.format("Unknown destination '%s'", routingAddress);
                 }
+                throw new UnroutableMessageException(errorCode, errorMessage);
             }
             else
             {
                 _eventLogger.message(ExchangeMessages.DISCARDMSG(_destination.getName(), routingAddress));
             }
         }
-        return ACCEPTED;
     }
 
     private String getRoutingAddress(final ServerMessage<?> message)
@@ -199,14 +163,6 @@ public class NodeReceivingDestination implements ReceivingDestination
         return initialRoutingAddress;
     }
 
-    private Outcome createdRejectedOutcome(AmqpError errorCode, String errorMessage)
-    {
-        Rejected rejected = new Rejected();
-        final Error notFoundError = new Error(errorCode, errorMessage);
-        rejected.setError(notFoundError);
-        return rejected;
-    }
-
     @Override
     public String getAddress()
     {

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/2495d194/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingDestination.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingDestination.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingDestination.java
index 5abd825..5c746be 100644
--- a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingDestination.java
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/ReceivingDestination.java
@@ -22,29 +22,20 @@ package org.apache.qpid.server.protocol.v1_0;
 
 import org.apache.qpid.server.message.MessageDestination;
 import org.apache.qpid.server.message.ServerMessage;
-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.Outcome;
 import org.apache.qpid.server.protocol.v1_0.type.Symbol;
 import org.apache.qpid.server.security.SecurityToken;
 import org.apache.qpid.server.txn.ServerTransaction;
 
 public interface ReceivingDestination
 {
-    Symbol DELIVERY_TAG = Symbol.valueOf("delivery-tag");
     Symbol REJECT_UNROUTABLE = Symbol.valueOf("REJECT_UNROUTABLE");
     Symbol DISCARD_UNROUTABLE = Symbol.valueOf("DISCARD_UNROUTABLE");
 
     Symbol[] getCapabilities();
 
-    Outcome[] getOutcomes();
-
-    Outcome send(final ServerMessage<?> message,
-                 final ServerTransaction txn,
-                 final SecurityToken securityToken,
-                 final boolean rejectedOutcomeSupportedBySource,
-                 final boolean deliverySettled,
-                 final Binary deliveryTag) throws AmqpErrorException;
+    void send(final ServerMessage<?> message,
+              final ServerTransaction txn,
+              final SecurityToken securityToken) throws UnroutableMessageException;
 
     int getCredit();
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/2495d194/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 a565f7f..aebff2e 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
@@ -54,6 +54,7 @@ import org.apache.qpid.server.protocol.v1_0.type.DeliveryState;
 import org.apache.qpid.server.protocol.v1_0.type.Outcome;
 import org.apache.qpid.server.protocol.v1_0.type.Symbol;
 import org.apache.qpid.server.protocol.v1_0.type.UnsignedInteger;
+import org.apache.qpid.server.protocol.v1_0.type.messaging.Accepted;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.Rejected;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.Source;
 import org.apache.qpid.server.protocol.v1_0.type.messaging.Target;
@@ -77,6 +78,8 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
         implements AsyncAutoCommitTransaction.FutureRecorder
 {
     private static final Logger LOGGER = LoggerFactory.getLogger(StandardReceivingLinkEndpoint.class);
+    private static final Symbol DELIVERY_TAG = Symbol.valueOf("delivery-tag");
+    private static final Accepted ACCEPTED = new Accepted();
     private static final String LINK = "link";
 
     private volatile ReceivingDestination _receivingDestination;
@@ -267,16 +270,37 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
                     {
                         try
                         {
-                            outcome = getReceivingDestination().send(serverMessage,
-                                                                     transaction,
-                                                                     session.getSecurityToken(),
-                                                                     _rejectedOutcomeSupportedBySource,
-                                                                     delivery.isSettled(),
-                                                                     delivery.getDeliveryTag());
+                            getReceivingDestination().send(serverMessage,
+                                                           transaction,
+                                                           session.getSecurityToken());
+                            outcome = ACCEPTED;
                         }
-                        catch (AmqpErrorException e)
+                        catch (UnroutableMessageException e)
                         {
-                            return e.getError();
+                            final Error error = new Error();
+                            error.setCondition(e.getErrorCondition());
+                            error.setDescription(e.getMessage());
+                            String targetAddress = getTarget().getAddress();
+                            if (targetAddress == null || "".equals(targetAddress.trim()))
+                            {
+                                error.setInfo(Collections.singletonMap(DELIVERY_TAG, delivery.getDeliveryTag()));
+                            }
+                            if (!_rejectedOutcomeSupportedBySource ||
+                                (delivery.isSettled() && !(transaction instanceof LocalTransaction)))
+                            {
+                                return error;
+                            }
+                            else
+                            {
+                                if (delivery.isSettled() && transaction instanceof LocalTransaction)
+                                {
+                                    ((LocalTransaction) transaction).setRollbackOnly();
+                                }
+
+                                Rejected rejected = new Rejected();
+                                rejected.setError(error);
+                                outcome = rejected;
+                            }
                         }
                     }
 

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/2495d194/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/UnroutableMessageException.java
----------------------------------------------------------------------
diff --git a/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/UnroutableMessageException.java b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/UnroutableMessageException.java
new file mode 100644
index 0000000..378b86c
--- /dev/null
+++ b/broker-plugins/amqp-1-0-protocol/src/main/java/org/apache/qpid/server/protocol/v1_0/UnroutableMessageException.java
@@ -0,0 +1,39 @@
+/*
+ *
+ * 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.protocol.v1_0;
+
+import org.apache.qpid.server.protocol.v1_0.type.ErrorCondition;
+
+public class UnroutableMessageException extends Exception
+{
+    private final ErrorCondition _errorCondition;
+
+    public UnroutableMessageException(final ErrorCondition errorCondition, final String message)
+    {
+        super(message);
+        _errorCondition = errorCondition;
+    }
+
+    public ErrorCondition getErrorCondition()
+    {
+        return _errorCondition;
+    }
+}

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/2495d194/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousrelay/AnonymousRelayTest.java
----------------------------------------------------------------------
diff --git a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousrelay/AnonymousRelayTest.java b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousrelay/AnonymousRelayTest.java
index c3c69d1..4fc18dd 100644
--- a/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousrelay/AnonymousRelayTest.java
+++ b/systests/protocol-tests-amqp-1-0/src/test/java/org/apache/qpid/tests/protocol/v1_0/extensions/anonymousrelay/AnonymousRelayTest.java
@@ -70,8 +70,10 @@ import org.apache.qpid.tests.utils.BrokerAdminUsingTestBase;
 public class AnonymousRelayTest extends BrokerAdminUsingTestBase
 {
     private static final Symbol ANONYMOUS_RELAY = Symbol.valueOf("ANONYMOUS-RELAY");
+    private static final Symbol DELIVERY_TAG = Symbol.valueOf("delivery-tag");
     private static final String TEST_MESSAGE_CONTENT = "test";
     private InetSocketAddress _brokerAddress;
+    private Binary _deliveryTag;
 
     @Before
     public void setUp()
@@ -79,6 +81,7 @@ public class AnonymousRelayTest extends BrokerAdminUsingTestBase
         final BrokerAdmin brokerAdmin = getBrokerAdmin();
         brokerAdmin.createQueue(BrokerAdmin.TEST_QUEUE_NAME);
         _brokerAddress = brokerAdmin.getBrokerAddress(BrokerAdmin.PortType.ANONYMOUS_AMQP);
+        _deliveryTag = new Binary("testTag".getBytes(StandardCharsets.UTF_8));
     }
 
     @SpecificationTest(section = "Using the Anonymous Terminus for Message Routing. 2.2. Sending A Message",
@@ -101,6 +104,7 @@ public class AnonymousRelayTest extends BrokerAdminUsingTestBase
 
                        .transferPayload(generateMessagePayloadToDestination(BrokerAdmin.TEST_QUEUE_NAME))
                        .transferSettled(Boolean.TRUE)
+                       .transferDeliveryTag(_deliveryTag)
                        .transfer()
                        .sync();
 
@@ -116,7 +120,9 @@ public class AnonymousRelayTest extends BrokerAdminUsingTestBase
                           + " if the address cannot be resolved to a node). In this case the routing node"
                           + " MUST communicate the error back to the sender of the message."
                           + " [...] the message has already been settled by the sender,"
-                          + " then the routing node MUST detach the link with an error.")
+                          + " then the routing node MUST detach the link with an error."
+                          + " [...] the info field of error MUST contain an entry with symbolic key delivery-tag"
+                          + " and binary value of the delivery-tag of the message which caused the failure.")
     @Test
     public void transferPreSettledToUnknownDestination() throws Exception
     {
@@ -133,12 +139,15 @@ public class AnonymousRelayTest extends BrokerAdminUsingTestBase
 
                        .transferPayload(generateMessagePayloadToDestination("Unknown"))
                        .transferSettled(Boolean.TRUE)
+                       .transferDeliveryTag(_deliveryTag)
                        .transfer();
 
             Detach detach = interaction.consumeResponse().getLatestResponse(Detach.class);
             Error error = detach.getError();
             assertThat(error, is(notNullValue()));
             assertThat(error.getCondition(), is(equalTo(AmqpError.NOT_FOUND)));
+            assertThat(error.getInfo(), is(notNullValue()));
+            assertThat(error.getInfo().get(DELIVERY_TAG), is(equalTo(_deliveryTag)));
         }
     }
 
@@ -150,7 +159,9 @@ public class AnonymousRelayTest extends BrokerAdminUsingTestBase
                           + " MUST communicate the error back to the sender of the message."
                           + " If the source of the link supports the rejected outcome,"
                           + " and the message has not already been settled by the sender, then the routing node"
-                          + " MUST reject the message.")
+                          + " MUST reject the message."
+                          + " [...] the info field of error MUST contain an entry with symbolic key delivery-tag"
+                          + " and binary value of the delivery-tag of the message which caused the failure.")
     @Test
     public void transferUnsettledToUnknownDestinationWhenRejectedOutcomeSupportedBySource() throws Exception
     {
@@ -167,6 +178,7 @@ public class AnonymousRelayTest extends BrokerAdminUsingTestBase
                        .consumeResponse(Flow.class)
 
                        .transferPayload(generateMessagePayloadToDestination("Unknown"))
+                       .transferDeliveryTag(_deliveryTag)
                        .transfer()
                        .consumeResponse();
 
@@ -181,6 +193,8 @@ public class AnonymousRelayTest extends BrokerAdminUsingTestBase
             Error error = rejected.getError();
             assertThat(error, is(notNullValue()));
             assertThat(error.getCondition(), is(equalTo(AmqpError.NOT_FOUND)));
+            assertThat(error.getInfo(), is(notNullValue()));
+            assertThat(error.getInfo().get(DELIVERY_TAG), is(equalTo(_deliveryTag)));
         }
     }
 
@@ -192,7 +206,9 @@ public class AnonymousRelayTest extends BrokerAdminUsingTestBase
                           + " MUST communicate the error back to the sender of the message."
                           + " [...]"
                           + " If the source of the link does not support the rejected outcome,"
-                          + " [...] then the routing node MUST detach the link with an error.")
+                          + " [...] then the routing node MUST detach the link with an error."
+                          + " [...] the info field of error MUST contain an entry with symbolic key delivery-tag"
+                          + " and binary value of the delivery-tag of the message which caused the failure.")
     @Test
     public void transferUnsettledToUnknownDestinationWhenRejectedOutcomeNotSupportedBySource() throws Exception
     {
@@ -209,12 +225,15 @@ public class AnonymousRelayTest extends BrokerAdminUsingTestBase
                        .consumeResponse(Flow.class)
 
                        .transferPayload(generateMessagePayloadToDestination("Unknown"))
+                       .transferDeliveryTag(_deliveryTag)
                        .transfer();
 
             Detach detach = interaction.consumeResponse().getLatestResponse(Detach.class);
             Error error = detach.getError();
             assertThat(error, is(notNullValue()));
             assertThat(error.getCondition(), is(equalTo(AmqpError.NOT_FOUND)));
+            assertThat(error.getInfo(), is(notNullValue()));
+            assertThat(error.getInfo().get(DELIVERY_TAG), is(equalTo(_deliveryTag)));
         }
     }
 
@@ -243,6 +262,7 @@ public class AnonymousRelayTest extends BrokerAdminUsingTestBase
 
                        .transferHandle(linkHandle)
                        .transferPayload(generateMessagePayloadToDestination(BrokerAdmin.TEST_QUEUE_NAME))
+                       .transferDeliveryTag(_deliveryTag)
                        .transferTransactionalState(txnState.getCurrentTransactionId())
                        .transferSettled(Boolean.TRUE)
                        .transfer()
@@ -263,9 +283,12 @@ public class AnonymousRelayTest extends BrokerAdminUsingTestBase
                           + " [...]"
                           + " <Not in spec yet>"
                           + " AMQP-140"
+                          + " If a message cannot be routed to the destination implied in the \"to:\" field,"
+                          + " and the source does not allow for the rejected outcome"
+                          + " [...] when messages are being sent within a transaction and have been sent pre-settled."
                           + " In this case the behaviour defined for transactions (of essentially marking"
                           + " the transaction as rollback only) should take precedence. "
-                          + ""
+                            + ""
                           + " AMQP spec 4.3 Discharging a Transaction"
                           + " If the coordinator is unable to complete the discharge, the coordinator MUST convey"
                           + " the error to the controller as a transaction-error. If the source for the link to"
@@ -285,7 +308,7 @@ public class AnonymousRelayTest extends BrokerAdminUsingTestBase
             interaction.begin()
                        .consumeResponse(Begin.class)
 
-                       // attaching coordinator link with supported outcomes Accept and Reject
+                       // attaching coordinator link with supported outcomes Accepted and Rejected
                        .txnAttachCoordinatorLink(txnState)
                        .txnDeclare(txnState)
 
@@ -297,6 +320,7 @@ public class AnonymousRelayTest extends BrokerAdminUsingTestBase
 
                        .transferHandle(linkHandle)
                        .transferPayload(generateMessagePayloadToDestination("Unknown"))
+                       .transferDeliveryTag(_deliveryTag)
                        .transferTransactionalState(txnState.getCurrentTransactionId())
                        .transferSettled(Boolean.TRUE)
                        .transferDeliveryId(UnsignedInteger.valueOf(1))
@@ -351,6 +375,11 @@ public class AnonymousRelayTest extends BrokerAdminUsingTestBase
                           + " [...]"
                           + " <Not in spec yet>"
                           + " AMQP-140"
+                          + " If a message cannot be routed to the destination implied in the \"to:\" field,"
+                          + " and the source does not allow for the rejected outcome"
+                          + " [...] when messages are being sent within a transaction and have been sent pre-settled."
+                          + " In this case the behaviour defined for transactions (of essentially marking"
+                          + " the transaction as rollback only) should take precedence. "
                           + ""
                           + " AMQP spec 4.3 Discharging a Transaction"
                           + " If the coordinator is unable to complete the discharge, the coordinator MUST convey"
@@ -394,6 +423,7 @@ public class AnonymousRelayTest extends BrokerAdminUsingTestBase
 
                        .transferHandle(linkHandle)
                        .transferPayload(generateMessagePayloadToDestination("Unknown"))
+                       .transferDeliveryTag(_deliveryTag)
                        .transferTransactionalState(txnState.getCurrentTransactionId())
                        .transferSettled(Boolean.TRUE)
                        .transfer();


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


[02/11] qpid-broker-j git commit: QPID-8032: [Broker-J][AMQP 1.0] Coalesce the dispositions for non-transactional transfers

Posted by or...@apache.org.
QPID-8032: [Broker-J][AMQP 1.0] Coalesce the dispositions for non-transactional transfers

(cherry picked from commit 3b92c3063ee213a9e4c4527acd139d40a4237d56)


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/16beefd0
Tree: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/tree/16beefd0
Diff: http://git-wip-us.apache.org/repos/asf/qpid-broker-j/diff/16beefd0

Branch: refs/heads/7.0.x
Commit: 16beefd0d408461e472aaa5ad8fc32f1491172fe
Parents: cf30e22
Author: Keith Wall <kw...@apache.org>
Authored: Mon Jan 15 15:14:03 2018 +0000
Committer: Alex Rudyy <or...@apache.org>
Committed: Mon Jan 29 13:55:36 2018 +0000

----------------------------------------------------------------------
 .../v1_0/AbstractReceivingLinkEndpoint.java     |  55 +++++++---
 .../qpid/server/protocol/v1_0/Session_1_0.java  |  37 +++++++
 .../v1_0/StandardReceivingLinkEndpoint.java     | 102 +++++++++++++++----
 3 files changed, 161 insertions(+), 33 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/16beefd0/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 aec18ad..0872eae 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
@@ -22,8 +22,10 @@
 package org.apache.qpid.server.protocol.v1_0;
 
 import java.util.Collections;
+import java.util.HashSet;
 import java.util.LinkedHashMap;
 import java.util.Map;
+import java.util.Set;
 
 import org.apache.qpid.server.protocol.v1_0.delivery.UnsettledDelivery;
 import org.apache.qpid.server.protocol.v1_0.messaging.SectionDecoder;
@@ -295,7 +297,19 @@ public abstract class AbstractReceivingLinkEndpoint<T extends BaseTarget> extend
                            final DeliveryState state,
                            final boolean settled)
     {
-        if (_unsettled.containsKey(deliveryTag))
+        updateDispositions(Collections.singleton(deliveryTag), state, settled);
+    }
+
+    void updateDispositions(final Set<Binary> deliveryTags,
+                           final DeliveryState state,
+                           final boolean settled)
+    {
+
+        final Set<Binary> unsettledKeys = new HashSet<>(_unsettled.keySet());
+        unsettledKeys.retainAll(deliveryTags);
+        final int settledDeliveryCount = deliveryTags.size() - unsettledKeys.size();
+
+        if (!unsettledKeys.isEmpty())
         {
             boolean outcomeUpdate = false;
             Outcome outcome = null;
@@ -310,36 +324,49 @@ public abstract class AbstractReceivingLinkEndpoint<T extends BaseTarget> extend
 
             if (outcome != null)
             {
-                if (!(_unsettled.get(deliveryTag) instanceof Outcome))
+                for (final Binary deliveryTag : unsettledKeys)
                 {
-                    Object oldOutcome = _unsettled.put(deliveryTag, outcome);
-                    outcomeUpdate = !outcome.equals(oldOutcome);
+                    if (!(_unsettled.get(deliveryTag) instanceof Outcome))
+                    {
+                        Object oldOutcome = _unsettled.put(deliveryTag, outcome);
+                        outcomeUpdate = outcomeUpdate || !outcome.equals(oldOutcome);
+                    }
                 }
             }
 
             if (outcomeUpdate || settled)
             {
-                getSession().updateDisposition(getRole(), deliveryTag, state, settled);
+                getSession().updateDisposition(getRole(), unsettledKeys, state, settled);
             }
 
             if (settled)
             {
 
-                if (settled(deliveryTag))
+                int credit = 0;
+                for (final Binary deliveryTag : unsettledKeys)
                 {
-                    if (!isDetached() && _creditWindow)
+                    if (settled(deliveryTag))
                     {
-                        setLinkCredit(getLinkCredit().add(UnsignedInteger.ONE));
-                        sendFlowConditional();
-                    }
-                    else
-                    {
-                        getSession().sendFlowConditional();
+                        if (!isDetached() && _creditWindow)
+                        {
+                            credit++;
+                        }
                     }
                 }
+
+                if (credit > 0)
+                {
+                    setLinkCredit(getLinkCredit().add(UnsignedInteger.valueOf(credit)));
+                    sendFlowConditional();
+                }
+                else
+                {
+                    getSession().sendFlowConditional();
+                }
             }
         }
-        else if (_creditWindow)
+
+        if (settledDeliveryCount > 0 && _creditWindow)
         {
             setLinkCredit(getLinkCredit().add(UnsignedInteger.ONE));
             sendFlowConditional();

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/16beefd0/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 50b681d..62045a6 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
@@ -33,12 +33,16 @@ import java.util.Collections;
 import java.util.EnumSet;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import java.util.SortedSet;
+import java.util.TreeSet;
 import java.util.UUID;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
 
 import javax.security.auth.Subject;
 
@@ -257,6 +261,39 @@ public class Session_1_0 extends AbstractAMQPSession<Session_1_0, ConsumerTarget
         updateDisposition(role, deliveryId, deliveryId, state, settled);
     }
 
+    void updateDisposition(final Role role,
+                           final Set<Binary> deliveryTags,
+                           final DeliveryState state,
+                           final boolean settled)
+    {
+        final DeliveryRegistry deliveryRegistry = role == Role.RECEIVER ? _incomingDeliveryRegistry : _outgoingDeliveryRegistry;
+        SortedSet<UnsignedInteger> deliveryIds = deliveryTags.stream()
+                                                             .map(deliveryRegistry::getDeliveryIdByTag)
+                                                             .collect(Collectors.toCollection(TreeSet::new));
+
+        final Iterator<UnsignedInteger> iterator = deliveryIds.iterator();
+        if (iterator.hasNext())
+        {
+            UnsignedInteger begin = iterator.next();
+            UnsignedInteger end = begin;
+            while (iterator.hasNext())
+            {
+                final UnsignedInteger deliveryId = iterator.next();
+                if (!end.add(UnsignedInteger.ONE).equals(deliveryId))
+                {
+                    updateDisposition(role, begin, end, state, settled);
+                    begin = deliveryId;
+                    end = begin;
+                }
+                else
+                {
+                    end = deliveryId;
+                }
+            }
+            updateDisposition(role, begin, end, state, settled);
+        }
+    }
+
     public boolean hasCreditToSend()
     {
         boolean b = _remoteIncomingWindow > 0;

http://git-wip-us.apache.org/repos/asf/qpid-broker-j/blob/16beefd0/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 bc18bfb..fe5c4db 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
@@ -25,12 +25,16 @@ import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
 import java.util.concurrent.ExecutionException;
 
-import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -80,6 +84,8 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
 
     private final LinkedList<AsyncCommand> _unfinishedCommandsQueue = new LinkedList<>();
 
+    private final Set<PendingDispositionHolder> _pendingDispositions = new LinkedHashSet<>();
+
     private final PublishingLink _publishingLink = new PublishingLink()
     {
         @Override
@@ -306,24 +312,7 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
 
                     if (transaction instanceof AsyncAutoCommitTransaction)
                     {
-                        recordFuture(Futures.immediateFuture(null), new ServerTransaction.Action()
-                        {
-                            @Override
-                            public void postCommit()
-                            {
-                                updateDisposition(delivery.getDeliveryTag(), resultantState, settled);
-                            }
-
-                            @Override
-                            public void onRollback()
-                            {
-                                //TODO: if reject is not supported, check spec behaviour
-                                Rejected rejected = new Rejected();
-                                rejected.setError(new Error(AmqpError.ILLEGAL_STATE, "Store transaction unexpectedly rolled-back"));
-                                DeliveryState state = sourceSupportedOutcomes.contains(Rejected.REJECTED_SYMBOL) ? rejected : resultantState;
-                                updateDisposition(delivery.getDeliveryTag(), state, settled);
-                            }
-                        });
+                        _pendingDispositions.add(new PendingDispositionHolder(delivery.getDeliveryTag(), resultantState, settled));
                     }
                     else
                     {
@@ -571,6 +560,49 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
         {
             cmd.complete();
         }
+
+        processPendingDispositions();
+    }
+
+    private void processPendingDispositions()
+    {
+        Iterator<PendingDispositionHolder> itr = _pendingDispositions.isEmpty() ? Collections.emptyIterator() : _pendingDispositions.iterator();
+        if (itr.hasNext())
+        {
+            try
+            {
+                PendingDispositionHolder disposition = itr.next();
+                PendingDispositionHolder current = disposition;
+
+                Set<Binary> deliveryTags = new HashSet<>();
+                deliveryTags.add(disposition.getDeliveryTag());
+
+                while (itr.hasNext())
+                {
+                    disposition = itr.next();
+
+                    if (current.isSettled() == disposition.isSettled() &&
+                        Objects.equals(current.getResultantState(), disposition.getResultantState()))
+                    {
+                        deliveryTags.add(disposition.getDeliveryTag());
+                    }
+                    else
+                    {
+                        updateDispositions(deliveryTags, current.getResultantState(), current.isSettled());
+                        deliveryTags.clear();
+                        current = disposition;
+                    }
+                }
+                if (!deliveryTags.isEmpty())
+                {
+                    updateDispositions(deliveryTags, current.getResultantState(), current.isSettled());
+                }
+            }
+            finally
+            {
+                _pendingDispositions.clear();
+            }
+        }
     }
 
     private static class AsyncCommand
@@ -627,4 +659,36 @@ public class StandardReceivingLinkEndpoint extends AbstractReceivingLinkEndpoint
         }
     }
 
+    private static class PendingDispositionHolder
+    {
+        private final Binary _deliveryTag;
+        private final DeliveryState _resultantState;
+        private final boolean _settled;
+
+        PendingDispositionHolder(final Binary deliveryTag,
+                                 final DeliveryState resultantState,
+                                 final boolean settled)
+        {
+            _deliveryTag = deliveryTag;
+            _resultantState = resultantState;
+            _settled = settled;
+        }
+
+        Binary getDeliveryTag()
+        {
+            return _deliveryTag;
+        }
+
+        DeliveryState getResultantState()
+        {
+            return _resultantState;
+        }
+
+        boolean isSettled()
+        {
+            return _settled;
+        }
+
+
+    }
 }


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