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

The following examples show how to use org.apache.qpid.proton.message.Message#setCorrelationId() . 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: 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 2
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 3
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 4
Source File: AbstractRequestResponseClientTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Verifies that the client passes a response message to the handler registered for the request that
 * the response correlates with.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testHandleResponseInvokesHandlerForMatchingCorrelationId(final VertxTestContext ctx) {

    // GIVEN a request message that has been sent to a peer
    client.createAndSendRequest(
            "request",
            Buffer.buffer("hello"),
            ctx.succeeding(s -> {
                // THEN the response is passed to the handler registered with the request
                assertEquals(200, s.getStatus());
                assertEquals("payload", s.getPayload().toString());
                // and no response time-out handler has been set
                verify(vertx, never()).setTimer(anyLong(), VertxMockSupport.anyHandler());
                ctx.completeNow();
            }),
            span);

    // WHEN a response is received for the request
    final Message response = ProtonHelper.message("payload");
    response.setCorrelationId(MESSAGE_ID);
    MessageHelper.addProperty(response, MessageHelper.APP_PROPERTY_STATUS, 200);
    final ProtonDelivery delivery = mock(ProtonDelivery.class);
    client.handleResponse(delivery, response);
}
 
Example 5
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 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.
 * 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 7
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 8
Source File: DeviceConnectionClientImplTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the client retrieves the result of the <em>get-last-known-gateway</em> operation from the
 * Device Connection service.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testGetLastKnownGatewayForDeviceSuccess(final VertxTestContext ctx) {

    final String gatewayId = "gatewayId";
    final JsonObject getLastGatewayResult = new JsonObject().
            put(DeviceConnectionConstants.FIELD_GATEWAY_ID, gatewayId);

    // WHEN getting the last known gateway
    client.getLastKnownGatewayForDevice("deviceId", span.context())
            .onComplete(ctx.succeeding(resultJson -> {
                ctx.verify(() -> {
                    // THEN the last known gateway has been retrieved from the service and the span is finished
                    assertThat(resultJson).isNotNull();
                    assertThat(resultJson.getString(DeviceConnectionConstants.FIELD_GATEWAY_ID)).isEqualTo(gatewayId);
                    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, getLastGatewayResult.toBuffer());
    client.handleResponse(mock(ProtonDelivery.class), response);
}
 
Example 9
Source File: CommandTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that a command can be created from a valid message, containing a message address with device id
 * differing from the one given in the command constructor.
 * Verifies that the replyToId are build up of all segments behind the tenant.
 */
@Test
public void testFromMessageSucceedsWithDifferingDeviceId() {
    final String gatewayId = "gw-1";
    final String targetDeviceId = "4711";
    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, targetDeviceId));
    message.setSubject("doThis");
    message.setCorrelationId(correlationId);
    message.setReplyTo(String.format("%s/%s/%s/%s",
            CommandConstants.NORTHBOUND_COMMAND_RESPONSE_ENDPOINT, Constants.DEFAULT_TENANT, targetDeviceId, replyToId));
    final boolean replyToContainedDeviceId = true;
    final String replyToOptionsBitFlag = Command.encodeReplyToOptions(replyToContainedDeviceId);
    final Command cmd = Command.from(message, Constants.DEFAULT_TENANT, gatewayId);
    assertTrue(cmd.isValid());
    assertThat(cmd.getName()).isEqualTo("doThis");
    assertThat(cmd.getDeviceId()).isEqualTo(gatewayId);
    assertThat(cmd.getOriginalDeviceId()).isEqualTo(targetDeviceId);
    assertThat(cmd.getReplyToId()).isEqualTo(String.format("%s/%s", targetDeviceId, 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 10
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 11
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 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, 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 13
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 14
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 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 status property.
 */
@Test
public void testFromMessageFailsForMissingStatus() {
    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);
    final CommandResponse response = CommandResponse.from(message);
    assertThat(response).isNull();
}
 
Example 17
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 18
Source File: DeviceConnectionClientImplTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private Message createNoContentResponseMessage(final Object correlationId) {
    final Message response = ProtonHelper.message();
    MessageHelper.addProperty(response, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_NO_CONTENT);
    MessageHelper.addCacheDirective(response, CacheDirective.maxAgeDirective(60));
    response.setCorrelationId(correlationId);
    return response;
}
 
Example 19
Source File: CommandAndControlAmqpIT.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
private ProtonMessageHandler createCommandConsumer(final VertxTestContext ctx, final ProtonReceiver cmdReceiver,
        final ProtonSender cmdResponseSender) {

    return (delivery, msg) -> {
        ctx.verify(() -> {
            assertThat(msg.getReplyTo()).isNotNull();
            assertThat(msg.getSubject()).isNotNull();
            assertThat(msg.getCorrelationId()).isNotNull();
        });
        final String command = msg.getSubject();
        final Object correlationId = msg.getCorrelationId();
        log.debug("received command [name: {}, reply-to: {}, correlation-id: {}]", command, msg.getReplyTo(), correlationId);
        ProtonHelper.accepted(delivery, true);
        cmdReceiver.flow(1);
        // send response
        final Message commandResponse = ProtonHelper.message(command + " ok");
        commandResponse.setAddress(msg.getReplyTo());
        commandResponse.setCorrelationId(correlationId);
        commandResponse.setContentType("text/plain");
        MessageHelper.addProperty(commandResponse, MessageHelper.APP_PROPERTY_STATUS, HttpURLConnection.HTTP_OK);
        log.debug("sending response [to: {}, correlation-id: {}]", commandResponse.getAddress(), commandResponse.getCorrelationId());
        cmdResponseSender.send(commandResponse, updatedDelivery -> {
            if (!Accepted.class.isInstance(updatedDelivery.getRemoteState())) {
                log.error("AMQP adapter did not accept command response [remote state: {}]",
                        updatedDelivery.getRemoteState().getClass().getSimpleName());
            }
        });
    };
}
 
Example 20
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);
}