org.apache.qpid.proton.amqp.transport.DeliveryState Java Examples

The following examples show how to use org.apache.qpid.proton.amqp.transport.DeliveryState. 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: ProtonServerReceiverContext.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private DeliveryState determineDeliveryState(final Source source, final boolean useModified, final Exception e) {
   Outcome defaultOutcome = getEffectiveDefaultOutcome(source);

   if (isAddressFull(e) && useModified &&
       (outcomeSupported(source, Modified.DESCRIPTOR_SYMBOL) || defaultOutcome instanceof Modified)) {
      Modified modified = new Modified();
      modified.setDeliveryFailed(true);
      return modified;
   } else {
      if (outcomeSupported(source, Rejected.DESCRIPTOR_SYMBOL) || defaultOutcome instanceof Rejected) {
         return createRejected(e);
      } else if (source.getDefaultOutcome() instanceof DeliveryState) {
         return ((DeliveryState) source.getDefaultOutcome());
      } else {
         // The AMQP specification requires that Accepted is returned for this case. However there exist
         // implementations that set neither outcomes/default-outcome but use/expect for full range of outcomes.
         // To maintain compatibility with these implementations, we maintain previous behaviour.
         return createRejected(e);
      }
   }
}
 
Example #2
Source File: RequestResponseEndpointTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the endpoint rejects malformed request messages.
 */
@Test
public void testHandleMessageRejectsMalformedMessage() {

    final Message msg = ProtonHelper.message();
    final ProtonConnection con = mock(ProtonConnection.class);
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    final RequestResponseEndpoint<ServiceConfigProperties> endpoint = getEndpoint(false);

    // WHEN a malformed message is received
    endpoint.handleRequestMessage(con, receiver, resource, delivery, msg);

    // THEN the link is closed and the message is rejected
    final ArgumentCaptor<DeliveryState> deliveryState = ArgumentCaptor.forClass(DeliveryState.class);
    verify(delivery).disposition(deliveryState.capture(), eq(Boolean.TRUE));
    assertThat(deliveryState.getValue()).isInstanceOf(Rejected.class);
    verify(receiver, never()).close();
    verify(receiver).flow(1);
}
 
Example #3
Source File: AmqpFixedProducer.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Override
public void processDeliveryUpdates(AmqpProvider provider, Delivery delivery) throws ProviderException {
    DeliveryState state = delivery.getRemoteState();
    if (state != null) {
        InFlightSend send = (InFlightSend) delivery.getContext();

        if (state.getType() == DeliveryStateType.Accepted) {
            LOG.trace("Outcome of delivery was accepted: {}", delivery);
            send.onSuccess();
        } else {
            applyDeliveryStateUpdate(send, delivery, state);
        }
    }

    super.processDeliveryUpdates(provider, delivery);
}
 
Example #4
Source File: TelemetryAndEventCli.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private void printDelivery(final ProtonDelivery delivery) {
    final DeliveryState state = delivery.getRemoteState();
    writer.printf("[Delivery State: %s] %n", state.getType()).flush();
    switch (state.getType()) {
    case Rejected:
        final Rejected rejected = (Rejected) state;
        if (rejected.getError() != null) {
            writer.printf("Message rejected: [Error Condition: %s, Error Description: %s] %n",
                    rejected.getError().getCondition(), rejected.getError().getDescription());
            writer.flush();
        }
        break;
    default:
        break;
    }
}
 
Example #5
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 #6
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 #7
Source File: DispositionType.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
public Disposition newInstance(Object described)
{
    List l = (List) described;

    Disposition o = new Disposition();

    if(l.isEmpty())
    {
        throw new DecodeException("The first field cannot be omitted");
    }

    switch(6 - l.size())
    {

        case 0:
            Boolean batchable = (Boolean) l.get(5);
            o.setBatchable(batchable == null ? false : batchable);
        case 1:
            o.setState( (DeliveryState) l.get( 4 ) );
        case 2:
            Boolean settled = (Boolean) l.get(3);
            o.setSettled(settled == null ? false : settled);
        case 3:
            o.setLast( (UnsignedInteger) l.get( 2 ) );
        case 4:
            o.setFirst( (UnsignedInteger) l.get( 1 ) );
        case 5:
            o.setRole( Boolean.TRUE.equals(l.get( 0 )) ? Role.RECEIVER : Role.SENDER );
    }


    return o;
}
 
Example #8
Source File: FastPathDispositionType.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
private final Disposition readFields(DecoderImpl decoder, int count) {
    Disposition disposition = new Disposition();

    for (int index = 0; index < count; ++index) {
        switch (index) {
            case 0:
                disposition.setRole(Boolean.TRUE.equals(decoder.readBoolean()) ? Role.RECEIVER : Role.SENDER);
                break;
            case 1:
                disposition.setFirst(decoder.readUnsignedInteger(null));
                break;
            case 2:
                disposition.setLast(decoder.readUnsignedInteger(null));
                break;
            case 3:
                disposition.setSettled(decoder.readBoolean(false));
                break;
            case 4:
                disposition.setState((DeliveryState) decoder.readObject());
                break;
            case 5:
                disposition.setBatchable(decoder.readBoolean(false));
                break;
            default:
                throw new IllegalStateException("To many entries in Disposition encoding");
        }
    }

    return disposition;
}
 
Example #9
Source File: ProtonServerReceiverContext.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
public void deliveryFailed(Delivery delivery, Receiver receiver, Exception e) {
   connection.runNow(() -> {
      DeliveryState deliveryState = determineDeliveryState(((Source) receiver.getSource()),
                                                           useModified,
                                                           e);
      delivery.disposition(deliveryState);
      settle(delivery);
      connection.flush();
   });
}
 
Example #10
Source File: CommandContext.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Settles the command message with the given {@code DeliveryState} outcome.
 * <p>
 * This method also finishes the OpenTracing span returned by
 * {@link #getCurrentSpan()}.
 *
 * @param deliveryState The deliveryState to set in the disposition frame.
 * @throws NullPointerException if deliveryState is {@code null}.
 */
public void disposition(final DeliveryState deliveryState) {

    Objects.requireNonNull(deliveryState);
    delivery.disposition(deliveryState, true);
    if (Accepted.class.isInstance(deliveryState)) {
        LOG.trace("accepted command message [{}]", getCommand());
        currentSpan.log("accepted command for device");

    } else if (Released.class.isInstance(deliveryState)) {
        LOG.debug("released command message [{}]", getCommand());
        TracingHelper.logError(currentSpan, "released command for device");

    } else if (Modified.class.isInstance(deliveryState)) {
        final Modified modified = (Modified) deliveryState;
        LOG.debug("modified command message [{}]", getCommand());
        TracingHelper.logError(currentSpan, "modified command for device"
                + (Boolean.TRUE.equals(modified.getDeliveryFailed()) ? "; delivery failed" : "")
                + (Boolean.TRUE.equals(modified.getUndeliverableHere()) ? "; undeliverable here" : ""));

    } else if (Rejected.class.isInstance(deliveryState)) {
        final ErrorCondition errorCondition = ((Rejected) deliveryState).getError();
        LOG.debug("rejected command message [error: {}, command: {}]", errorCondition, getCommand());
        TracingHelper.logError(currentSpan, "rejected command for device"
                + ((errorCondition != null && errorCondition.getDescription() != null) ? "; error: " + errorCondition.getDescription() : ""));
    } else {
        LOG.warn("unexpected delivery state [{}] when settling command message [{}]", deliveryState, getCommand());
        TracingHelper.logError(currentSpan, "unexpected delivery state: " + deliveryState);
    }
    currentSpan.finish();
}
 
Example #11
Source File: DeliveryImpl.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
@Override
public Delivery disposition(final DeliveryState state, final boolean settle) {
  ackOnContext(v -> {
    delivery.disposition(state, settle);
  });

  return this;
}
 
Example #12
Source File: DeliveryImpl.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
@Override
public void disposition(final DeliveryState state)
{
    _deliveryState = state;
    if(!_remoteSettled && !_settled)
    {
        addToTransportWorkList();
    }
}
 
Example #13
Source File: TransportImpl.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
private boolean processTransportWorkReceiver(DeliveryImpl delivery, ReceiverImpl rcv)
{
    TransportDelivery tpDelivery = delivery.getTransportDelivery();
    SessionImpl session = rcv.getSession();
    TransportSession tpSession = session.getTransportSession();

    if (tpSession.isLocalChannelSet())
    {
        boolean settled = delivery.isSettled();
        DeliveryState localState = delivery.getLocalState();
        // Use cached object as holder of data for immediate write to the FrameWriter
        cachedDisposition.setFirst(tpDelivery.getDeliveryId());
        cachedDisposition.setLast(tpDelivery.getDeliveryId());
        cachedDisposition.setRole(Role.RECEIVER);
        cachedDisposition.setSettled(settled);
        cachedDisposition.setState(localState);
        cachedDisposition.setBatchable(false);  // Enforce default is written

        if(localState == null && settled) {
            cachedDisposition.setState(delivery.getDefaultDeliveryState());
        }

        writeFrame(tpSession.getLocalChannel(), cachedDisposition, null, null);
        if (settled)
        {
            tpDelivery.settled();
        }
        return true;
    }

    return false;
}
 
Example #14
Source File: ProtonDeliveryImpl.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
@Override
public ProtonDelivery disposition(DeliveryState state, boolean settle) {
  if(delivery.isSettled()) {
    return this;
  }

  delivery.disposition(state);
  if (settle) {
    settle();
  } else {
    flushConnection();
  }

  return this;
}
 
Example #15
Source File: RequestResponseEndpointTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the endpoint rejects request messages for operations the client
 * is not authorized to invoke.
 */
@SuppressWarnings("unchecked")
@Test
public void testHandleMessageSendsResponseForUnauthorizedRequests() {

    final Message msg = ProtonHelper.message();
    msg.setSubject("unauthorized");
    msg.setReplyTo(REPLY_RESOURCE.toString());
    msg.setCorrelationId(UUID.randomUUID().toString());
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    final AuthorizationService authService = mock(AuthorizationService.class);
    when(authService.isAuthorized(any(HonoUser.class), any(ResourceIdentifier.class), anyString())).thenReturn(Future.succeededFuture(Boolean.FALSE));
    final RequestResponseEndpoint<ServiceConfigProperties> endpoint = getEndpoint(true);
    endpoint.setAuthorizationService(authService);
    endpoint.onLinkAttach(connection, sender, REPLY_RESOURCE);

    // WHEN a request for an operation is received that the client is not authorized to invoke
    endpoint.handleRequestMessage(connection, receiver, resource, delivery, msg);

    // THEN the message is accepted
    final ArgumentCaptor<DeliveryState> deliveryState = ArgumentCaptor.forClass(DeliveryState.class);
    verify(delivery).disposition(deliveryState.capture(), eq(Boolean.TRUE));
    assertThat(deliveryState.getValue()).isInstanceOf(Accepted.class);
    verify(receiver, never()).close();
    verify(authService).isAuthorized(Constants.PRINCIPAL_ANONYMOUS, resource, "unauthorized");
    // but not forwarded to the service instance
    verify(eventBus, never()).request(anyString(), any(), any(DeliveryOptions.class), any(Handler.class));
    // and a response is sent to the client with status 403
    verify(sender).send(argThat(m -> hasStatusCode(m, HttpURLConnection.HTTP_FORBIDDEN)));
}
 
Example #16
Source File: AbstractSender.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates a log entry in the given span with information about the message delivery outcome given in the delivery
 * parameter. Sets the {@link Tags#HTTP_STATUS} as well.
 * <p>
 * Also corresponding log output is created.
 *
 * @param currentSpan The current span to log to.
 * @param message The message.
 * @param delivery The updated delivery.
 * @throws NullPointerException if any of the parameters is {@code null}.
 */
protected final void logUpdatedDeliveryState(final Span currentSpan, final Message message, final ProtonDelivery delivery) {
    Objects.requireNonNull(currentSpan);
    final String messageId = message.getMessageId() != null ? message.getMessageId().toString() : "";
    final String messageAddress = getMessageAddress(message);
    final DeliveryState remoteState = delivery.getRemoteState();
    if (Accepted.class.isInstance(remoteState)) {
        log.trace("message [ID: {}, address: {}] accepted by peer", messageId, messageAddress);
        currentSpan.log("message accepted by peer");
        Tags.HTTP_STATUS.set(currentSpan, HttpURLConnection.HTTP_ACCEPTED);
    } else {
        final Map<String, Object> events = new HashMap<>();
        if (Rejected.class.isInstance(remoteState)) {
            final Rejected rejected = (Rejected) delivery.getRemoteState();
            Tags.HTTP_STATUS.set(currentSpan, HttpURLConnection.HTTP_BAD_REQUEST);
            if (rejected.getError() == null) {
                logMessageSendingError("message [ID: {}, address: {}] rejected by peer", messageId, messageAddress);
                events.put(Fields.MESSAGE, "message rejected by peer");
            } else {
                logMessageSendingError("message [ID: {}, address: {}] rejected by peer: {}, {}", messageId,
                        messageAddress, rejected.getError().getCondition(), rejected.getError().getDescription());
                events.put(Fields.MESSAGE, String.format("message rejected by peer: %s, %s",
                        rejected.getError().getCondition(), rejected.getError().getDescription()));
            }
        } else if (Released.class.isInstance(remoteState)) {
            logMessageSendingError("message [ID: {}, address: {}] not accepted by peer, remote state: {}",
                    messageId, messageAddress, remoteState.getClass().getSimpleName());
            Tags.HTTP_STATUS.set(currentSpan, HttpURLConnection.HTTP_UNAVAILABLE);
            events.put(Fields.MESSAGE, "message not accepted by peer, remote state: " + remoteState);
        } else if (Modified.class.isInstance(remoteState)) {
            final Modified modified = (Modified) delivery.getRemoteState();
            logMessageSendingError("message [ID: {}, address: {}] not accepted by peer, remote state: {}",
                    messageId, messageAddress, modified);
            Tags.HTTP_STATUS.set(currentSpan, modified.getUndeliverableHere() ? HttpURLConnection.HTTP_NOT_FOUND
                    : HttpURLConnection.HTTP_UNAVAILABLE);
            events.put(Fields.MESSAGE, "message not accepted by peer, remote state: " + remoteState);
        }
        TracingHelper.logError(currentSpan, events);
    }
}
 
Example #17
Source File: AdapterInstanceCommandHandlerTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Test
void testHandleCommandMessageWithInvalidMessage() {
    final Message msg = mock(Message.class);
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    adapterInstanceCommandHandler.handleCommandMessage(msg, delivery);

    final ArgumentCaptor<DeliveryState> deliveryStateCaptor = ArgumentCaptor.forClass(DeliveryState.class);
    verify(delivery).disposition(deliveryStateCaptor.capture(), anyBoolean());
    assertThat(deliveryStateCaptor.getValue()).isNotNull();
    assertThat(deliveryStateCaptor.getValue()).isInstanceOf(Rejected.class);
}
 
Example #18
Source File: AdapterInstanceCommandHandlerTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Test
void testHandleCommandMessageWithNoHandlerFound() {
    final Message msg = mock(Message.class);
    final String deviceId = "4711";
    when(msg.getAddress()).thenReturn(String.format("%s/%s/%s",
            CommandConstants.COMMAND_ENDPOINT, Constants.DEFAULT_TENANT, deviceId));
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    adapterInstanceCommandHandler.handleCommandMessage(msg, delivery);

    final ArgumentCaptor<DeliveryState> deliveryStateCaptor = ArgumentCaptor.forClass(DeliveryState.class);
    verify(delivery).disposition(deliveryStateCaptor.capture(), anyBoolean());
    assertThat(deliveryStateCaptor.getValue()).isNotNull();
    assertThat(deliveryStateCaptor.getValue()).isInstanceOf(Released.class);
}
 
Example #19
Source File: AmqpFixedProducer.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
private void handleSendCompletion(boolean successful) {
    setRequestTimeout(null);

    if (getDelivery() != null) {
        sent.remove(envelope.getMessageId());
        delivery.settle();
        tagGenerator.returnTag(delivery.getTag());
    } else {
        blocked.remove(envelope.getMessageId());
    }

    // Null delivery means that we never had credit to send so no delivery was created to carry the message.
    if (delivery != null) {
        DeliveryState remoteState = delivery.getRemoteState();
        tracer.completeSend(envelope.getMessage().getFacade(), remoteState == null ? null : remoteState.getType().name());
    } else {
        tracer.completeSend(envelope.getMessage().getFacade(), null);
    }

    // Put the message back to usable state following send complete
    envelope.getMessage().onSendComplete();

    // Once the pending sends queue is drained and all in-flight sends have been
    // settled we can propagate the close request.
    if (isAwaitingClose() && !isClosed() && blocked.isEmpty() && sent.isEmpty()) {
        AmqpFixedProducer.super.close(closeRequest);
    }
}
 
Example #20
Source File: VertxBasedAmqpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter signals a rejected one-way command
 * back to the sender of the command.
 */
@Test
public void testOneWayCommandRejected() {

    final DeliveryState remoteState = new Rejected();
    final ProtonDelivery unsuccessfulDelivery = mock(ProtonDelivery.class);
    when(unsuccessfulDelivery.remotelySettled()).thenReturn(true);
    when(unsuccessfulDelivery.getRemoteState()).thenReturn(remoteState);
    testOneWayCommandOutcome(unsuccessfulDelivery, Rejected.class, ProcessingOutcome.UNPROCESSABLE);
}
 
Example #21
Source File: VertxBasedAmqpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter signals a released one-way command
 * back to the sender of the command.
 */
@Test
public void testOneWayCommandReleased() {

    final DeliveryState remoteState = new Released();
    final ProtonDelivery unsuccessfulDelivery = mock(ProtonDelivery.class);
    when(unsuccessfulDelivery.remotelySettled()).thenReturn(true);
    when(unsuccessfulDelivery.getRemoteState()).thenReturn(remoteState);
    testOneWayCommandOutcome(unsuccessfulDelivery, Released.class, ProcessingOutcome.UNDELIVERABLE);
}
 
Example #22
Source File: VertxBasedAmqpProtocolAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the adapter signals a released one-way command
 * back to the sender of the command.
 */
@Test
public void testOneWayCommandUnsettled() {

    final DeliveryState remoteState = mock(DeliveryState.class);
    final ProtonDelivery unsuccessfulDelivery = mock(ProtonDelivery.class);
    when(unsuccessfulDelivery.remotelySettled()).thenReturn(false);
    when(unsuccessfulDelivery.getRemoteState()).thenReturn(remoteState);
    testOneWayCommandOutcome(unsuccessfulDelivery, Released.class, ProcessingOutcome.UNDELIVERABLE);
}
 
Example #23
Source File: RequestResponseEndpointTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the endpoint processes request messages for operations the client
 * is authorized to invoke.
 */
@SuppressWarnings("unchecked")
@Test
public void testHandleMessageProcessesAuthorizedRequests() {

    final Message msg = ProtonHelper.message();
    msg.setSubject("get");
    msg.setReplyTo(REPLY_RESOURCE.toString());
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    final AuthorizationService authService = mock(AuthorizationService.class);
    when(authService.isAuthorized(any(HonoUser.class), any(ResourceIdentifier.class), anyString())).thenReturn(Future.succeededFuture(Boolean.TRUE));

    final RequestResponseEndpoint<ServiceConfigProperties> endpoint = getEndpoint(true);
    endpoint.setAuthorizationService(authService);
    endpoint.onLinkAttach(connection, sender, REPLY_RESOURCE);

    // WHEN a request for an operation is received that the client is authorized to invoke
    endpoint.handleRequestMessage(connection, receiver, resource, delivery, msg);

    // THEN then the message gets processed
    final ArgumentCaptor<DeliveryState> deliveryState = ArgumentCaptor.forClass(DeliveryState.class);
    verify(delivery).disposition(deliveryState.capture(), eq(Boolean.TRUE));
    assertThat(deliveryState.getValue()).isInstanceOf(Accepted.class);
    verify(receiver, never()).close();
    verify(authService).isAuthorized(Constants.PRINCIPAL_ANONYMOUS, resource, "get");
    // and forwarded to the service instance
    final ArgumentCaptor<Handler<AsyncResult<io.vertx.core.eventbus.Message<Object>>>> replyHandler = ArgumentCaptor.forClass(Handler.class);
    verify(eventBus).request(eq(EVENT_BUS_ADDRESS), any(JsonObject.class), any(DeliveryOptions.class), replyHandler.capture());

    // WHEN the service implementation sends the response
    final EventBusMessage response = EventBusMessage.forStatusCode(HttpURLConnection.HTTP_ACCEPTED);
    final io.vertx.core.eventbus.Message<Object> reply = mock(io.vertx.core.eventbus.Message.class);
    when(reply.body()).thenReturn(response.toJson());
    replyHandler.getValue().handle(Future.succeededFuture(reply));

    // THEN the response is sent to the client
    verify(sender).send(any(Message.class));
    verify(receiver).flow(1);
}
 
Example #24
Source File: ProtonDeliveryImpl.java    From vertx-proton with Apache License 2.0 4 votes vote down vote up
public void setDefaultDeliveryState(DeliveryState state) {
  delivery.setDefaultDeliveryState(state);
}
 
Example #25
Source File: ProtonDeliveryImpl.java    From vertx-proton with Apache License 2.0 4 votes vote down vote up
public DeliveryState getLocalState() {
  return delivery.getLocalState();
}
 
Example #26
Source File: ProtonDeliveryImpl.java    From vertx-proton with Apache License 2.0 4 votes vote down vote up
public DeliveryState getDefaultDeliveryState() {
  return delivery.getDefaultDeliveryState();
}
 
Example #27
Source File: TrackerImpl.java    From vertx-proton with Apache License 2.0 4 votes vote down vote up
@Override
public DeliveryState getRemoteState() {
  return delivery.getRemoteState();
}
 
Example #28
Source File: ProtonDeliveryImpl.java    From vertx-proton with Apache License 2.0 4 votes vote down vote up
public DeliveryState getRemoteState() {
  return delivery.getRemoteState();
}
 
Example #29
Source File: AmqpFixedProducer.java    From qpid-jms with Apache License 2.0 4 votes vote down vote up
private void applyDeliveryStateUpdate(InFlightSend send, Delivery delivery, DeliveryState state) {
    ProviderException deliveryError = null;
    if (state == null) {
        return;
    }

    switch (state.getType()) {
        case Transactional:
            LOG.trace("State of delivery is Transactional, retrieving outcome: {}", state);
            applyDeliveryStateUpdate(send, delivery, (DeliveryState) ((TransactionalState) state).getOutcome());
            break;
        case Accepted:
            LOG.trace("Outcome of delivery was accepted: {}", delivery);
            send.onSuccess();
            break;
        case Rejected:
            LOG.trace("Outcome of delivery was rejected: {}", delivery);
            ErrorCondition remoteError = ((Rejected) state).getError();
            if (remoteError == null) {
                remoteError = getEndpoint().getRemoteCondition();
            }

            deliveryError = AmqpSupport.convertToNonFatalException(getParent().getProvider(), getEndpoint(), remoteError);
            break;
        case Released:
            LOG.trace("Outcome of delivery was released: {}", delivery);
            deliveryError = new ProviderDeliveryReleasedException("Delivery failed: released by receiver");
            break;
        case Modified:
            LOG.trace("Outcome of delivery was modified: {}", delivery);
            Modified modified = (Modified) state;
            deliveryError = new ProviderDeliveryModifiedException("Delivery failed: failure at remote", modified);
            break;
        default:
            LOG.warn("Message send updated with unsupported state: {}", state);
    }

    if (deliveryError != null) {
        send.onFailure(deliveryError);
    }
}
 
Example #30
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);
    }
}