Java Code Examples for org.apache.qpid.proton.message.Message#setSubject()

The following examples show how to use org.apache.qpid.proton.message.Message#setSubject() . 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: 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 2
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 3
Source File: AdapterInstanceCommandHandlerTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Test
void testHandleCommandMessageWithHandlerForGatewayAndSpecificDevice() {
    final String deviceId = "4711";
    final String gatewayId = "gw-1";
    final String correlationId = "the-correlation-id";
    final Message message = ProtonHelper.message("input data");
    message.setAddress(String.format("%s/%s/%s",
            CommandConstants.COMMAND_ENDPOINT, Constants.DEFAULT_TENANT, deviceId));
    message.setSubject("doThis");
    message.setCorrelationId(correlationId);

    final Handler<CommandContext> commandHandler = VertxMockSupport.mockHandler();
    adapterInstanceCommandHandler.putDeviceSpecificCommandHandler(Constants.DEFAULT_TENANT, deviceId, gatewayId, commandHandler);

    adapterInstanceCommandHandler.handleCommandMessage(message, mock(ProtonDelivery.class));

    final ArgumentCaptor<CommandContext> commandContextCaptor = ArgumentCaptor.forClass(CommandContext.class);
    verify(commandHandler).handle(commandContextCaptor.capture());
    assertThat(commandContextCaptor.getValue()).isNotNull();
    // assert that command is directed at the gateway
    assertThat(commandContextCaptor.getValue().getCommand().getDeviceId()).isEqualTo(gatewayId);
    assertThat(commandContextCaptor.getValue().getCommand().getOriginalDeviceId()).isEqualTo(deviceId);
}
 
Example 4
Source File: ProtonRequestClientTest.java    From enmasse with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequest() throws Exception {
    try (ProtonRequestClient client = new ProtonRequestClient(Vertx.vertx(), "test-client")) {
        CompletableFuture<Void> future = new CompletableFuture<>();
        client.connect("127.0.0.1", 12347, future);
        future.get(10, TimeUnit.SECONDS);
        Message request = Message.Factory.create();
        request.setAddress("health-check");
        request.setBody(new AmqpValue("[{\"name\":\"myqueue\",\"store_and_forward\":true,\"multicast\":false}]"));
        request.setSubject("health-check");
        Message response = client.request(request, 10, TimeUnit.SECONDS);
        assertTrue((Boolean) ((AmqpValue) response.getBody()).getValue());

        future = new CompletableFuture<>();
        client.connect("127.0.0.1", 12347, future);
        future.get(10, TimeUnit.SECONDS);
    }
}
 
Example 5
Source File: CommandTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a command can be created from a valid message.
 * Verifies that the replyToId are build up of all segments behind the tenant.
 */
@Test
public void testFromMessageSucceeds() {
    final String replyToId = "the-reply-to-id";
    final String correlationId = "the-correlation-id";
    final Message message = ProtonHelper.message("input data");
    message.setAddress(String.format("%s/%s/%s",
            CommandConstants.COMMAND_ENDPOINT, Constants.DEFAULT_TENANT, "4711"));
    message.setSubject("doThis");
    message.setCorrelationId(correlationId);
    message.setReplyTo(String.format("%s/%s/%s/%s",
            CommandConstants.NORTHBOUND_COMMAND_RESPONSE_ENDPOINT, Constants.DEFAULT_TENANT, "4711", replyToId));
    final boolean replyToContainedDeviceId = true;
    final String replyToOptionsBitFlag = Command.encodeReplyToOptions(replyToContainedDeviceId);
    final Command cmd = Command.from(message, Constants.DEFAULT_TENANT, "4711");
    assertTrue(cmd.isValid());
    assertThat(cmd.getName()).isEqualTo("doThis");
    assertThat(cmd.getDeviceId()).isEqualTo("4711");
    assertThat(cmd.getOriginalDeviceId()).isEqualTo("4711");
    assertThat(cmd.getReplyToId()).isEqualTo(String.format("4711/%s", replyToId));
    assertThat(cmd.getReplyToEndpoint()).isEqualTo(CommandConstants.NORTHBOUND_COMMAND_RESPONSE_ENDPOINT);
    assertThat(cmd.getCorrelationId()).isEqualTo(correlationId);
    assertFalse(cmd.isOneWay());
    assertThat(cmd.getCommandMessage().getReplyTo()).isEqualTo(String.format("%s/%s/%s/%s%s",
            CommandConstants.COMMAND_RESPONSE_ENDPOINT, Constants.DEFAULT_TENANT, "4711", replyToOptionsBitFlag, replyToId));
}
 
Example 6
Source File: CommandTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that a command can be created from a valid message having device-id as part of the reply-to address.
 * Verifies that the reply-to address contains the device-id and the reply-id is prefixed with flag 0.
 */
@Test
public void testForReplyToWithDeviceId() {
    final String replyToId = "the-reply-to-id";
    final String correlationId = "the-correlation-id";
    final Message message = ProtonHelper.message("input data");
    message.setAddress(String.format("%s/%s/%s",
            CommandConstants.COMMAND_ENDPOINT, Constants.DEFAULT_TENANT, "4711"));
    message.setSubject("doThis");
    message.setCorrelationId(correlationId);
    message.setReplyTo(String.format("%s/%s/%s/%s",
            CommandConstants.NORTHBOUND_COMMAND_RESPONSE_ENDPOINT, Constants.DEFAULT_TENANT, "4711", replyToId));
    final String replyToOptionsBitFlag = Command.encodeReplyToOptions(true);
    final Command cmd = Command.from(message, Constants.DEFAULT_TENANT, "4711");
    assertTrue(cmd.isValid());
    assertThat(cmd.getReplyToId()).isEqualTo(String.format("4711/%s", replyToId));
    assertThat(cmd.getCommandMessage()).isNotNull();
    assertThat(cmd.getCommandMessage().getReplyTo()).isNotNull();
    assertThat(cmd.getCommandMessage().getReplyTo()).isEqualTo(String.format("%s/%s/%s/%s%s",
            CommandConstants.COMMAND_RESPONSE_ENDPOINT, Constants.DEFAULT_TENANT, "4711", replyToOptionsBitFlag, replyToId));
}
 
Example 7
Source File: TenantMessageFilterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Message givenAMessageHavingProperties(final TenantConstants.TenantAction action) {
    final Message msg = ProtonHelper.message();
    msg.setMessageId("msg");
    msg.setReplyTo("reply");
    msg.setSubject(action.toString());
    return msg;
}
 
Example 8
Source File: MappingAndDelegatingCommandHandlerTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Message getValidCommandMessage(final String deviceId) {
    final Message message = ProtonHelper.message("input data");
    message.setAddress(String.format("%s/%s/%s",
            CommandConstants.COMMAND_ENDPOINT, Constants.DEFAULT_TENANT, deviceId));
    message.setSubject("doThis");
    message.setCorrelationId("the-correlation-id");
    return message;
}
 
Example 9
Source File: AmqpMessageCoderTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Test
public void encodeDecode() throws Exception {
  Message message = Message.Factory.create();
  message.setBody(new AmqpValue("body"));
  message.setAddress("address");
  message.setSubject("test");
  AmqpMessageCoder coder = AmqpMessageCoder.of();

  Message clone = CoderUtils.clone(coder, message);

  assertEquals("AmqpValue{body}", clone.getBody().toString());
  assertEquals("address", clone.getAddress());
  assertEquals("test", clone.getSubject());
}
 
Example 10
Source File: AmqpMessageCoderTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Test
public void encodeDecodeLargeMessage() throws Exception {
  Message message = Message.Factory.create();
  message.setAddress("address");
  message.setSubject("subject");
  String body = Joiner.on("").join(Collections.nCopies(32 * 1024 * 1024, " "));
  message.setBody(new AmqpValue(body));

  AmqpMessageCoder coder = AmqpMessageCoder.of();

  Message clone = CoderUtils.clone(coder, message);

  clone.getBody().toString().equals(message.getBody().toString());
}
 
Example 11
Source File: AbstractRequestResponseClientTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the client succeeds the result handler if the peer accepts
 * the request message for a one-way request.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testSendOneWayRequestSucceedsOnAcceptedMessage(final VertxTestContext ctx) {

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

    // WHEN sending a one-way request message with some headers and payload
    final JsonObject payload = new JsonObject().put("key", "value");
    final Map<String, Object> applicationProps = new HashMap<>();

    final Message request = ProtonHelper.message();
    request.setMessageId("12345");
    request.setCorrelationId("23456");
    request.setSubject("aRequest");
    request.setApplicationProperties(new ApplicationProperties(applicationProps));
    MessageHelper.setPayload(request, "application/json", payload.toBuffer());

    final SpanContext spanContext = mock(SpanContext.class);
    final Span span = mock(Span.class);
    when(span.context()).thenReturn(spanContext);

    client.sendRequest(request, ctx.succeeding(t -> {
        // THEN the result handler is succeeded
        ctx.completeNow();
    }), null, span);
    // and the peer accepts the message
    final Accepted accepted = new Accepted();
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    when(delivery.getRemoteState()).thenReturn(accepted);
    @SuppressWarnings("unchecked")
    final ArgumentCaptor<Handler<ProtonDelivery>> dispositionHandlerCaptor = ArgumentCaptor.forClass(Handler.class);
    verify(sender).send(any(Message.class), dispositionHandlerCaptor.capture());
    dispositionHandlerCaptor.getValue().handle(delivery);
}
 
Example 12
Source File: RequestResponseEndpointTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void testHandleMessageSendsResponseWithStatusCode(final Throwable error, final int expectedStatus) {

    final Message msg = ProtonHelper.message();
    msg.setSubject("get");
    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.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 is accepted
    verify(delivery).disposition(argThat(d -> d instanceof Accepted), eq(Boolean.TRUE));
    // 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 invocation times out
    replyHandler.getValue().handle(Future.failedFuture(error));

    // THEN a response with status 500 is sent to the client
    verify(sender).send(argThat(m -> hasStatusCode(m, expectedStatus)));
    verify(receiver).flow(1);
}
 
Example 13
Source File: AmqpJmsMessageFacadeTest.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
/**
 * Test that {@link AmqpJmsMessageFacade#getType()} returns the expected value
 * for a message received with the message Subject set.
 *
 * @throws Exception if an error occurs during the test.
 */
@Test
public void testGetJMSTypeWithReceivedMessage() throws Exception {
    String myJMSType = "myJMSType";

    Message message = Proton.message();
    message.setSubject(myJMSType);
    AmqpJmsMessageFacade amqpMessageFacade = createReceivedMessageFacade(createMockAmqpConsumer(), message);

    assertEquals("JMSType value was not as expected", myJMSType, amqpMessageFacade.getType());
}
 
Example 14
Source File: AmqpMessageCoderTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Test
public void encodeDecodeTooMuchLargerMessage() throws Exception {
  thrown.expect(CoderException.class);
  Message message = Message.Factory.create();
  message.setAddress("address");
  message.setSubject("subject");
  String body = Joiner.on("").join(Collections.nCopies(64 * 1024 * 1024, " "));
  message.setBody(new AmqpValue(body));

  AmqpMessageCoder coder = AmqpMessageCoder.of();

  byte[] encoded = CoderUtils.encodeToByteArray(coder, message);
}
 
Example 15
Source File: CredentialsMessageFilterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private static Message givenAValidMessageWithoutBody(final CredentialsConstants.CredentialsAction action) {
    final Message msg = ProtonHelper.message();
    msg.setMessageId("msg");
    msg.setReplyTo("reply");
    msg.setSubject(action.toString());
    return msg;
}
 
Example 16
Source File: RegistrationMessageFilterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private static Message givenAMessageHavingProperties(final String deviceId, final String action) {
    final Message msg = ProtonHelper.message();
    msg.setMessageId("msg-id");
    msg.setReplyTo("reply");
    msg.setSubject(action);
    if (deviceId != null) {
        MessageHelper.addDeviceId(msg, deviceId);
    }
    return msg;
}
 
Example 17
Source File: CommandClientImpl.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Future<Void> sendOneWayCommand(
        final String deviceId,
        final String command,
        final String contentType,
        final Buffer data,
        final Map<String, Object> properties) {

    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(command);

    final Span currentSpan = newChildSpan(null, command);
    TracingHelper.setDeviceTags(currentSpan, getTenantId(), deviceId);

    if (sender.isOpen()) {
        final Promise<BufferResult> responseTracker = Promise.promise();
        final Message request = ProtonHelper.message();

        AbstractHonoClient.setApplicationProperties(request, properties);

        final String messageId = createMessageId();
        request.setAddress(getTargetAddress(getTenantId(), deviceId));
        request.setMessageId(messageId);
        request.setSubject(command);

        MessageHelper.setPayload(request, contentType, data);
        sendRequest(request, responseTracker, null, currentSpan);

        return responseTracker.future()
                .recover(t -> {
                    Tags.HTTP_STATUS.set(currentSpan, ServiceInvocationException.extractStatusCode(t));
                    TracingHelper.logError(currentSpan, t);
                    currentSpan.finish();
                    return Future.failedFuture(t);
                }).map(ignore -> {
                    Tags.HTTP_STATUS.set(currentSpan, HttpURLConnection.HTTP_ACCEPTED);
                    currentSpan.finish();
                    return null;
                });
    } else {
        Tags.HTTP_STATUS.set(currentSpan, HttpURLConnection.HTTP_UNAVAILABLE);
        TracingHelper.logError(currentSpan, "sender link is not open");
        currentSpan.finish();
        return Future.failedFuture(new ServerErrorException(
                HttpURLConnection.HTTP_UNAVAILABLE, "sender link is not open"));
    }
}
 
Example 18
Source File: CommandAndControlMqttIT.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Verifies that the adapter rejects malformed command messages sent by applications.
 *
 * @param endpointConfig The endpoints to use for sending/receiving commands.
 * @param ctx The vert.x test context.
 * @throws InterruptedException if not all commands and responses are exchanged in time.
 */
@ParameterizedTest(name = IntegrationTestSupport.PARAMETERIZED_TEST_NAME_PATTERN)
@MethodSource("allCombinations")
@Timeout(timeUnit = TimeUnit.SECONDS, value = 20)
public void testSendCommandFailsForMalformedMessage(
        final MqttCommandEndpointConfiguration endpointConfig,
        final VertxTestContext ctx) throws InterruptedException {

    final VertxTestContext setup = new VertxTestContext();
    final Checkpoint ready = setup.checkpoint(3);

    final String commandTargetDeviceId = endpointConfig.isSubscribeAsGateway()
            ? helper.setupGatewayDeviceBlocking(tenantId, deviceId, 5)
            : deviceId;

    helper.registry
            .addDeviceForTenant(tenantId, tenant, deviceId, password)
            .compose(ok -> connectToAdapter(IntegrationTestSupport.getUsername(deviceId, tenantId), password))
            .compose(ok -> createConsumer(tenantId, msg -> {
                // expect empty notification with TTD -1
                setup.verify(() -> assertThat(msg.getContentType()).isEqualTo(EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION));
                final TimeUntilDisconnectNotification notification = TimeUntilDisconnectNotification
                        .fromMessage(msg).orElse(null);
                LOGGER.info("received notification [{}]", notification);
                if (notification.getTtd() == -1) {
                    ready.flag();
                }
            }))
            .compose(conAck -> subscribeToCommands(commandTargetDeviceId, msg -> {
                setup.failNow(new IllegalStateException("should not have received command"));
            }, endpointConfig, MqttQoS.AT_MOST_ONCE))
            .onComplete(ctx.succeeding(ok -> ready.flag()));

    final AtomicReference<MessageSender> sender = new AtomicReference<>();
    final String linkTargetAddress = endpointConfig.getSenderLinkTargetAddress(tenantId);

    helper.applicationClientFactory.createGenericMessageSender(linkTargetAddress)
    .map(s -> {
        LOGGER.debug("created generic sender for sending commands [target address: {}]", linkTargetAddress);
        sender.set(s);
        ready.flag();
        return s;
    });

    assertThat(setup.awaitCompletion(15, TimeUnit.SECONDS)).isTrue();
    if (setup.failed()) {
        ctx.failNow(setup.causeOfFailure());
    }

    final Checkpoint failedAttempts = ctx.checkpoint(2);
    final String messageAddress = endpointConfig.getCommandMessageAddress(tenantId, commandTargetDeviceId);

    LOGGER.debug("sending command message lacking subject");
    final Message messageWithoutSubject = ProtonHelper.message("input data");
    messageWithoutSubject.setAddress(messageAddress);
    messageWithoutSubject.setMessageId("message-id");
    messageWithoutSubject.setReplyTo("reply/to/address");
    sender.get().sendAndWaitForOutcome(messageWithoutSubject).onComplete(ctx.failing(t -> {
        ctx.verify(() -> assertThat(t).isInstanceOf(ClientErrorException.class));
        failedAttempts.flag();
    }));

    LOGGER.debug("sending command message lacking message ID and correlation ID");
    final Message messageWithoutId = ProtonHelper.message("input data");
    messageWithoutId.setAddress(messageAddress);
    messageWithoutId.setSubject("setValue");
    messageWithoutId.setReplyTo("reply/to/address");
    sender.get().sendAndWaitForOutcome(messageWithoutId).onComplete(ctx.failing(t -> {
        ctx.verify(() -> assertThat(t).isInstanceOf(ClientErrorException.class));
        failedAttempts.flag();
    }));
}
 
Example 19
Source File: AmqpMessageTest.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
@Test
public void testMessageAttributes() {
    Map<String, Object> props = new LinkedHashMap<>();
    props.put("hello", "world");
    props.put("some", "content");
    Message message = message();
    message.setTtl(1);
    message.setDurable(true);
    message.setReplyTo("reply");
    ApplicationProperties apps = new ApplicationProperties(props);
    message.setApplicationProperties(apps);
    message.setContentType("text/plain");
    message.setCorrelationId("1234");
    message.setDeliveryCount(2);
    message.setExpiryTime(10000);
    message.setFooter(new Footer(props));
    message.setGroupId("some-group");
    message.setAddress("address");
    message.setCreationTime(System.currentTimeMillis());
    message.setSubject("subject");
    message.setUserId("username".getBytes());
    message.setPriority((short) 2);
    message.setBody(new AmqpValue("hello"));
    message.setMessageId("4321");

    AmqpMessage<?> msg = new AmqpMessage<>(new AmqpMessageImpl(message), null, null);
    assertThat(msg.getAddress()).isEqualTo("address");
    assertThat(msg.getApplicationProperties()).contains(entry("hello", "world"), entry("some", "content"));
    assertThat(msg.getContentType()).isEqualTo("text/plain");
    assertThat(msg.getCreationTime()).isNotZero();
    assertThat(msg.getDeliveryCount()).isEqualTo(2);
    assertThat(msg.getExpiryTime()).isEqualTo(10000);
    assertThat(msg.getGroupId()).isEqualTo("some-group");
    assertThat(msg.getTtl()).isEqualTo(1);
    assertThat(msg.getSubject()).isEqualTo("subject");
    assertThat(msg.getPriority()).isEqualTo((short) 2);
    assertThat(((AmqpValue) msg.getBody()).getValue()).isEqualTo("hello");
    assertThat(msg.getCorrelationId()).isEqualTo("1234");
    assertThat(msg.getMessageId()).isEqualTo("4321");
    assertThat(msg.getHeader()).isNotNull();
    assertThat(msg.isDurable()).isTrue();
    assertThat(msg.getError().name()).isEqualTo("OK");
    assertThat(msg.getGroupSequence()).isZero();

}
 
Example 20
Source File: CommandAndControlAmqpIT.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Verifies that the adapter rejects malformed command messages sent by applications.
 *
 * @param endpointConfig The endpoints to use for sending/receiving commands.
 * @param ctx The vert.x test context.
 * @throws InterruptedException if not all commands and responses are exchanged in time.
 */
@ParameterizedTest(name = IntegrationTestSupport.PARAMETERIZED_TEST_NAME_PATTERN)
@MethodSource("allCombinations")
@Timeout(timeUnit = TimeUnit.SECONDS, value = 10)
public void testSendCommandFailsForMalformedMessage(
        final AmqpCommandEndpointConfiguration endpointConfig,
        final VertxTestContext ctx) throws InterruptedException {

    final String commandTargetDeviceId = endpointConfig.isSubscribeAsGateway()
            ? helper.setupGatewayDeviceBlocking(tenantId, deviceId, 5)
            : deviceId;

    final AtomicReference<MessageSender> sender = new AtomicReference<>();
    final String targetAddress = endpointConfig.getSenderLinkTargetAddress(tenantId);

    final VertxTestContext setup = new VertxTestContext();
    final Checkpoint preconditions = setup.checkpoint(2);

    connectToAdapter(tenantId, tenant, deviceId, password, () -> createEventConsumer(tenantId, msg -> {
        // expect empty notification with TTD -1
        ctx.verify(() -> assertThat(msg.getContentType()).isEqualTo(EventConstants.CONTENT_TYPE_EMPTY_NOTIFICATION));
        final TimeUntilDisconnectNotification notification = TimeUntilDisconnectNotification.fromMessage(msg).orElse(null);
        log.debug("received notification [{}]", notification);
        ctx.verify(() -> assertThat(notification).isNotNull());
        if (notification.getTtd() == -1) {
            preconditions.flag();
        }
    }))
    .compose(con -> subscribeToCommands(endpointConfig, tenantId, commandTargetDeviceId)
        .map(recv -> {
            recv.handler((delivery, msg) -> ctx
                    .failNow(new IllegalStateException("should not have received command")));
            return null;
        }))
    .compose(ok -> helper.applicationClientFactory.createGenericMessageSender(targetAddress))
    .map(s -> {
        log.debug("created generic sender for sending commands [target address: {}]", targetAddress);
        sender.set(s);
        preconditions.flag();
        return s;
    })
    .onComplete(setup.completing());

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

    final Checkpoint expectedFailures = ctx.checkpoint(2);

    log.debug("sending command message lacking subject");
    final Message messageWithoutSubject = ProtonHelper.message("input data");
    messageWithoutSubject.setAddress(endpointConfig.getCommandMessageAddress(tenantId, commandTargetDeviceId));
    messageWithoutSubject.setMessageId("message-id");
    messageWithoutSubject.setReplyTo("reply/to/address");
    sender.get().sendAndWaitForOutcome(messageWithoutSubject).onComplete(ctx.failing(t -> {
        ctx.verify(() -> assertThat(t).isInstanceOf(ClientErrorException.class));
        expectedFailures.flag();
    }));

    log.debug("sending command message lacking message ID and correlation ID");
    final Message messageWithoutId = ProtonHelper.message("input data");
    messageWithoutId.setAddress(endpointConfig.getCommandMessageAddress(tenantId, commandTargetDeviceId));
    messageWithoutId.setSubject("setValue");
    messageWithoutId.setReplyTo("reply/to/address");
    sender.get().sendAndWaitForOutcome(messageWithoutId).onComplete(ctx.failing(t -> {
        ctx.verify(() -> assertThat(t).isInstanceOf(ClientErrorException.class));
        expectedFailures.flag();
    }));
}