org.apache.qpid.proton.amqp.messaging.Rejected Java Examples

The following examples show how to use org.apache.qpid.proton.amqp.messaging.Rejected. 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: TenantClientImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the client fails if the Tenant service cannot be reached.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testGetTenantFailsWithRejectedRequest(final VertxTestContext ctx) {

    // GIVEN a client with no credit left
    final ProtonDelivery update = mock(ProtonDelivery.class);
    when(update.getRemoteState()).thenReturn(new Rejected());
    when(update.remotelySettled()).thenReturn(true);
    when(sender.send(any(Message.class), VertxMockSupport.anyHandler())).thenAnswer(invocation -> {
        final Handler<ProtonDelivery> dispositionHandler = invocation.getArgument(1);
        dispositionHandler.handle(update);
        return mock(ProtonDelivery.class);
    });

    // WHEN getting tenant information
    client.get("tenant").onComplete(ctx.failing(t -> {
        assertEquals(HttpURLConnection.HTTP_BAD_REQUEST, ((ServiceInvocationException) t).getErrorCode());
        // THEN the invocation fails and the span is marked as erroneous
        verify(span).setTag(eq(Tags.ERROR.getKey()), eq(Boolean.TRUE));
        // and the span is finished
        verify(span).finish();
        ctx.completeNow();
    }));
}
 
Example #2
Source File: TelemetrySenderImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the sender does not wait for the peer to settle and
 * accept a message before succeeding.
 */
@Test
public void testSendMessageDoesNotWaitForAcceptedOutcome() {

    // GIVEN a sender that has credit
    when(sender.sendQueueFull()).thenReturn(Boolean.FALSE);
    final DownstreamSender messageSender = new TelemetrySenderImpl(connection, sender, "tenant", "telemetry/tenant");
    final AtomicReference<Handler<ProtonDelivery>> handlerRef = new AtomicReference<>();
    doAnswer(invocation -> {
        handlerRef.set(invocation.getArgument(1));
        return mock(ProtonDelivery.class);
    }).when(sender).send(any(Message.class), VertxMockSupport.anyHandler());

    // WHEN trying to send a message
    final Future<ProtonDelivery> result = messageSender.send("device", "some payload", "application/text");
    // which gets rejected by the peer
    final ProtonDelivery rejected = mock(ProtonDelivery.class);
    when(rejected.remotelySettled()).thenReturn(Boolean.TRUE);
    when(rejected.getRemoteState()).thenReturn(new Rejected());
    handlerRef.get().handle(rejected);

    // THEN the resulting future is succeeded nevertheless
    assertTrue(result.succeeded());
    // and the message has been sent
    verify(sender).send(any(Message.class), eq(handlerRef.get()));
}
 
Example #3
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 #4
Source File: MappingAndDelegatingCommandHandlerTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies the behaviour of the <em>mapAndDelegateIncomingCommandMessage</em> method in a scenario where
 * the command shall get handled by another adapter instance, and the command message is invalid.
 */
@Test
public void testMapWithCommandHandlerOnAnotherInstanceWithInvalidMessage() {
    final String deviceId = "4711";

    // GIVEN a deviceId commandHandler registered for another adapter instance (not the local one)
    final String otherAdapterInstance = "otherAdapterInstance";
    when(commandTargetMapper.getTargetGatewayAndAdapterInstance(anyString(), anyString(), any()))
            .thenReturn(Future.succeededFuture(createTargetAdapterInstanceJson(deviceId, otherAdapterInstance)));

    // register local command handler - that shall not get used
    final AtomicReference<CommandContext> localHandlerCmdContextRef = new AtomicReference<>();
    adapterInstanceCommandHandler.putDeviceSpecificCommandHandler(Constants.DEFAULT_TENANT, deviceId, null, localHandlerCmdContextRef::set);

    // WHEN mapping and delegating the invalid command message
    final Message message = getValidCommandMessage(deviceId);
    message.setSubject(null); // make the message invalid
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    mappingAndDelegatingCommandHandler.mapAndDelegateIncomingCommandMessage(Constants.DEFAULT_TENANT, delivery, message);

    // THEN the delivery gets REJECTED
    verify(delivery).disposition(any(Rejected.class), eq(true));
    assertThat(localHandlerCmdContextRef.get()).isNull();
}
 
Example #5
Source File: MappingAndDelegatingCommandHandlerTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies the behaviour of the <em>mapAndDelegateIncomingCommandMessage</em> method in a scenario where
 * no command handling adapter instance is found for the command message device and the command message
 * is invalid.
 */
@Test
public void testMapWithNoAdapterInstanceFoundAndMessageInvalid() {
    final String deviceId = "4711";

    // GIVEN no registered commandHandler for the deviceId
    // but a deviceId commandHandler registered for the local adapter instance
    when(commandTargetMapper.getTargetGatewayAndAdapterInstance(anyString(), anyString(), any()))
            .thenReturn(Future.succeededFuture(createTargetAdapterInstanceJson(deviceId, adapterInstanceId)));

    // WHEN mapping and delegating an invalid command message
    final Message message = getValidCommandMessage(deviceId);
    message.setSubject(null); // make the message invalid
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    mappingAndDelegatingCommandHandler.mapAndDelegateIncomingCommandMessage(Constants.DEFAULT_TENANT, delivery, message);

    // THEN the disposition is REJECTED
    verify(delivery).disposition(any(Rejected.class), eq(true));
}
 
Example #6
Source File: MappingAndDelegatingCommandHandlerTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a command message with an address that contains a tenant which doesn't
 * match the scope of the command receiver link gets rejected.
 */
@SuppressWarnings("unchecked")
@Test
public void testMapForMessageHavingAddressWithInvalidTenant() {

    // GIVEN a command message with an address that contains an
    // invalid tenant
    final String deviceId = "4711";
    final Message message = getValidCommandMessage(deviceId);
    message.setAddress(String.format("%s/%s/%s", CommandConstants.COMMAND_ENDPOINT, "wrong-tenant", deviceId));

    // WHEN mapping and delegating the command
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    mappingAndDelegatingCommandHandler.mapAndDelegateIncomingCommandMessage(Constants.DEFAULT_TENANT, delivery, message);

    // THEN the disposition is REJECTED
    verify(delivery).disposition(
            argThat(state -> AmqpError.UNAUTHORIZED_ACCESS.equals(((Rejected) state).getError().getCondition())),
            eq(true));
    // and the message is not being delegated
    verify(sender, never()).send(any(Message.class), any(Handler.class));
}
 
Example #7
Source File: MappingAndDelegatingCommandHandlerTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a command message with an address that doesn't contain a device ID
 * gets rejected.
 */
@SuppressWarnings("unchecked")
@Test
public void testMapForMessageHavingAddressWithoutDeviceId() {

    // GIVEN a command message with an address that does not
    // contain a device ID
    final String deviceId = "4711";
    final Message message = getValidCommandMessage(deviceId);
    message.setAddress(String.format("%s/%s", CommandConstants.COMMAND_ENDPOINT, Constants.DEFAULT_TENANT));

    // WHEN mapping and delegating the command
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    mappingAndDelegatingCommandHandler.mapAndDelegateIncomingCommandMessage(Constants.DEFAULT_TENANT, delivery, message);

    // THEN the disposition is REJECTED
    verify(delivery).disposition(
            argThat(state -> Constants.AMQP_BAD_REQUEST.equals(((Rejected) state).getError().getCondition())),
            eq(true));
    // and the message is not being delegated
    verify(sender, never()).send(any(Message.class), any(Handler.class));
}
 
Example #8
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 #9
Source File: ProtonServerReceiverContext.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private Rejected createRejected(final Exception e) {
   ErrorCondition condition = new ErrorCondition();

   // Set condition
   if (e instanceof ActiveMQSecurityException) {
      condition.setCondition(AmqpError.UNAUTHORIZED_ACCESS);
   } else if (isAddressFull(e)) {
      condition.setCondition(AmqpError.RESOURCE_LIMIT_EXCEEDED);
   } else {
      condition.setCondition(Symbol.valueOf("failed"));
   }
   condition.setDescription(e.getMessage());

   Rejected rejected = new Rejected();
   rejected.setError(condition);
   return rejected;
}
 
Example #10
Source File: CredentialsClientImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the client fails if the credentials service cannot be reached.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testGetCredentialsFailsWithRejectedRequest(final VertxTestContext ctx) {

    // GIVEN a client with no credit left
    final ProtonDelivery update = mock(ProtonDelivery.class);
    when(update.getRemoteState()).thenReturn(new Rejected());
    when(update.remotelySettled()).thenReturn(true);
    when(sender.send(any(Message.class), VertxMockSupport.anyHandler())).thenAnswer(invocation -> {
        final Handler<ProtonDelivery> dispositionHandler = invocation.getArgument(1);
        dispositionHandler.handle(update);
        return mock(ProtonDelivery.class);
    });

    // WHEN getting credentials
    client.get(CredentialsConstants.SECRETS_TYPE_HASHED_PASSWORD, "test-auth")
            .onComplete(ctx.failing(t -> {
                assertEquals(HttpURLConnection.HTTP_BAD_REQUEST,
                        ((ServiceInvocationException) t).getErrorCode());
                // THEN the invocation fails and the span is marked as erroneous
                verify(span).setTag(eq(Tags.ERROR.getKey()), eq(Boolean.TRUE));
                // and the span is finished
                verify(span).finish();
                ctx.completeNow();
            }));
}
 
Example #11
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 #12
Source File: CommandAndControlAmqpIT.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private ProtonMessageHandler createRejectingCommandConsumer(final VertxTestContext ctx, final ProtonReceiver receiver) {
    return (delivery, msg) -> {
        ctx.verify(() -> {
            assertThat(msg.getReplyTo()).isNotNull();
            assertThat(msg.getSubject()).isNotNull();
            assertThat(msg.getCorrelationId()).isNotNull();
        });
        final String command = msg.getSubject();
        final Object correlationId = msg.getCorrelationId();
        log.debug("received command [name: {}, reply-to: {}, correlation-id: {}]", command, msg.getReplyTo(), correlationId);
        final Rejected rejected = new Rejected();
        rejected.setError(new ErrorCondition(Constants.AMQP_BAD_REQUEST, REJECTED_COMMAND_ERROR_MESSAGE));
        delivery.disposition(rejected, true);
        receiver.flow(1);
    };
}
 
Example #13
Source File: AmqpTransactionCoordinatorBuilder.java    From qpid-jms with Apache License 2.0 6 votes vote down vote up
@Override
protected Sender createEndpoint(JmsSessionInfo resourceInfo) {
    Coordinator coordinator = new Coordinator();
    coordinator.setCapabilities(TxnCapability.LOCAL_TXN);

    Symbol[] outcomes = new Symbol[]{ Accepted.DESCRIPTOR_SYMBOL, Rejected.DESCRIPTOR_SYMBOL, Released.DESCRIPTOR_SYMBOL, Modified.DESCRIPTOR_SYMBOL };

    Source source = new Source();
    source.setOutcomes(outcomes);

    String coordinatorName = "qpid-jms:coordinator:" + resourceInfo.getId().toString();

    Sender sender = getParent().getSession().getEndpoint().sender(coordinatorName);
    sender.setSource(source);
    sender.setTarget(coordinator);
    sender.setSenderSettleMode(SenderSettleMode.UNSETTLED);
    sender.setReceiverSettleMode(ReceiverSettleMode.FIRST);

    return sender;
}
 
Example #14
Source File: AmqpUploadTestBase.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that a message containing a payload which has the <em>emtpy notification</em>
 * content type is rejected by the adapter.
 *
 * @param context The Vert.x context for running asynchronous tests.
 * @throws InterruptedException if test is interrupted while running.
 */
@Test
@Timeout(timeUnit = TimeUnit.SECONDS, value = 10)
public void testAdapterRejectsBadInboundMessage(final VertxTestContext context) throws InterruptedException {

    final String tenantId = helper.getRandomTenantId();
    final String deviceId = helper.getRandomDeviceId(tenantId);

    final VertxTestContext setup = new VertxTestContext();

    setupProtocolAdapter(tenantId, deviceId, false)
    .map(s -> {
        sender = s;
        return s;
    })
    .onComplete(setup.completing());

    assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue();
    if (setup.failed()) {
        context.failNow(setup.causeOfFailure());
        return;
    }

    final Message msg = ProtonHelper.message("some payload");
    msg.setContentType(EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION);
    msg.setAddress(getEndpointName());
    sender.send(msg, delivery -> {

        context.verify(() -> {
            assertThat(delivery.getRemoteState()).isInstanceOf(Rejected.class);
            final Rejected rejected = (Rejected) delivery.getRemoteState();
            final ErrorCondition error = rejected.getError();
            assertThat((Object) error.getCondition()).isEqualTo(Constants.AMQP_BAD_REQUEST);
        });
        context.completeNow();
    });

}
 
Example #15
Source File: AmqpSourceBridgeEndpoint.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
/**
 * Send a "rejected" delivery to the AMQP remote sender
 *
 * @param linkName AMQP link name
 * @param delivery AMQP delivery
 * @param cause exception related to the rejection cause
 */
private void rejectedDelivery(String linkName, ProtonDelivery delivery, Throwable cause) {

    Rejected rejected = new Rejected();
    rejected.setError(new ErrorCondition(Symbol.valueOf(AmqpBridge.AMQP_ERROR_SEND_TO_KAFKA),
            cause.getMessage()));
    delivery.disposition(rejected, true);
    log.debug("Delivery sent [rejected] on link {}", linkName);
}
 
Example #16
Source File: AmqpBridgeSender.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
public void run(Vertx vertx) {

            ProtonClient client = ProtonClient.create(vertx);

            client.connect(AmqpBridgeSender.BRIDGE_HOST, AmqpBridgeSender.BRIDGE_PORT, ar -> {
                if (ar.succeeded()) {

                    this.connection = ar.result();
                    this.connection.open();

                    log.info("Connected as {}", this.connection.getContainer());

                    this.sender = this.connection.createSender(ExampleOne.TOPIC);
                    this.sender.open();

                    String topic = ExampleOne.TOPIC;
                    Message message = ProtonHelper.message(topic, "Simple message from " + this.connection.getContainer());

                    this.sender.send(ProtonHelper.tag("my_tag"), message, delivery -> {
                        log.info("Message delivered {}", delivery.getRemoteState());
                        if (delivery.getRemoteState() instanceof Rejected) {
                            Rejected rejected = (Rejected) delivery.getRemoteState();
                            log.info("... but rejected {} {}", rejected.getError().getCondition(), rejected.getError().getDescription());
                        }
                    });
                } else {
                    log.info("Error on connection ... {}", ar.cause());
                }
            });

            try {
                System.in.read();

                this.sender.close();
                this.connection.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
Example #17
Source File: AmqpProducerBuilder.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
@Override
protected Sender createEndpoint(JmsProducerInfo resourceInfo) {
    JmsDestination destination = resourceInfo.getDestination();
    AmqpConnection connection = getParent().getConnection();

    String targetAddress = AmqpDestinationHelper.getDestinationAddress(destination, connection);

    Symbol[] outcomes = new Symbol[]{ Accepted.DESCRIPTOR_SYMBOL, Rejected.DESCRIPTOR_SYMBOL, Released.DESCRIPTOR_SYMBOL, Modified.DESCRIPTOR_SYMBOL };
    String sourceAddress = resourceInfo.getId().toString();
    Source source = new Source();
    source.setAddress(sourceAddress);
    source.setOutcomes(outcomes);
    // TODO: default outcome. Accepted normally, Rejected for transaction controller?

    Target target = new Target();
    target.setAddress(targetAddress);
    Symbol typeCapability =  AmqpDestinationHelper.toTypeCapability(destination);
    if (typeCapability != null) {
        target.setCapabilities(typeCapability);
    }

    String senderName = "qpid-jms:sender:" + sourceAddress + ":" + targetAddress;

    Sender sender = getParent().getEndpoint().sender(senderName);
    sender.setSource(source);
    sender.setTarget(target);
    if (resourceInfo.isPresettle()) {
        sender.setSenderSettleMode(SenderSettleMode.SETTLED);
    } else {
        sender.setSenderSettleMode(SenderSettleMode.UNSETTLED);
    }
    sender.setReceiverSettleMode(ReceiverSettleMode.FIRST);

    if (!connection.getProperties().isDelayedDeliverySupported()) {
        validateDelayedDeliveryLinkCapability = true;
        sender.setDesiredCapabilities(new Symbol[] { AmqpSupport.DELAYED_DELIVERY });
    }

    return sender;
}
 
Example #18
Source File: RejectedType.java    From qpid-proton-j with Apache License 2.0 5 votes vote down vote up
public Rejected newInstance(Object described)
{
    List l = (List) described;

    Rejected o = new Rejected();

    switch(1 - l.size())
    {
        case 0:
            o.setError( (ErrorCondition) l.get( 0 ) );
    }


    return o;
}
 
Example #19
Source File: AmqpFlowControlFailTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Parameterized.Parameters(name = "useModified={0}")
public static Collection<Object[]> parameters() {
   return Arrays.asList(new Object[][] {
         {true, new Symbol[]{Accepted.DESCRIPTOR_SYMBOL, Rejected.DESCRIPTOR_SYMBOL, Modified.DESCRIPTOR_SYMBOL}, "failure at remote"},
         {true, new Symbol[]{Accepted.DESCRIPTOR_SYMBOL, Rejected.DESCRIPTOR_SYMBOL}, "[condition = amqp:resource-limit-exceeded]"},
         {false, new Symbol[]{Accepted.DESCRIPTOR_SYMBOL, Rejected.DESCRIPTOR_SYMBOL, Modified.DESCRIPTOR_SYMBOL}, "[condition = amqp:resource-limit-exceeded]"},
         {false, new Symbol[]{}, "[condition = amqp:resource-limit-exceeded]"}
   });
}
 
Example #20
Source File: AmqpReceiver.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
/**
 * Reject a message that was dispatched under the given Delivery instance.
 *
 * @param delivery
 *        the Delivery instance to reject.
 * @throws IOException
 *         if an error occurs while sending the release.
 */
public void reject(final Delivery delivery) throws IOException {
   checkClosed();

   if (delivery == null) {
      throw new IllegalArgumentException("Delivery to release cannot be null");
   }

   final ClientFuture request = new ClientFuture();
   session.getScheduler().execute(new Runnable() {

      @Override
      public void run() {
         checkClosed();
         try {
            if (!delivery.isSettled()) {
               delivery.disposition(new Rejected());
               delivery.settle();
               session.pumpToProtonTransport(request);
            }
            request.onSuccess();
         } catch (Exception e) {
            request.onFailure(e);
         }
      }
   });

   request.sync();
}
 
Example #21
Source File: AmqpReceiver.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
protected void configureSource(Source source) {
   Map<Symbol, DescribedType> filters = new HashMap<>();
   Symbol[] outcomes = new Symbol[] {Accepted.DESCRIPTOR_SYMBOL, Rejected.DESCRIPTOR_SYMBOL, Released.DESCRIPTOR_SYMBOL, Modified.DESCRIPTOR_SYMBOL};

   if (getSubscriptionName() != null && !getSubscriptionName().isEmpty()) {
      source.setExpiryPolicy(TerminusExpiryPolicy.NEVER);
      source.setDurable(TerminusDurability.UNSETTLED_STATE);
      source.setDistributionMode(COPY);
   } else {
      source.setDurable(TerminusDurability.NONE);
      source.setExpiryPolicy(TerminusExpiryPolicy.LINK_DETACH);
   }

   source.setOutcomes(outcomes);

   Modified modified = new Modified();
   modified.setDeliveryFailed(true);
   modified.setUndeliverableHere(false);

   source.setDefaultOutcome(modified);

   if (isNoLocal()) {
      filters.put(NO_LOCAL_NAME, AmqpNoLocalFilter.NO_LOCAL);
   }

   if (getSelector() != null && !getSelector().trim().equals("")) {
      filters.put(JMS_SELECTOR_NAME, new AmqpJmsSelectorFilter(getSelector()));
   }

   if (!filters.isEmpty()) {
      source.setFilter(filters);
   }
}
 
Example #22
Source File: ProtonTransactionHandler.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private Rejected createRejected(Symbol amqpError, String message) {
   Rejected rejected = new Rejected();
   ErrorCondition condition = new ErrorCondition();
   condition.setCondition(amqpError);
   condition.setDescription(message);
   rejected.setError(condition);
   return rejected;
}
 
Example #23
Source File: ProtonSessionImpl.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
@Override
public ProtonReceiver createReceiver(String address, ProtonLinkOptions receiverOptions) {
  Receiver receiver = session.receiver(getOrCreateLinkName(receiverOptions));

  Symbol[] outcomes = new Symbol[] { Accepted.DESCRIPTOR_SYMBOL, Rejected.DESCRIPTOR_SYMBOL,
      Released.DESCRIPTOR_SYMBOL, Modified.DESCRIPTOR_SYMBOL };

  Source source = new Source();
  source.setAddress(address);
  source.setOutcomes(outcomes);
  source.setDefaultOutcome(Released.getInstance());
  if(receiverOptions.isDynamic()) {
    source.setDynamic(true);
  }

  Target target = new Target();

  receiver.setSource(source);
  receiver.setTarget(target);

  ProtonReceiverImpl r = new ProtonReceiverImpl(receiver);
  r.openHandler((result) -> {
    LOG.trace("Receiver open completed");
  });
  r.closeHandler((result) -> {
    if (result.succeeded()) {
      LOG.trace("Receiver closed");
    } else {
      LOG.warn("Receiver closed with error", result.cause());
    }
  });

  // Default to at-least-once
  r.setQoS(ProtonQoS.AT_LEAST_ONCE);

  return r;
}
 
Example #24
Source File: ProtonSessionImpl.java    From vertx-proton with Apache License 2.0 5 votes vote down vote up
@Override
public ProtonSender createSender(String address, ProtonLinkOptions senderOptions) {
  Sender sender = session.sender(getOrCreateLinkName(senderOptions));

  Symbol[] outcomes = new Symbol[] { Accepted.DESCRIPTOR_SYMBOL, Rejected.DESCRIPTOR_SYMBOL,
      Released.DESCRIPTOR_SYMBOL, Modified.DESCRIPTOR_SYMBOL };
  Source source = new Source();
  source.setOutcomes(outcomes);

  Target target = new Target();
  target.setAddress(address);
  if(senderOptions.isDynamic()) {
    target.setDynamic(true);
  }

  sender.setSource(source);
  sender.setTarget(target);

  ProtonSenderImpl s = new ProtonSenderImpl(sender);
  if (address == null) {
    s.setAnonymousSender(true);
  }

  s.openHandler((result) -> {
    LOG.trace("Sender open completed");
  });
  s.closeHandler((result) -> {
    if (result.succeeded()) {
      LOG.trace("Sender closed");
    } else {
      LOG.warn("Sender closed with error", result.cause());
    }
  });

  // Default to at-least-once
  s.setQoS(ProtonQoS.AT_LEAST_ONCE);

  return s;
}
 
Example #25
Source File: CommandContext.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Settles the command message with the <em>rejected</em> outcome.
 * <p>
 * This method also finishes the OpenTracing span returned by
 * {@link #getCurrentSpan()}.
 *
 * @param errorCondition The error condition to send in the disposition frame (may be {@code null}).
 */
public void reject(final ErrorCondition errorCondition) {
    final Rejected rejected = new Rejected();
    if (errorCondition != null) {
        rejected.setError(errorCondition);
    }
    delivery.disposition(rejected, true);
    TracingHelper.logError(currentSpan, "rejected command for device"
            + ((errorCondition != null && errorCondition.getDescription() != null) ? "; error: " + errorCondition.getDescription() : ""));
    currentSpan.finish();
}
 
Example #26
Source File: DeviceConnectionClientImplTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that a client invocation of the <em>get-last-known-gateway</em> operation fails
 * if the device connection service cannot be reached.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testGetLastKnownGatewayForDeviceFailsWithRejectedRequest(final VertxTestContext ctx) {

    // GIVEN a client with no credit left
    final ProtonDelivery update = mock(ProtonDelivery.class);
    when(update.getRemoteState()).thenReturn(new Rejected());
    when(update.remotelySettled()).thenReturn(true);
    when(sender.send(any(Message.class), VertxMockSupport.anyHandler())).thenAnswer(invocation -> {
        final Handler<ProtonDelivery> dispositionHandler = invocation.getArgument(1);
        dispositionHandler.handle(update);
        return mock(ProtonDelivery.class);
    });

    // WHEN getting last known gateway information
    client.getLastKnownGatewayForDevice("deviceId", span.context())
            .onComplete(ctx.failing(t -> {
                assertThat(((ServiceInvocationException) t).getErrorCode()).isEqualTo(HttpURLConnection.HTTP_BAD_REQUEST);
                ctx.verify(() -> {
                    // THEN the invocation fails and the span is marked as erroneous
                    verify(span).setTag(eq(Tags.ERROR.getKey()), eq(Boolean.TRUE));
                    // and the span is finished
                    verify(span).finish();
                });
                ctx.completeNow();
            }));
}
 
Example #27
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 #28
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 #29
Source File: AbstractRequestResponseClientTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the client fails the result handler if the peer rejects
 * the request message.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCreateAndSendRequestFailsOnRejectedMessage(final VertxTestContext ctx) {

    // GIVEN a request-response client that times out requests after 200 ms
    client.setRequestTimeout(200);

    // WHEN sending a request message with some headers and payload
    final JsonObject payload = new JsonObject().put("key", "value");
    client.createAndSendRequest(
            "get",
            payload.toBuffer(),
            ctx.failing(t -> {
                // THEN the result handler is failed with a 400 status code
                assertFailureCause(ctx, span, t, HttpURLConnection.HTTP_BAD_REQUEST);
                ctx.completeNow();
            }),
            span);
    // and the peer rejects the message
    final Rejected rejected = new Rejected();
    rejected.setError(ProtonHelper.condition(Constants.AMQP_BAD_REQUEST, "request message is malformed"));
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    when(delivery.getRemoteState()).thenReturn(rejected);
    @SuppressWarnings("unchecked")
    final ArgumentCaptor<Handler<ProtonDelivery>> dispositionHandlerCaptor = ArgumentCaptor.forClass(Handler.class);
    verify(sender).send(any(Message.class), dispositionHandlerCaptor.capture());
    dispositionHandlerCaptor.getValue().handle(delivery);
}
 
Example #30
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);
}