Java Code Examples for io.vertx.proton.ProtonHelper#message()

The following examples show how to use io.vertx.proton.ProtonHelper#message() . 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 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 2
Source File: AbstractRequestResponseClientTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the adapter does not put the response from the service to the cache
 * if the response contains a <em>no-cache</em> cache directive.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCreateAndSendRequestDoesNotAddResponseToCache(final VertxTestContext ctx) {

    // GIVEN an adapter with an empty cache
    client.setResponseCache(cache);

    // WHEN sending a request
    client.createAndSendRequest("get", (Buffer) null, ctx.succeeding(result -> {
        assertEquals(200, result.getStatus());
        // THEN the response is not put to the cache
        verify(cache, never()).put(eq("cacheKey"), any(SimpleRequestResponseResult.class), any(Duration.class));
        ctx.completeNow();
    }), "cacheKey");
    final ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
    verify(sender).send(messageCaptor.capture(), VertxMockSupport.anyHandler());
    final Message response = ProtonHelper.message("result");
    MessageHelper.addProperty(response, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
    MessageHelper.addCacheDirective(response, CacheDirective.noCacheDirective());
    response.setCorrelationId(messageCaptor.getValue().getMessageId());
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    client.handleResponse(delivery, response);
}
 
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: 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 5
Source File: EventSenderImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the sender marks messages as durable.
 */
@Test
public void testSendAndWaitForOutcomeMarksMessageAsDurable() {

    // GIVEN a sender that has credit
    when(sender.sendQueueFull()).thenReturn(Boolean.FALSE);
    final DownstreamSender messageSender = new EventSenderImpl(connection, sender, "tenant", "telemetry/tenant");
    when(sender.send(any(Message.class), VertxMockSupport.anyHandler())).thenReturn(mock(ProtonDelivery.class));

    // WHEN trying to send a message
    final Message msg = ProtonHelper.message("telemetry/tenant/deviceId", "some payload");
    messageSender.sendAndWaitForOutcome(msg);

    // THEN the message has been sent
    verify(sender).send(any(Message.class), VertxMockSupport.anyHandler());
    // and the message has been marked as durable
    assertTrue(msg.isDurable());
}
 
Example 6
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, containing nothing behind the
 * device id part.
 */
@Test
public void testFromMessageFailsForInvalidAddressWithNothingBehindDeviceId() {
    final Message message = ProtonHelper.message();
    // use address with an invalid resource id part (nothing behind the device id)
    message.setAddress(ResourceIdentifier.from(getCommandResponseEndpoint(), TENANT_ID, DEVICE_ID).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 7
Source File: MessageHelperTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the helper does not throw an exception when reading
 * invalid UTF-8 from a message's payload.
 */
@Test
public void testGetPayloadAsStringHandlesNonCharacterPayload() {

    final Message msg = ProtonHelper.message();
    msg.setBody(new Data(new Binary(new byte[] { (byte) 0xc3, (byte) 0x28 })));
    assertThat(MessageHelper.getPayloadAsString(msg)).isNotNull();

    msg.setBody(new Data(new Binary(new byte[] { (byte) 0xf0, (byte) 0x28, (byte) 0x8c, (byte) 0xbc })));
    assertThat(MessageHelper.getPayloadAsString(msg)).isNotNull();
}
 
Example 8
Source File: RegistrationClientImplTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the client retrieves registration information from the
 * Device Registration service if no cache is configured.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testAssertRegistrationInvokesServiceIfNoCacheConfigured(final VertxTestContext ctx) {

    // GIVEN an adapter with no cache configured
    final JsonObject registrationAssertion = newRegistrationAssertionResult();
    final Message response = ProtonHelper.message();
    MessageHelper.addProperty(response, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
    MessageHelper.addCacheDirective(response, CacheDirective.maxAgeDirective(60));
    MessageHelper.setPayload(response, MessageHelper.CONTENT_TYPE_APPLICATION_JSON, registrationAssertion.toBuffer());

    // WHEN getting registration information
    client.assertRegistration("device").onComplete(ctx.succeeding(result -> {
        ctx.verify(() -> {
            // THEN the registration information has been retrieved from the service
            assertThat(result).isEqualTo(registrationAssertion);
            // and not been put to the cache
            verify(cache, never()).put(any(), any(RegistrationResult.class), any(Duration.class));
            // and the span is finished
            verify(span).finish();
        });
        ctx.completeNow();
    }));

    final ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
    verify(sender).send(messageCaptor.capture(), VertxMockSupport.anyHandler());
    response.setCorrelationId(messageCaptor.getValue().getMessageId());
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    client.handleResponse(delivery, response);
}
 
Example 9
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, containing an invalid
 * replyToOptions bit.
 */
@Test
public void testFromMessageFailsForInvalidAddressWithWrongReplyToOptionsBit() {
    final String replyToOptionsBitFlag = "X"; // invalid value to test with
    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, HttpURLConnection.HTTP_OK);
    final CommandResponse response = CommandResponse.from(message);
    assertThat(response).isNull();
}
 
Example 10
Source File: CommandResponseTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the device-id is part of the reply-to-id.
 */
@Test
public void testForDeviceIdInReplyToId() {
    final boolean replyToContainedDeviceId = true;
    final String replyToOptionsBitFlag = Command.encodeReplyToOptions(replyToContainedDeviceId);
    final Message message = ProtonHelper.message();
    message.setAddress(ResourceIdentifier
            .from("control", TENANT_ID, String.format("%s/%srid-1", 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).isNotNull();
    assertThat(response.getReplyToId()).isEqualTo("4711/rid-1");
}
 
Example 11
Source File: MessageHelperTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the helper does not add JMS vendor properties for
 * empty content encoding.
 */
@Test
public void testAddJmsVendorPropertiesRejectsEmptyContentEncoding() {

    final Message msg = ProtonHelper.message();
    msg.setContentEncoding("");
    MessageHelper.addJmsVendorProperties(msg);
    assertThat(msg.getApplicationProperties()).isNull();
}
 
Example 12
Source File: AmqpAdapterClientTelemetrySenderImpl.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Message createMessage(final String deviceId, final byte[] payload, final String contentType,
        final Map<String, ?> properties) {
    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(payload);

    final Message msg = ProtonHelper.message();
    msg.setAddress(getTo(deviceId));
    MessageHelper.setPayload(msg, contentType, payload);
    setApplicationProperties(msg, properties);
    MessageHelper.addDeviceId(msg, deviceId);
    return msg;
}
 
Example 13
Source File: MessageAnnotationsInjectExtractAdapterTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the same entries injected via the {@code MessageAnnotationsInjectAdapter} are extracted via the
 * {@code MessageAnnotationsExtractAdapter}.
 * Also verifies that there are no errors during encoding/decoding of the message with the injected entries.
 */
@Test
public void testInjectAndExtract() {
    final Map<String, String> testEntries = new HashMap<>();
    testEntries.put("key1", "value1");
    testEntries.put("key2", "value2");

    final Message message = ProtonHelper.message();
    // inject the properties
    final MessageAnnotationsInjectAdapter injectAdapter = new MessageAnnotationsInjectAdapter(message, propertiesMapName);
    testEntries.forEach((key, value) -> {
        injectAdapter.put(key, value);
    });

    // encode the message
    final WritableBuffer.ByteBufferWrapper buffer = WritableBuffer.ByteBufferWrapper.allocate(100);
    message.encode(buffer);

    // decode the message
    final Message decodedMessage = ProtonHelper.message();
    decodedMessage.decode(buffer.toReadableBuffer());
    // extract the properties from the decoded message
    final MessageAnnotationsExtractAdapter extractAdapter = new MessageAnnotationsExtractAdapter(decodedMessage, propertiesMapName);
    extractAdapter.iterator().forEachRemaining(extractedEntry -> {
        assertThat(extractedEntry.getValue()).isEqualTo(testEntries.get(extractedEntry.getKey()));
    });
}
 
Example 14
Source File: MessageHelper.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns a copy of the given message.
 * <p>
 * This is a shallow copy of the <em>Message</em> object, except for the copied <em>Properties</em>.
 *
 * @param message The message to copy.
 * @return The message copy.
 */
public static Message getShallowCopy(final Message message) {
    final Message copy = ProtonHelper.message();
    copy.setDeliveryAnnotations(message.getDeliveryAnnotations());
    copy.setMessageAnnotations(message.getMessageAnnotations());
    if (message.getProperties() != null) {
        copy.setProperties(new Properties(message.getProperties()));
    }
    copy.setApplicationProperties(message.getApplicationProperties());
    copy.setBody(message.getBody());
    copy.setFooter(message.getFooter());
    return copy;
}
 
Example 15
Source File: MessageHelperTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the helper adds JMS vendor properties for
 * non-empty content type.
 */
@Test
public void testAddJmsVendorPropertiesAddsContentType() {

    final Message msg = ProtonHelper.message();
    msg.setContentType("application/json");
    MessageHelper.addJmsVendorProperties(msg);
    assertThat(msg.getApplicationProperties().getValue().get(MessageHelper.JMS_VENDOR_PROPERTY_CONTENT_TYPE)).isEqualTo("application/json");
}
 
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: 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 18
Source File: DeviceConnectionClientImplTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the client handles the response of the <em>get-cmd-handling-adapter-instances</em> operation from the
 * Device Connection service.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testGetCommandHandlingAdapterInstances(final VertxTestContext ctx) {

    final String adapterInstanceId = "adapterInstanceId";
    final String deviceId = "4711";

    final JsonArray adapterInstancesArray = new JsonArray();
    adapterInstancesArray
            .add(new JsonObject().put(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCE_ID, adapterInstanceId)
                    .put(DeviceConnectionConstants.FIELD_PAYLOAD_DEVICE_ID, deviceId));
    final JsonObject adapterInstancesResult = new JsonObject().
            put(DeviceConnectionConstants.FIELD_ADAPTER_INSTANCES, adapterInstancesArray);

    // WHEN getting the command handling adapter instances
    client.getCommandHandlingAdapterInstances(deviceId, Collections.emptyList(), span.context())
            .onComplete(ctx.succeeding(resultJson -> {
                ctx.verify(() -> {
                    // THEN the response has been handled and the span is finished
                    assertThat(resultJson).isEqualTo(adapterInstancesResult);
                    verify(span).finish();
                });
                ctx.completeNow();
            }));

    final Message sentMessage = verifySenderSend();
    final Message response = ProtonHelper.message();
    MessageHelper.addProperty(response, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
    MessageHelper.addCacheDirective(response, CacheDirective.maxAgeDirective(60));
    response.setCorrelationId(sentMessage.getMessageId());
    MessageHelper.setPayload(response, MessageHelper.CONTENT_TYPE_APPLICATION_JSON, adapterInstancesResult.toBuffer());
    client.handleResponse(mock(ProtonDelivery.class), response);
}
 
Example 19
Source File: CredentialsClientImplTest.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Verifies that the client retrieves credentials from the Device Registration service if no cache is configured.
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings("unchecked")
@Test
public void testGetCredentialsInvokesServiceIfNoCacheConfigured(final VertxTestContext ctx) {

    final String authId = "test-auth";
    final String credentialsType = CredentialsConstants.SECRETS_TYPE_HASHED_PASSWORD;
    final JsonObject credentialsObject = newCredentialsResult("device", authId);
    final Message response = ProtonHelper.message();
    MessageHelper.addProperty(response, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
    MessageHelper.addCacheDirective(response, CacheDirective.maxAgeDirective(60));
    MessageHelper.setPayload(response, MessageHelper.CONTENT_TYPE_APPLICATION_JSON, credentialsObject.toBuffer());

    // WHEN getting credential information information
    final Future<CredentialsObject> getFuture = client.get(credentialsType, authId);

    final ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
    verify(sender).send(messageCaptor.capture(), VertxMockSupport.anyHandler());
    response.setCorrelationId(messageCaptor.getValue().getMessageId());
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    final Message sentMessage = messageCaptor.getValue();

    getFuture.onComplete(ctx.succeeding(credentials -> {
        ctx.verify(() -> {
            // THEN the credentials has been retrieved from the service
            assertNotNull(credentials);
            assertEquals("device", credentials.getDeviceId());
            // and not been put to the cache
            verify(cache, never()).put(any(), any(CredentialsResult.class), any(Duration.class));
            // and the span is finished
            verify(span).finish();

            assertEquals(sentMessage.getSubject(), CredentialsConstants.CredentialsAction.get.toString());
            assertEquals(MessageHelper.getJsonPayload(sentMessage).getString(CredentialsConstants.FIELD_TYPE),
                    credentialsType);
            assertEquals(MessageHelper.getJsonPayload(sentMessage).getString(CredentialsConstants.FIELD_AUTH_ID), authId);
        });
        ctx.completeNow();
    }));

    client.handleResponse(delivery, response);
}
 
Example 20
Source File: MessageHelper.java    From hono with Eclipse Public License 2.0 3 votes vote down vote up
/**
 * Creates a new AMQP 1.0 message.
 * <p>
 * This method creates a new {@code Message} and sets
 * <ul>
 * <li>its <em>creation-time</em> to the current system time,</li>
 * <li>its <em>content-type</em> to the given value,</li>
 * <li>its payload as an AMQP <em>Data</em> section</li>
 * </ul>
 * The message is then passed to {@link #addProperties(Message, ResourceIdentifier, String, TenantObject,
 * JsonObject, Integer, Duration, String, boolean, boolean)}.
 *
 * @param target The target address of the message or {@code null} if the message's
 *               <em>to</em> property contains the target address. The target
 *               address is used to determine if the message represents an event or not.
 *               Determining this information from the <em>to</em> property
 *               requires additional parsing which can be prevented by passing in the
 *               target address as a {@code ResourceIdentifier} instead.
 * @param publishAddress The address that the message has been published to originally by the device or
 *            {@code null} if unknown.
 *            <p>
 *            This address will be transport protocol specific, e.g. an HTTP based adapter will probably use URIs
 *            here whereas an MQTT based adapter might use the MQTT message's topic.
 * @param contentType The content type describing the message's payload or {@code null} if no content type
 *                    should be set.
 * @param payload The message payload or {@code null} if the message has no payload.
 * @param tenant The information registered for the tenant that the device belongs to or {@code null}
 *               if no information about the tenant is available.
 * @param deviceDefaultProperties The device's default properties registered at the device level or {@code null}
 *                                if no default properties are registered for the device.
 * @param timeUntilDisconnect The number of seconds until the device that has published the message will disconnect
 *            from the protocol adapter or {@code null} if unknown.
 * @param timeToLive The message's <em>time-to-live</em> as provided by the device or {@code null} if the
 *                   device did not provide any TTL.
 * @param adapterTypeName The type name of the protocol adapter that the message has been published to.
 * @param addDefaults {@code true} if the default properties registered for the device should be added
 *                    to the message. The properties to add are determined by merging the properties returned
 *                    by {@link TenantObject#getDefaults()} with the given device level default properties.
 * @param addJmsVendorProps {@code true} if
 *                          <a href="https://www.oasis-open.org/committees/download.php/60574/amqp-bindmap-jms-v1.0-wd09.pdf">
 *                          JMS Vendor Properties</a> should be added to the message.

 * @return The newly created message.
 * @throws NullPointerException if adapterTypeName is {@code null}.
 */
public static Message newMessage(
        final ResourceIdentifier target,
        final String publishAddress,
        final String contentType,
        final Buffer payload,
        final TenantObject tenant,
        final JsonObject deviceDefaultProperties,
        final Integer timeUntilDisconnect,
        final Duration timeToLive,
        final String adapterTypeName,
        final boolean addDefaults,
        final boolean addJmsVendorProps) {

    Objects.requireNonNull(adapterTypeName);

    final Message msg = ProtonHelper.message();
    msg.setContentType(contentType);
    setPayload(msg, contentType, payload);

    return addProperties(
            msg,
            target,
            publishAddress,
            tenant,
            deviceDefaultProperties,
            timeUntilDisconnect,
            timeToLive,
            adapterTypeName,
            addDefaults,
            addJmsVendorProps);
}