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

The following examples show how to use org.apache.qpid.proton.message.Message#setAddress() . 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: AdapterInstanceCommandHandlerTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Test
void testHandleCommandMessageWithHandlerForDevice() {
    final String deviceId = "4711";
    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, null, commandHandler);

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

    final ArgumentCaptor<CommandContext> commandContextCaptor = ArgumentCaptor.forClass(CommandContext.class);
    verify(commandHandler).handle(commandContextCaptor.capture());
    assertThat(commandContextCaptor.getValue()).isNotNull();
    assertThat(commandContextCaptor.getValue().getCommand().getDeviceId()).isEqualTo(deviceId);
}
 
Example 2
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 no 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 1.
 */
@Test
public void testForReplyToWithoutDeviceId() {
    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",
            CommandConstants.NORTHBOUND_COMMAND_RESPONSE_ENDPOINT, Constants.DEFAULT_TENANT, replyToId));
    final boolean replyToContainedDeviceId = false;
    final String replyToOptionsBitFlag = Command.encodeReplyToOptions(replyToContainedDeviceId);
    final Command cmd = Command.from(message, Constants.DEFAULT_TENANT, "4711");
    assertTrue(cmd.isValid());
    assertThat(cmd.getReplyToId()).isEqualTo(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 3
Source File: AsyncCommandClientImpl.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Future<Void> sendAsyncCommand(final String deviceId, final String command, final String contentType, final Buffer data,
        final String correlationId, final String replyId, final Map<String, Object> properties, final SpanContext context) {
    Objects.requireNonNull(command);
    Objects.requireNonNull(correlationId);
    Objects.requireNonNull(replyId);

    final Message message = ProtonHelper.message();
    message.setCorrelationId(correlationId);
    MessageHelper.setCreationTime(message);
    MessageHelper.setPayload(message, contentType, data);
    message.setSubject(command);
    message.setAddress(getTargetAddress(tenantId, deviceId));
    final String replyToAddress = String.format("%s/%s/%s", CommandConstants.NORTHBOUND_COMMAND_RESPONSE_ENDPOINT, tenantId, replyId);
    message.setReplyTo(replyToAddress);

    return sendAndWaitForOutcome(message, context).compose(ignore -> Future.succeededFuture());
}
 
Example 4
Source File: BlockingClientTest.java    From enmasse with Apache License 2.0 6 votes vote down vote up
@Test
public void testReceive() throws Exception {
    try (BlockingClient client = new BlockingClient("127.0.0.1", actualPort)) {
        Message m = Message.Factory.create();
        m.setAddress("testreceive");
        m.setBody(new AmqpValue("hello there"));
        outbox.put(m);

        List<Message> messages = client.recv("testsend", 1, 1, TimeUnit.MINUTES);
        assertThat(messages.size(), is(1));

        Message received = messages.get(0);
        assertNotNull(received);
        assertThat(received.getMessageId(), is(m.getMessageId()));
        assertThat(((AmqpValue) received.getBody()).getValue(), is("hello there"));
    }
}
 
Example 5
Source File: AmqpDefaultMessageConverter.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
@Override
public Message toMessage(String address, KafkaConsumerRecord<String, byte[]> record) {

    Message message = Proton.message();
    message.setAddress(address);

    // put message annotations about partition, offset and key (if not null)
    Map<Symbol, Object> map = new HashMap<>();
    map.put(Symbol.valueOf(AmqpBridge.AMQP_PARTITION_ANNOTATION), record.partition());
    map.put(Symbol.valueOf(AmqpBridge.AMQP_OFFSET_ANNOTATION), record.offset());
    map.put(Symbol.valueOf(AmqpBridge.AMQP_KEY_ANNOTATION), record.key());
    map.put(Symbol.valueOf(AmqpBridge.AMQP_TOPIC_ANNOTATION), record.topic());

    MessageAnnotations messageAnnotations = new MessageAnnotations(map);
    message.setMessageAnnotations(messageAnnotations);

    message.setBody(new Data(new Binary(record.value())));

    return message;
}
 
Example 6
Source File: AdapterInstanceCommandHandlerTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Test
void testHandleCommandMessageWithHandlerForGateway() {
    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);
    message.setApplicationProperties(
            new ApplicationProperties(Collections.singletonMap(MessageHelper.APP_PROPERTY_CMD_VIA, gatewayId)));

    final Handler<CommandContext> commandHandler = VertxMockSupport.mockHandler();
    adapterInstanceCommandHandler.putDeviceSpecificCommandHandler(Constants.DEFAULT_TENANT, gatewayId, null, 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 7
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 8
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 9
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 10
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 11
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 12
Source File: CommandResponseTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that creating a response fails for a message with an invalid address, having an empty id
 * after the replyToOptions bit.
 */
@Test
public void testFromMessageFailsForInvalidAddressWithEmptyReplyId() {
    final boolean replyToContainedDeviceId = false;
    final String replyToOptionsBitFlag = Command.encodeReplyToOptions(replyToContainedDeviceId);
    final Message message = ProtonHelper.message();
    message.setAddress(ResourceIdentifier
            .from(getCommandResponseEndpoint(), TENANT_ID, String.format("%s/%s%s", DEVICE_ID, replyToOptionsBitFlag, "")).toString());
    message.setCorrelationId(CORRELATION_ID);
    MessageHelper.addProperty(message, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
    final CommandResponse response = CommandResponse.from(message);
    assertThat(response).isNull();
}
 
Example 13
Source File: CommandResponseTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the device-id is not part of the CommandResponse replyToId.
 */
@Test
public void testForNoDeviceIdInReplyToId() {
    final boolean replyToContainedDeviceId = false;
    final String replyToOptionsBitFlag = Command.encodeReplyToOptions(replyToContainedDeviceId);
    final Message message = ProtonHelper.message();
    message.setAddress(ResourceIdentifier
            .from(getCommandResponseEndpoint(), TENANT_ID, String.format("%s/%s%s", DEVICE_ID, replyToOptionsBitFlag, "rid-1")).toString());
    message.setCorrelationId(CORRELATION_ID);
    MessageHelper.addProperty(message, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
    final CommandResponse response = CommandResponse.from(message);
    assertThat(response).isNotNull();
    assertThat(response.getReplyToId()).isEqualTo("rid-1");
}
 
Example 14
Source File: BlockingClientTest.java    From enmasse with Apache License 2.0 5 votes vote down vote up
@Test
public void testSend() throws Exception {
    try (BlockingClient client = new BlockingClient("127.0.0.1", actualPort)) {
        Message m = Message.Factory.create();
        m.setAddress("testsend");
        m.setBody(new AmqpValue("hello there"));
        client.send("testsend", Arrays.asList(m), 1, TimeUnit.MINUTES);

        Message received = inbox.poll(1, TimeUnit.MINUTES);
        assertNotNull(received);
        assertThat(received.getMessageId(), is(m.getMessageId()));
        assertThat(((AmqpValue) received.getBody()).getValue(), is("hello there"));
    }
}
 
Example 15
Source File: CommandResponseTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that creating a response fails for a message with status property containing an invalid value.
 */
@Test
public void testFromMessageFailsForInvalidStatus() {
    final boolean replyToContainedDeviceId = true;
    final String replyToOptionsBitFlag = Command.encodeReplyToOptions(replyToContainedDeviceId);
    final Message message = ProtonHelper.message();
    message.setAddress(ResourceIdentifier
            .from(getCommandResponseEndpoint(), TENANT_ID, String.format("%s/%srid-1", DEVICE_ID, replyToOptionsBitFlag)).toString());
    message.setCorrelationId(CORRELATION_ID);
    MessageHelper.addProperty(message, MessageHelper.APP_PROPERTY_STATUS, 777);
    final CommandResponse response = CommandResponse.from(message);
    assertThat(response).isNull();
}
 
Example 16
Source File: CommandResponseTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that creating a response fails for a message with no correlation id.
 */
@Test
public void testFromMessageFailsForMissingCorrelationId() {
    final boolean replyToContainedDeviceId = true;
    final String replyToOptionsBitFlag = Command.encodeReplyToOptions(replyToContainedDeviceId);
    final Message message = ProtonHelper.message();
    message.setAddress(ResourceIdentifier
            .from(getCommandResponseEndpoint(), TENANT_ID, String.format("%s/%srid-1", DEVICE_ID, replyToOptionsBitFlag)).toString());
    MessageHelper.addProperty(message, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
    final CommandResponse response = CommandResponse.from(message);
    assertThat(response).isNull();
}
 
Example 17
Source File: RequestResponseApiConstants.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Creates an AMQP message from a result to a service invocation.
 *
 * @param endpoint The service endpoint that the operation has been invoked on.
 * @param tenantId The id of the tenant (may be {@code null}).
 * @param request The request message.
 * @param result The result message.
 * @return The AMQP message.
 * @throws NullPointerException if endpoint, request or result is {@code null}.
 * @throws IllegalArgumentException if the result does not contain a correlation ID.
 */
public static final Message getAmqpReply(final String endpoint, final String tenantId, final Message request, final RequestResponseResult<JsonObject> result) {

    Objects.requireNonNull(endpoint);
    Objects.requireNonNull(request);
    Objects.requireNonNull(result);

    final Object correlationId = MessageHelper.getCorrelationId(request);

    if (correlationId == null) {
        throw new IllegalArgumentException("request must contain correlation ID");
    }

    final String deviceId = MessageHelper.getDeviceId(request);

    final ResourceIdentifier address = ResourceIdentifier.from(endpoint, tenantId, deviceId);

    final Message message = ProtonHelper.message();
    message.setMessageId(UUID.randomUUID().toString());
    message.setCorrelationId(correlationId.toString());
    message.setAddress(address.toString());

    final Map<String, Object> map = new HashMap<>();
    map.put(MessageHelper.APP_PROPERTY_STATUS, result.getStatus());
    if (tenantId != null) {
        map.put(MessageHelper.APP_PROPERTY_TENANT_ID, tenantId);
    }
    if (deviceId != null) {
        map.put(MessageHelper.APP_PROPERTY_DEVICE_ID, deviceId);
    }
    if (result.getCacheDirective() != null) {
        map.put(MessageHelper.APP_PROPERTY_CACHE_CONTROL, result.getCacheDirective().toString());
    }
    message.setApplicationProperties(new ApplicationProperties(map));

    MessageHelper.setJsonPayload(message, result.getPayload());

    return message;
}
 
Example 18
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 19
Source File: AbstractRequestResponseClient.java    From hono with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Creates an AMQP message for a subject and address.
 * <p>
 * The message can be extended by arbitrary application properties passed in.
 *
 * @param subject The subject system property of the message.
 * @param address The address of the message, put in the <em>to</em> property.
 * @param appProperties The map containing arbitrary application properties.
 *                      Maybe null if no application properties are needed.
 * @return The Proton message constructed from the provided parameters.
 * @throws NullPointerException if the subject is {@code null}.
 * @throws IllegalArgumentException if the application properties contain not AMQP 1.0 compatible values
 *                  (see {@link AbstractHonoClient#setApplicationProperties(Message, Map)}
 */
private Message createMessage(final String subject, final String address,
        final Map<String, Object> appProperties) {

    Objects.requireNonNull(subject);
    final Message msg = ProtonHelper.message();
    final String messageId = createMessageId();
    AbstractHonoClient.setApplicationProperties(msg, appProperties);
    msg.setAddress(address);
    msg.setReplyTo(replyToAddress);
    msg.setMessageId(messageId);
    msg.setSubject(subject);
    return msg;
}
 
Example 20
Source File: ProtonHelper.java    From vertx-proton with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a Message object with the given String contained as an AmqpValue body, and the 'to' address set as given.
 *
 * @param address
 *          the 'to' address to set
 * @param body
 *          the string to set as an AmqpValue body
 * @return the message
 */
public static Message message(String address, String body) {
  Message value = message(body);
  value.setAddress(address);
  return value;
}