Java Code Examples for org.apache.qpid.proton.engine.Delivery#settle()

The following examples show how to use org.apache.qpid.proton.engine.Delivery#settle() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Server.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public void onDelivery(Event evt) {
    Delivery dlv = evt.getDelivery();
    Link link = dlv.getLink();
    if (link instanceof Sender) {
        dlv.settle();
    } else {
        Receiver rcv = (Receiver) link;
        if (!dlv.isPartial()) {
            byte[] bytes = new byte[dlv.pending()];
            rcv.recv(bytes, 0, bytes.length);
            String address = router.getAddress(rcv);
            Message message = new Message(bytes);
            messages.put(address, message);
            dlv.disposition(Accepted.getInstance());
            dlv.settle();
            if (!quiet) {
                System.out.println(String.format("Got message(%s): %s", address, message));
            }
            send(address);
        }
    }
}
 
Example 2
Source File: Drain.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public void onDelivery(Event evt) {
    Delivery dlv = evt.getDelivery();
    if (dlv.getLink() instanceof Receiver) {
        Receiver receiver = (Receiver) dlv.getLink();

        if (!dlv.isPartial()) {
            byte[] bytes = new byte[dlv.pending()];
            receiver.recv(bytes, 0, bytes.length);
            Message msg = new Message(bytes);

            if (!quiet) {
                System.out.println(String.format("Got message: %s", msg));
            }
            received++;
            dlv.settle();
        }

        if ((received >= count) || (!block && !receiver.draining())) {
            receiver.getSession().getConnection().close();
        }
    }
}
 
Example 3
Source File: Send.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public void onLinkFlow(Event event) {
    Sender snd = (Sender)event.getLink();
    if (snd.getCredit() > 0) {
        byte[] msgData = new byte[1024];
        int length;
        while(true) {
            try {
                length = message.encode(msgData, 0, msgData.length);
                break;
            } catch(BufferOverflowException e) {
                msgData = new byte[msgData.length * 2];
            }
        }
        byte[] tag = String.valueOf(nextTag++).getBytes();
        Delivery dlv = snd.delivery(tag);
        snd.send(msgData, 0, length);
        dlv.settle();
        snd.advance();
        snd.close();
        snd.getSession().close();
        snd.getSession().getConnection().close();
    }
}
 
Example 4
Source File: AmqpReceiver.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
protected void deliveryFailed(Delivery incoming, boolean expandCredit) {
   Modified disposition = new Modified();
   disposition.setUndeliverableHere(true);
   disposition.setDeliveryFailed(true);
   incoming.disposition(disposition);
   incoming.settle();
   if (expandCredit) {
      getEndpoint().flow(1);
   }
}
 
Example 5
Source File: ProtonReceiverImpl.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
private void handleAborted(Receiver receiver, Delivery delivery) {
  splitContent = null;

  receiver.advance();
  delivery.settle();

  if(!receiver.getDrain()) {
    flow(1, false);
  } else {
    processForDrainCompletion();
  }
}
 
Example 6
Source File: ProtonSenderImpl.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
@Override
public ProtonDelivery send(byte[] tag, Message message, Handler<ProtonDelivery> onUpdated) {
  if (anonymousSender && message.getAddress() == null) {
    throw new IllegalArgumentException("Message must have an address when using anonymous sender.");
  }
  // TODO: prevent odd combination of onRecieved callback + SenderSettleMode.SETTLED, or just allow it?

  Delivery delivery = sender().delivery(tag); // start a new delivery..
  ProtonWritableBufferImpl buffer = new ProtonWritableBufferImpl();
  MessageImpl msg = (MessageImpl) message;
  msg.encode(buffer);
  ReadableBuffer encoded = new ProtonReadableBufferImpl(buffer.getBuffer());

  sender().sendNoCopy(encoded);

  if (link.getSenderSettleMode() == SenderSettleMode.SETTLED) {
    delivery.settle();
  }
  sender().advance(); // ends the delivery.

  ProtonDeliveryImpl protonDeliveryImpl = new ProtonDeliveryImpl(delivery);
  if (onUpdated != null) {
    protonDeliveryImpl.setAutoSettle(autoSettle);
    protonDeliveryImpl.handler(onUpdated);
  } else {
    protonDeliveryImpl.setAutoSettle(true);
  }

  getSession().getConnectionImpl().flush();

  return protonDeliveryImpl;
}
 
Example 7
Source File: AmqpConsumer.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
private void handleAccepted(JmsInboundMessageDispatch envelope, Delivery delivery) {
    LOG.debug("Accepted Ack of message: {}", envelope);
    if (!delivery.remotelySettled()) {
        if (session.isTransacted() && !getResourceInfo().isBrowser()) {

            if (session.isTransactionFailed()) {
                LOG.trace("Skipping ack of message {} in failed transaction.", envelope);
                return;
            }

            Binary txnId = session.getTransactionContext().getAmqpTransactionId();
            if (txnId != null) {
                delivery.disposition(session.getTransactionContext().getTxnAcceptState());
                delivery.settle();
                session.getTransactionContext().registerTxConsumer(this);
            }
        } else {
            delivery.disposition(Accepted.getInstance());
            delivery.settle();
        }
    } else {
        delivery.settle();
    }

    if (envelope.isDelivered()) {
        deliveredCount--;
    }
    dispatchedCount--;
}
 
Example 8
Source File: ProtonServerSenderContext.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Override
public void onMessage(Delivery delivery) throws ActiveMQAMQPException {
   if (closed) {
      return;
   }

   OperationContext oldContext = sessionSPI.recoverContext();

   try {
      Message message = ((MessageReference) delivery.getContext()).getMessage();
      DeliveryState remoteState = delivery.getRemoteState();

      if (remoteState != null && remoteState.getType() == DeliveryStateType.Accepted) {
         // this can happen in the twice ack mode, that is the receiver accepts and settles separately
         // acking again would show an exception but would have no negative effect but best to handle anyway.
         if (!delivery.isSettled()) {
            // we have to individual ack as we can't guarantee we will get the delivery updates
            // (including acks) in order from dealer, a performance hit but a must
            try {
               sessionSPI.ack(null, brokerConsumer, message);
            } catch (Exception e) {
               log.warn(e.toString(), e);
               throw ActiveMQAMQPProtocolMessageBundle.BUNDLE.errorAcknowledgingMessage(message.toString(), e.getMessage());
            }

            delivery.settle();
         }
      } else {
         handleExtendedDeliveryOutcomes(message, delivery, remoteState);
      }

      if (!preSettle) {
         protonSession.replaceTag(delivery.getTag());
      }
   } finally {
      sessionSPI.afterIO(connectionFlusher);
      sessionSPI.resetContext(oldContext);
   }
}
 
Example 9
Source File: AmqpSender.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private void doSend(AmqpMessage message, AsyncResult request, AmqpTransactionId txId) throws Exception {
   LOG.trace("Producer sending message: {}", message);

   Delivery delivery = null;
   if (presettle) {
      delivery = getEndpoint().delivery(EMPTY_BYTE_ARRAY, 0, 0);
   } else {
      byte[] tag = tagGenerator.getNextTag();
      delivery = getEndpoint().delivery(tag, 0, tag.length);
   }

   delivery.setContext(request);

   Binary amqpTxId = null;
   if (txId != null) {
      amqpTxId = txId.getRemoteTxId();
   } else if (session.isInTransaction()) {
      amqpTxId = session.getTransactionId().getRemoteTxId();
   }

   if (amqpTxId != null) {
      TransactionalState state = new TransactionalState();
      state.setTxnId(amqpTxId);
      delivery.disposition(state);
   }

   encodeAndSend(message.getWrappedMessage(), delivery);

   if (presettle) {
      delivery.settle();
      request.onSuccess();
   } else {
      pending.add(delivery);
      getEndpoint().advance();
   }
}
 
Example 10
Source File: Server.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
private int send(String address, Sender snd) {
    if (snd == null) {
        Router.Routes<Sender> routes = router.getOutgoing(address);
        snd = routes.choose();
        if (snd == null) {
            return 0;
        }
    }

    int count = 0;
    while (snd.getCredit() > 0 && snd.getQueued() < 1024) {
        Message msg = messages.get(address);
        if (msg == null) {
            snd.drained();
            return count;
        }
        Delivery dlv = snd.delivery(nextTag());
        byte[] bytes = msg.getBytes();
        snd.send(bytes, 0, bytes.length);
        dlv.settle();
        count++;
        if (!quiet) {
            System.out.println(String.format("Sent message(%s): %s", address, msg));
        }
    }

    return count;
}
 
Example 11
Source File: ReactorTest.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void onLinkFlow(Event event) {
    Sender link = (Sender)event.getLink();
    while (link.getCredit() > 0 && remaining > 0) {
        Delivery dlv = link.delivery(new byte[0]);
        assertNotNull(dlv);
        dlv.settle();
        link.advance();
        --remaining;
    }

    if (remaining == 0) {
        event.getConnection().close();
    }
}
 
Example 12
Source File: ReactorTest.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void onDelivery(Event event) {
    Delivery dlv = event.getDelivery();
    if (!dlv.isPartial()) {
        dlv.settle();
        ++received;
    }
}
 
Example 13
Source File: AmqpConsumer.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
private void handleDisposition(JmsInboundMessageDispatch envelope, Delivery delivery, DeliveryState outcome) {
    delivery.disposition(outcome);
    delivery.settle();
    if (envelope.isDelivered()) {
        deliveredCount--;
    }
    dispatchedCount--;
}
 
Example 14
Source File: Spout.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void onDelivery(Event evt) {
    Delivery dlv = evt.getDelivery();
    if (dlv.remotelySettled()) {
        if (!quiet) {
            System.out.println(String.format("Settled %s: %s", new String(dlv.getTag()), dlv.getRemoteState()));
        }
        dlv.settle();
        settled++;
    }

    if (settled >= count) {
        dlv.getLink().getSession().getConnection().close();
    }
}
 
Example 15
Source File: AmqpConsumer.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private boolean processDelivery(Delivery incoming) throws Exception {
    JmsMessage message = null;
    try {
        message = AmqpCodec.decodeMessage(this, getEndpoint().recv()).asJmsMessage();
    } catch (Exception e) {
        LOG.warn("Error on transform: {}", e.getMessage());
        // TODO - We could signal provider error but not sure we want to fail
        //        the connection just because we can't convert the message.
        //        In the future once the JMS mapping is complete we should be
        //        able to convert everything to some message even if its just
        //        a bytes messages as a fall back.
        incoming.disposition(MODIFIED_FAILED_UNDELIVERABLE);
        incoming.settle();
        // TODO: this flows credit, which we might not want, e.g if
        // a drain was issued to stop the link.
        sendFlowIfNeeded();
        return false;
    }

    try {
        // Let the message do any final processing before sending it onto a consumer.
        // We could defer this to a later stage such as the JmsConnection or even in
        // the JmsMessageConsumer dispatch method if we needed to.
        message.onDispatch();

        JmsInboundMessageDispatch envelope = new JmsInboundMessageDispatch(getNextIncomingSequenceNumber());
        envelope.setMessage(message);
        envelope.setConsumerId(getResourceInfo().getId());
        envelope.setConsumerInfo(getResourceInfo());
        // Store link to delivery in the hint for use in acknowledge requests.
        envelope.setProviderHint(incoming);
        envelope.setMessageId(message.getFacade().getProviderMessageIdObject());

        // Store reference to envelope in delivery context for recovery
        incoming.setContext(envelope);

        deliver(envelope);

        return true;
    } finally {
        getEndpoint().advance();
    }
}
 
Example 16
Source File: ProtonServerSenderContext.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
public void settle(Delivery delivery) {
   connection.requireInHandler();
   delivery.settle();
}
 
Example 17
Source File: ProtonServerSenderContext.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
private void deliverStandard(MessageReference messageReference, AMQPMessage message) {
   // Let the Message decide how to present the message bytes
   ReadableBuffer sendBuffer = message.getSendBuffer(messageReference.getDeliveryCount());
   // we only need a tag if we are going to settle later
   byte[] tag = preSettle ? new byte[0] : protonSession.getTag();

   boolean releaseRequired = sendBuffer instanceof NettyReadable;
   final Delivery delivery;
   delivery = sender.delivery(tag, 0, tag.length);
   delivery.setMessageFormat((int) message.getMessageFormat());
   delivery.setContext(messageReference);

   try {

      if (releaseRequired) {
         sender.send(sendBuffer);
         // Above send copied, so release now if needed
         releaseRequired = false;
         ((NettyReadable) sendBuffer).getByteBuf().release();
      } else {
         // Don't have pooled content, no need to release or copy.
         sender.sendNoCopy(sendBuffer);
      }

      if (preSettle) {
         // Presettled means the client implicitly accepts any delivery we send it.
         try {
            sessionSPI.ack(null, brokerConsumer, messageReference.getMessage());
         } catch (Exception e) {
            log.debug(e.getMessage(), e);
         }
         delivery.settle();
      } else {
         sender.advance();
      }

      connection.flush();
   } finally {
      synchronized (creditsLock) {
         pending.decrementAndGet();
      }
      if (releaseRequired) {
         ((NettyReadable) sendBuffer).getByteBuf().release();
      }
   }
}
 
Example 18
Source File: TransportImplTest.java    From qpid-proton-j with Apache License 2.0 4 votes vote down vote up
/**
 * Verify that no Disposition frame is emitted by the Transport should a Delivery
 * have disposition applied after the Close frame was sent.
 */
@Test
public void testDispositionAfterCloseSent()
{
    MockTransportImpl transport = new MockTransportImpl();
    Connection connection = Proton.connection();
    transport.bind(connection);

    connection.open();

    Session session = connection.session();
    session.open();

    String linkName = "myReceiver";
    Receiver receiver = session.receiver(linkName);
    receiver.flow(5);
    receiver.open();

    pumpMockTransport(transport);

    assertEquals("Unexpected frames written: " + getFrameTypesWritten(transport), 4, transport.writes.size());

    assertTrue("Unexpected frame type", transport.writes.get(0) instanceof Open);
    assertTrue("Unexpected frame type", transport.writes.get(1) instanceof Begin);
    assertTrue("Unexpected frame type", transport.writes.get(2) instanceof Attach);
    assertTrue("Unexpected frame type", transport.writes.get(3) instanceof Flow);

    Delivery delivery = receiver.current();
    assertNull("Should not yet have a delivery", delivery);

    // Send the necessary responses to open/begin/attach as well as a transfer
    transport.handleFrame(new TransportFrame(0, new Open(), null));

    Begin begin = new Begin();
    begin.setRemoteChannel(UnsignedShort.valueOf((short) 0));
    begin.setNextOutgoingId(UnsignedInteger.ONE);
    begin.setIncomingWindow(UnsignedInteger.valueOf(1024));
    begin.setOutgoingWindow(UnsignedInteger.valueOf(1024));
    transport.handleFrame(new TransportFrame(0, begin, null));

    Attach attach = new Attach();
    attach.setHandle(UnsignedInteger.ZERO);
    attach.setRole(Role.SENDER);
    attach.setName(linkName);
    attach.setInitialDeliveryCount(UnsignedInteger.ZERO);
    transport.handleFrame(new TransportFrame(0, attach, null));

    String deliveryTag = "tag1";
    String messageContent = "content1";
    handleTransfer(transport, 1, deliveryTag, messageContent);

    assertEquals("Unexpected frames written: " + getFrameTypesWritten(transport), 4, transport.writes.size());

    delivery = verifyDelivery(receiver, deliveryTag, messageContent);
    assertNotNull("Should now have a delivery", delivery);

    // Cause the Close frame to be sent
    connection.close();
    pumpMockTransport(transport);

    assertEquals("Unexpected frames written: " + getFrameTypesWritten(transport), 5, transport.writes.size());
    assertTrue("Unexpected frame type", transport.writes.get(4) instanceof Close);

    delivery.disposition(Released.getInstance());
    delivery.settle();

    pumpMockTransport(transport);

    assertEquals("Unexpected frames written: " + getFrameTypesWritten(transport), 5, transport.writes.size());
}
 
Example 19
Source File: AmqpTransactionCoordinator.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
@Override
public void processDeliveryUpdates(AmqpProvider provider, Delivery delivery) throws ProviderException {

    try {
        if (delivery != null && delivery.remotelySettled()) {
            DeliveryState state = delivery.getRemoteState();

            if (delivery.getContext() == null || !(delivery.getContext() instanceof OperationContext)) {
                return;
            }

            OperationContext context = (OperationContext) delivery.getContext();

            AsyncResult pendingRequest = context.getRequest();
            JmsTransactionId txId = context.getTransactionId();

            if (state instanceof Declared) {
                LOG.debug("New TX started: {}", txId);
                Declared declared = (Declared) state;
                txId.setProviderHint(declared.getTxnId());
                pendingRequest.onSuccess();
            } else if (state instanceof Rejected) {
                LOG.debug("Last TX request failed: {}", txId);
                Rejected rejected = (Rejected) state;
                ProviderException cause = AmqpSupport.convertToNonFatalException(getParent().getProvider(), getEndpoint(), rejected.getError());
                if (COMMIT_MARKER.equals(txId.getProviderContext()) && !(cause instanceof ProviderTransactionRolledBackException)){
                    cause = new ProviderTransactionRolledBackException(cause.getMessage(), cause);
                } else {
                    cause = new ProviderTransactionInDoubtException(cause.getMessage(), cause);
                }

                txId.setProviderHint(null);
                pendingRequest.onFailure(cause);
            } else {
                LOG.debug("Last TX request succeeded: {}", txId);
                pendingRequest.onSuccess();
            }

            // Reset state for next TX action.
            delivery.settle();
            pendingRequest = null;

            if (context.getTimeout() != null) {
                context.getTimeout().cancel(false);
            }
        }

        super.processDeliveryUpdates(provider, delivery);
    } catch (Throwable e) {
        throw ProviderExceptionSupport.createNonFatalOrPassthrough(e);
    }
}
 
Example 20
Source File: AmqpFixedProducer.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private void doSend(JmsOutboundMessageDispatch envelope, InFlightSend send) throws ProviderException {
    LOG.trace("Producer sending message: {}", envelope);

    boolean presettle = envelope.isPresettle() || isPresettle();
    Delivery delivery = null;

    if (presettle) {
        delivery = getEndpoint().delivery(EMPTY_BYTE_ARRAY, 0, 0);
    } else {
        byte[] tag = tagGenerator.getNextTag();
        delivery = getEndpoint().delivery(tag, 0, tag.length);
    }

    if (session.isTransacted()) {
        AmqpTransactionContext context = session.getTransactionContext();
        delivery.disposition(context.getTxnEnrolledState());
        context.registerTxProducer(this);
    }

    // Write the already encoded AMQP message into the Sender
    ByteBuf encoded = (ByteBuf) envelope.getPayload();
    getEndpoint().sendNoCopy(new AmqpReadableBuffer(encoded.duplicate()));

    AmqpProvider provider = getParent().getProvider();

    if (!presettle && getSendTimeout() != JmsConnectionInfo.INFINITE && send.requestTimeout == null) {
        send.requestTimeout = getParent().getProvider().scheduleRequestTimeout(send, getSendTimeout(), send);
    }

    if (presettle) {
        delivery.settle();
    } else {
        sent.put(envelope.getMessageId(), send);
        getEndpoint().advance();
    }

    send.setDelivery(delivery);
    delivery.setContext(send);

    // Put it on the wire and let it fail if the connection is broken, if it does
    // get written then continue on to determine when we should complete it.
    if (provider.pumpToProtonTransport(send, false)) {
        // For presettled messages we can just mark as successful and we are done, but
        // for any other message we still track it until the remote settles.  If the send
        // was tagged as asynchronous we must mark the original request as complete but
        // we still need to wait for the disposition before we can consider the send as
        // having been successful.
        if (presettle) {
            send.onSuccess();
        } else if (envelope.isSendAsync()) {
            send.getOriginalRequest().onSuccess();
        }

        try {
            provider.getTransport().flush();
        } catch (Throwable ex) {
            throw ProviderExceptionSupport.createOrPassthroughFatal(ex);
        }
    }
}