io.vertx.proton.ProtonHelper Java Examples

The following examples show how to use io.vertx.proton.ProtonHelper. 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: AmqpServiceBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Closes an expired client connection.
 * <p>
 * A connection is considered expired if the {@link HonoUser#isExpired()} method
 * of the user principal attached to the connection returns {@code true}.
 *
 * @param con The client connection.
 */
protected final void closeExpiredConnection(final ProtonConnection con) {

    if (!con.isDisconnected()) {
        final HonoUser clientPrincipal = Constants.getClientPrincipal(con);
        if (clientPrincipal != null) {
            log.debug("client's [{}] access token has expired, closing connection", clientPrincipal.getName());
            con.disconnectHandler(null);
            con.closeHandler(null);
            con.setCondition(ProtonHelper.condition(AmqpError.UNAUTHORIZED_ACCESS, "access token expired"));
            con.close();
            con.disconnect();
            publishConnectionClosedEvent(con);
        }
    }
}
 
Example #2
Source File: AbstractProtocolAdapterBaseTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the adapter does not add default properties to downstream messages
 * if disabled for the adapter.
 */
@Test
public void testAddPropertiesIgnoresDefaultsIfDisabled() {

    properties.setDefaultsEnabled(false);

    final Message message = ProtonHelper.message();
    final ResourceIdentifier target = ResourceIdentifier.from(EventConstants.EVENT_ENDPOINT, Constants.DEFAULT_TENANT, "4711");
    final JsonObject assertion = newRegistrationAssertionResult()
            .put(RegistrationConstants.FIELD_PAYLOAD_DEFAULTS, new JsonObject()
                .put(MessageHelper.SYS_HEADER_PROPERTY_TTL, 30)
                .put("custom-device", true));

    adapter.addProperties(message, target, null, null, assertion, null);

    assertThat(
            MessageHelper.getApplicationProperty(message.getApplicationProperties(), "custom-device", Boolean.class),
            is(nullValue()));
    assertThat(message.getTtl(), is(0L));
}
 
Example #3
Source File: AmqpAdapterClientCommandResponseSender.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public Future<ProtonDelivery> sendCommandResponse(final String deviceId, final String targetAddress,
        final String correlationId, final int status, final byte[] payload,
        final String contentType, final Map<String, ?> properties, final SpanContext context) {

    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(targetAddress);
    Objects.requireNonNull(correlationId);

    final Message message = ProtonHelper.message();
    message.setAddress(targetAddress);
    message.setCorrelationId(correlationId);

    MessageHelper.setCreationTime(message);

    setApplicationProperties(message, properties);
    MessageHelper.addTenantId(message, tenantId);
    MessageHelper.addDeviceId(message, deviceId);
    MessageHelper.addProperty(message, MessageHelper.APP_PROPERTY_STATUS, status);
    MessageHelper.setPayload(message, contentType, payload);

    return sendAndWaitForOutcome(message, context);
}
 
Example #4
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 #5
Source File: TelemetryAndEventCli.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Connects to the AMQP org.eclipse.hono.cli.app.adapter and send a telemetry/event message to the org.eclipse.hono.cli.app.adapter.
 *
 * @param messageTracker The future to notify when the message is sent. The future is completed with the delivery
 *            upon success or completed with an exception.
 */
private void sendMessage(final CompletableFuture<ProtonDelivery> messageTracker) {

    ctx.runOnContext(go -> {
        connectToAdapter()
        .compose(con -> {
            adapterConnection = con;
            return createSender();
        })
        .map(sender -> {
            final Message message = ProtonHelper.message(messageAddress, payload);
            sender.send(message, delivery -> {
                adapterConnection.close();
                messageTracker.complete(delivery);
            });
            return sender;
        })
        .otherwise(t -> {
            messageTracker.completeExceptionally(t);
            return null;
        });
    });
 }
 
Example #6
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 #7
Source File: MessageHelperTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the current system time is set on a downstream message
 * if the message doesn't contain a creation time.
 */
@Test
public void testAddPropertiesSetsCreationTime() {

    final Message message = ProtonHelper.message();
    assertThat(message.getCreationTime()).isEqualTo(0);

    MessageHelper.addProperties(
            message,
            ResourceIdentifier.fromString("telemetry/DEFAULT_TENANT/4711"),
            null,
            null,
            null,
            null,
            null,
            "custom-adapter",
            true,
            true);

    assertThat(message.getCreationTime()).isGreaterThan(0);
}
 
Example #8
Source File: RequestResponseApiConstants.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates an AMQP (response) message for conveying an erroneous outcome of an operation.
 *
 * @param status The status code.
 * @param errorDescription An (optional) error description which will be put to a <em>Data</em>
 *                         section.
 * @param requestMessage The request message.
 * @return The response message.
 */
public static final Message getErrorMessage(
        final int status,
        final String errorDescription,
        final Message requestMessage) {

    Objects.requireNonNull(requestMessage);
    if (status < 100 || status >= 600) {
        throw new IllegalArgumentException("illegal status code");
    }

    final Message message = ProtonHelper.message();
    MessageHelper.addStatus(message, status);
    message.setCorrelationId(MessageHelper.getCorrelationId(requestMessage));
    if (errorDescription != null) {
        MessageHelper.setPayload(message, MessageHelper.CONTENT_TYPE_TEXT_PLAIN, Buffer.buffer(errorDescription));
    }
    return message;
}
 
Example #9
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 #10
Source File: MessageHelperTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the fall back content type is set on a downstream message
 * if no default has been configured for the device.
 */
@Test
public void testAddPropertiesAddsFallbackContentType() {

    final Message message = ProtonHelper.message();
    message.setAddress("telemetry/DEFAULT_TENANT/4711");
    MessageHelper.addProperties(
            message,
            null,
            null,
            null,
            null,
            null,
            null,
            "custom",
            true,
            false);

    assertThat(message.getContentType()).isEqualTo(MessageHelper.CONTENT_TYPE_OCTET_STREAM);
}
 
Example #11
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 #12
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 a response from the service to the cache
 * that does not contain any cache directive but has a <em>non-cacheable</em> status code.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCreateAndSendRequestDoesNotAddNonCacheableResponseToCache(final VertxTestContext ctx) {

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

    // WHEN getting a 404 response to a request which contains
    // no cache directive
    client.createAndSendRequest("get", (Buffer) null, ctx.succeeding(result -> {
        // 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();
    response.setCorrelationId(messageCaptor.getValue().getMessageId());
    MessageHelper.addProperty(response, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_NOT_FOUND);
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    client.handleResponse(delivery, response);
}
 
Example #13
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 #14
Source File: EventSenderImplTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the sender fails if no credit is available.
 */
@Test
public void testSendAndWaitForOutcomeFailsOnLackOfCredit() {

    // GIVEN a sender that has credit
    when(sender.sendQueueFull()).thenReturn(Boolean.TRUE);
    final DownstreamSender messageSender = new EventSenderImpl(connection, sender, "tenant", "event/tenant");

    // WHEN trying to send a message
    final Message event = ProtonHelper.message("event/tenant", "hello");
    final Future<ProtonDelivery> result = messageSender.sendAndWaitForOutcome(event);

    // THEN the message is not sent
    assertFalse(result.succeeded());
    verify(sender, never()).send(any(Message.class), VertxMockSupport.anyHandler());
}
 
Example #15
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 testSendMarksMessageAsDurable() {

    // 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.send(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 #16
Source File: AbstractRequestResponseClientTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the adapter puts the response from the service to the cache
 * using the max age indicated by a response's <em>max-age</em> cache directive.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCreateAndSendRequestAddsResponseToCacheWithMaxAge(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 has been put to the cache
        verify(cache).put(eq("cacheKey"), any(SimpleRequestResponseResult.class), eq(Duration.ofSeconds(35)));
        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.maxAgeDirective(35));
    response.setCorrelationId(messageCaptor.getValue().getMessageId());
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    client.handleResponse(delivery, response);
}
 
Example #17
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 #18
Source File: AbstractSenderTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the sender removes the registration assertion
 * from a message if the peer does not support validation of
 * assertions.
 */
@Test
public void testSendMessageRemovesRegistrationAssertion() {

    // GIVEN a sender that is connected to a peer which does not
    // support validation of registration assertions
    when(protonSender.getRemoteOfferedCapabilities()).thenReturn(null);
    when(protonSender.send(any(Message.class), VertxMockSupport.anyHandler())).thenReturn(mock(ProtonDelivery.class));
    final AbstractSender sender = newSender("tenant", "endpoint");

    // WHEN sending a message
    final Message msg = ProtonHelper.message("some payload");
    msg.setContentType("application/text");
    MessageHelper.addDeviceId(msg, "device");
    sender.send(msg);

    // THEN the message is sent without the registration assertion
    final ArgumentCaptor<Message> sentMessage = ArgumentCaptor.forClass(Message.class);
    verify(protonSender).send(sentMessage.capture());
    assertNull(MessageHelper.getAndRemoveRegistrationAssertion(sentMessage.getValue()));
}
 
Example #19
Source File: AbstractProtocolAdapterBase.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates an AMQP error condition for an throwable.
 * <p>
 * Non {@link ServiceInvocationException} instances are mapped to {@link AmqpError#PRECONDITION_FAILED}.
 *
 * @param t The throwable to map to an error condition.
 * @return The error condition.
 */
protected final ErrorCondition getErrorCondition(final Throwable t) {
    if (ServiceInvocationException.class.isInstance(t)) {
        final ServiceInvocationException error = (ServiceInvocationException) t;
        switch (error.getErrorCode()) {
        case HttpURLConnection.HTTP_BAD_REQUEST:
            return ProtonHelper.condition(Constants.AMQP_BAD_REQUEST, error.getMessage());
        case HttpURLConnection.HTTP_FORBIDDEN:
            return ProtonHelper.condition(AmqpError.UNAUTHORIZED_ACCESS, error.getMessage());
        case HttpUtils.HTTP_TOO_MANY_REQUESTS:
            return ProtonHelper.condition(AmqpError.RESOURCE_LIMIT_EXCEEDED, error.getMessage());
        default:
            return ProtonHelper.condition(AmqpError.PRECONDITION_FAILED, error.getMessage());
        }
    } else {
        return ProtonHelper.condition(AmqpError.PRECONDITION_FAILED, t.getMessage());
    }
}
 
Example #20
Source File: SimpleAuthenticationServer.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Processes the AMQP <em>open</em> frame received from a peer.
 * <p>
 * Checks if the open frame contains a desired <em>ADDRESS_AUTHZ</em> capability and if so,
 * adds the authenticated clients' authorities to the properties of the open frame sent
 * to the peer in response.
 *
 * @param connection The connection opened by the peer.
 */
@Override
protected void processRemoteOpen(final ProtonConnection connection) {
    if (AddressAuthzHelper.isAddressAuthzCapabilitySet(connection)) {
        LOG.debug("client [container: {}] requests transfer of authenticated user's authorities in open frame",
                connection.getRemoteContainer());
        AddressAuthzHelper.processAddressAuthzCapability(connection);
    }
    connection.open();
    vertx.setTimer(5000, closeCon -> {
        if (!connection.isDisconnected()) {
            LOG.debug("connection with client [{}] timed out after 5 seconds, closing connection", connection.getRemoteContainer());
            connection.setCondition(ProtonHelper.condition(Constants.AMQP_ERROR_INACTIVITY,
                    "client must retrieve token within 5 secs after opening connection")).close();
        }
    });
}
 
Example #21
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 #22
Source File: RegistrationClientImplTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that on a cache miss the adapter retrieves registration information
 * from the Device Registration service and puts it to the cache.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testAssertRegistrationAddsResponseToCacheOnCacheMiss(final VertxTestContext ctx) {

    final JsonObject registrationAssertion = newRegistrationAssertionResult();

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

    // WHEN getting registration information
    client.assertRegistration("myDevice").onComplete(ctx.succeeding(result -> {
        ctx.verify(() -> {
            // THEN the registration information has been added to the cache
            assertThat(result).isEqualTo(registrationAssertion);
            verify(cache).put(eq(TriTuple.of("assert", "myDevice", null)), 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());
    final Message response = ProtonHelper.message();
    MessageHelper.addProperty(response, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
    MessageHelper.addCacheDirective(response, CacheDirective.maxAgeDirective(60));
    response.setCorrelationId(messageCaptor.getValue().getMessageId());
    MessageHelper.setPayload(response, MessageHelper.CONTENT_TYPE_APPLICATION_JSON, registrationAssertion.toBuffer());
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    client.handleResponse(delivery, response);
}
 
Example #23
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 type.
 */
@Test
public void testAddJmsVendorPropertiesRejectsEmptyContentType() {

    final Message msg = ProtonHelper.message();
    msg.setContentType("");
    MessageHelper.addJmsVendorProperties(msg);
    assertThat(msg.getApplicationProperties()).isNull();;
}
 
Example #24
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 encoding.
 */
@Test
public void testAddJmsVendorPropertiesAddsContentEncoding() {

    final Message msg = ProtonHelper.message();
    msg.setContentEncoding("gzip");
    MessageHelper.addJmsVendorProperties(msg);
    assertThat(msg.getApplicationProperties().getValue().get(MessageHelper.JMS_VENDOR_PROPERTY_CONTENT_ENCODING)).isEqualTo("gzip");
}
 
Example #25
Source File: AbstractDownstreamSender.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public final Future<ProtonDelivery> send(final String deviceId, final Map<String, ?> properties, final byte[] payload, final String contentType) {
    Objects.requireNonNull(deviceId);
    Objects.requireNonNull(payload);
    Objects.requireNonNull(contentType);

    final Message msg = ProtonHelper.message();
    msg.setAddress(getTo(deviceId));
    MessageHelper.setPayload(msg, contentType, payload);
    setApplicationProperties(msg, properties);
    MessageHelper.addDeviceId(msg, deviceId);
    return send(msg);
}
 
Example #26
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 #27
Source File: TenantClientImplTest.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.
 */
@SuppressWarnings("unchecked")
@Test
public void testGetTenantInvokesServiceIfNoCacheConfigured(final VertxTestContext ctx) {

    // GIVEN an adapter with no cache configured
    client.setResponseCache(null);
    final JsonObject tenantResult = newTenantResult("tenant");

    // WHEN getting tenant information by ID
    client.get("tenant").onComplete(ctx.succeeding(tenant -> {
        ctx.verify(() -> {
            // THEN the registration information has been retrieved from the service
            assertThat(tenant).isNotNull();
            assertThat(tenant.getTenantId()).isEqualTo("tenant");
            // and not been put to the cache
            verify(cache, never()).put(any(), any(TenantResult.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(), any(Handler.class));
    final Message response = ProtonHelper.message();
    MessageHelper.addProperty(response, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
    MessageHelper.addCacheDirective(response, CacheDirective.maxAgeDirective(60));
    response.setCorrelationId(messageCaptor.getValue().getMessageId());
    MessageHelper.setPayload(response, MessageHelper.CONTENT_TYPE_APPLICATION_JSON, tenantResult.toBuffer());
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    client.handleResponse(delivery, response);
}
 
Example #28
Source File: TenantClientImplTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that on a cache miss the adapter retrieves tenant information
 * from the Tenant service and puts it to the cache.
 *
 * @param ctx The vert.x test context.
 */
@SuppressWarnings("unchecked")
@Test
public void testGetTenantAddsInfoToCacheOnCacheMiss(final VertxTestContext ctx) {

    // GIVEN an adapter with an empty cache
    client.setResponseCache(cache);
    final JsonObject tenantResult = newTenantResult("tenant");

    // WHEN getting tenant information
    client.get("tenant").onComplete(ctx.succeeding(tenant -> {
        ctx.verify(() -> {
            // THEN the tenant result has been added to the cache
            assertThat(tenant).isNotNull();
            assertThat(tenant.getTenantId()).isEqualTo("tenant");
            verify(cache).put(eq(TriTuple.of(TenantAction.get, "tenant", null)), any(TenantResult.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());
    final Message response = ProtonHelper.message();
    MessageHelper.addProperty(response, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
    MessageHelper.addCacheDirective(response, CacheDirective.maxAgeDirective(60));
    response.setCorrelationId(messageCaptor.getValue().getMessageId());
    MessageHelper.setPayload(response, MessageHelper.CONTENT_TYPE_APPLICATION_JSON, tenantResult.toBuffer());
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    client.handleResponse(delivery, response);
}
 
Example #29
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 #30
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;
}