Search in sources :

Example 21 with CommandConsumer

use of org.eclipse.hono.client.command.CommandConsumer in project hono by eclipse.

the class VertxBasedHttpProtocolAdapterTest method configureServiceClients.

/**
 * Sets up the fixture.
 *
 * @param testInfo The test meta data.
 */
@BeforeEach
public void configureServiceClients(final TestInfo testInfo) {
    LOG.info("running test case [{}]", testInfo.getDisplayName());
    createClients();
    prepareClients();
    setServiceClients(adapter);
    final CommandConsumer commandConsumer = mock(CommandConsumer.class);
    when(commandConsumer.close(any())).thenReturn(Future.succeededFuture());
    when(commandConsumerFactory.createCommandConsumer(anyString(), anyString(), VertxMockSupport.anyHandler(), any(), any())).thenReturn(Future.succeededFuture(commandConsumer));
    doAnswer(invocation -> {
        final Handler<AsyncResult<User>> resultHandler = invocation.getArgument(2);
        resultHandler.handle(Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_UNAUTHORIZED, "bad credentials")));
        return null;
    }).when(usernamePasswordAuthProvider).authenticate(any(UsernamePasswordCredentials.class), any(), VertxMockSupport.anyHandler());
    doAnswer(invocation -> {
        final JsonObject authInfo = invocation.getArgument(0);
        final String username = JsonHelper.getValue(authInfo, CredentialsConstants.FIELD_USERNAME, String.class, null);
        final String password = JsonHelper.getValue(authInfo, CredentialsConstants.FIELD_PASSWORD, String.class, null);
        if (username == null || password == null) {
            return null;
        } else {
            return UsernamePasswordCredentials.create(username, password);
        }
    }).when(usernamePasswordAuthProvider).getCredentials(any(JsonObject.class));
}
Also used : CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) ClientErrorException(org.eclipse.hono.client.ClientErrorException) JsonObject(io.vertx.core.json.JsonObject) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) AsyncResult(io.vertx.core.AsyncResult) UsernamePasswordCredentials(org.eclipse.hono.adapter.auth.device.UsernamePasswordCredentials) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 22 with CommandConsumer

use of org.eclipse.hono.client.command.CommandConsumer in project hono by eclipse.

the class VertxBasedHttpProtocolAdapterTest method testPostTelemetryWithTtdSucceedsWithCommandInResponse.

/**
 * Verifies that the adapter includes a command for the device in the response to
 * a POST request which contains a time-til-disconnect.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testPostTelemetryWithTtdSucceedsWithCommandInResponse(final VertxTestContext ctx) {
    // GIVEN an device for which a command is pending
    givenATelemetrySenderForAnyTenant();
    mockSuccessfulAuthentication("DEFAULT_TENANT", "device_1");
    final CommandContext commandContext = givenARequestResponseCommandContext("DEFAULT_TENANT", "device_1", "doThis", "reply-to-id", null, null, MessagingType.amqp);
    final CommandConsumer commandConsumer = mock(CommandConsumer.class);
    when(commandConsumer.close(any())).thenReturn(Future.succeededFuture());
    when(commandConsumerFactory.createCommandConsumer(eq("DEFAULT_TENANT"), eq("device_1"), VertxMockSupport.anyHandler(), any(), any())).thenAnswer(invocation -> {
        final Handler<CommandContext> consumer = invocation.getArgument(2);
        consumer.handle(commandContext);
        return Future.succeededFuture(commandConsumer);
    });
    // WHEN the device posts a telemetry message including a TTD
    httpClient.post("/telemetry").addQueryParam("hono-ttd", "3").putHeader(HttpHeaders.CONTENT_TYPE.toString(), HttpUtils.CONTENT_TYPE_JSON).basicAuthentication("testuser@DEFAULT_TENANT", "password123").putHeader(HttpHeaders.ORIGIN.toString(), ORIGIN_HEADER_VALUE).expect(ResponsePredicate.SC_OK).expect(this::assertCorsHeaders).expect(response -> {
        if (!"doThis".equals(response.getHeader(Constants.HEADER_COMMAND))) {
            return ResponsePredicateResult.failure("response does not contain expected hono-command header");
        }
        if (response.getHeader(Constants.HEADER_COMMAND_REQUEST_ID) == null) {
            return ResponsePredicateResult.failure("response does not contain hono-cmd-req-id header");
        }
        return ResponsePredicateResult.success();
    }).sendJsonObject(new JsonObject(), ctx.succeeding(r -> {
        ctx.verify(() -> {
            verify(commandConsumerFactory).createCommandConsumer(eq("DEFAULT_TENANT"), eq("device_1"), VertxMockSupport.anyHandler(), any(), any());
            // and the command consumer has been closed again
            verify(commandConsumer).close(any());
            verify(commandContext).accept();
        });
        ctx.completeNow();
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) WebClientOptions(io.vertx.ext.web.client.WebClientOptions) BeforeEach(org.junit.jupiter.api.BeforeEach) ResponsePredicate(io.vertx.ext.web.client.predicate.ResponsePredicate) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) LoggerFactory(org.slf4j.LoggerFactory) MultiMap(io.vertx.core.MultiMap) Timeout(io.vertx.junit5.Timeout) AfterAll(org.junit.jupiter.api.AfterAll) MessagingType(org.eclipse.hono.util.MessagingType) TestInstance(org.junit.jupiter.api.TestInstance) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BeforeAll(org.junit.jupiter.api.BeforeAll) Mockito.doAnswer(org.mockito.Mockito.doAnswer) JsonObject(io.vertx.core.json.JsonObject) JsonHelper(org.eclipse.hono.util.JsonHelper) CommandContext(org.eclipse.hono.client.command.CommandContext) HttpHeaders(io.vertx.core.http.HttpHeaders) Lifecycle(org.junit.jupiter.api.TestInstance.Lifecycle) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) TestInfo(org.junit.jupiter.api.TestInfo) Test(org.junit.jupiter.api.Test) User(io.vertx.ext.auth.User) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) UsernamePasswordCredentials(org.eclipse.hono.adapter.auth.device.UsernamePasswordCredentials) HttpAdapterMetrics(org.eclipse.hono.adapter.http.HttpAdapterMetrics) QoS(org.eclipse.hono.util.QoS) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) VertxTestContext(io.vertx.junit5.VertxTestContext) HttpResponse(io.vertx.ext.web.client.HttpResponse) ProtonDelivery(io.vertx.proton.ProtonDelivery) WebClient(io.vertx.ext.web.client.WebClient) ResponsePredicateResult(io.vertx.ext.web.client.predicate.ResponsePredicateResult) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Constants(org.eclipse.hono.util.Constants) DeviceUser(org.eclipse.hono.service.auth.DeviceUser) ProtocolAdapterTestSupport(org.eclipse.hono.adapter.test.ProtocolAdapterTestSupport) Timer(io.micrometer.core.instrument.Timer) HttpUtils(org.eclipse.hono.service.http.HttpUtils) AsyncResult(io.vertx.core.AsyncResult) CommandConstants(org.eclipse.hono.util.CommandConstants) Logger(org.slf4j.Logger) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Mockito.when(org.mockito.Mockito.when) CredentialsConstants(org.eclipse.hono.util.CredentialsConstants) Mockito.verify(org.mockito.Mockito.verify) TimeUnit(java.util.concurrent.TimeUnit) DeviceCredentialsAuthProvider(org.eclipse.hono.adapter.auth.device.DeviceCredentialsAuthProvider) HttpProtocolAdapterProperties(org.eclipse.hono.adapter.http.HttpProtocolAdapterProperties) Handler(io.vertx.core.Handler) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) CommandContext(org.eclipse.hono.client.command.CommandContext) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) JsonObject(io.vertx.core.json.JsonObject) Test(org.junit.jupiter.api.Test)

Example 23 with CommandConsumer

use of org.eclipse.hono.client.command.CommandConsumer in project hono by eclipse.

the class AbstractVertxBasedMqttProtocolAdapterTest method testOnSubscribeIncludesStatusCodeForEachFilter.

/**
 * Verifies that the adapter includes a status code for each topic filter in its SUBACK packet.
 */
@SuppressWarnings("unchecked")
@Test
public void testOnSubscribeIncludesStatusCodeForEachFilter() {
    // GIVEN a device connected to an adapter
    givenAnAdapter(properties);
    givenAnEventSenderForAnyTenant();
    final MqttEndpoint endpoint = mockEndpoint();
    when(endpoint.isConnected()).thenReturn(true);
    // WHEN a device sends a SUBSCRIBE packet for several unsupported filters
    final List<MqttTopicSubscription> subscriptions = new ArrayList<>();
    subscriptions.add(newMockTopicSubscription("unsupported/#", MqttQoS.AT_LEAST_ONCE));
    subscriptions.add(newMockTopicSubscription("bumlux/+/+/#", MqttQoS.AT_MOST_ONCE));
    subscriptions.add(newMockTopicSubscription("bumlux/+/+/#", MqttQoS.AT_MOST_ONCE));
    // and for subscribing to commands
    final CommandConsumer commandConsumer = mock(CommandConsumer.class);
    when(commandConsumer.close(any())).thenReturn(Future.succeededFuture());
    when(commandConsumerFactory.createCommandConsumer(eq("tenant-1"), eq("device-A"), VertxMockSupport.anyHandler(), any(), any())).thenReturn(Future.succeededFuture(commandConsumer));
    subscriptions.add(newMockTopicSubscription(getCommandSubscriptionTopic("tenant-1", "device-A"), MqttQoS.AT_MOST_ONCE));
    subscriptions.add(newMockTopicSubscription(getCommandSubscriptionTopic("tenant-1", "device-B"), MqttQoS.EXACTLY_ONCE));
    final MqttSubscribeMessage msg = mock(MqttSubscribeMessage.class);
    when(msg.messageId()).thenReturn(15);
    when(msg.topicSubscriptions()).thenReturn(subscriptions);
    final var mqttDeviceEndpoint = adapter.createMqttDeviceEndpoint(endpoint, null, OptionalInt.empty());
    mqttDeviceEndpoint.onSubscribe(msg);
    // THEN the adapter sends a SUBACK packet to the device
    // which contains a failure status code for each unsupported filter
    final ArgumentCaptor<List<MqttQoS>> codeCaptor = ArgumentCaptor.forClass(List.class);
    verify(endpoint).subscribeAcknowledge(eq(15), codeCaptor.capture());
    assertThat(codeCaptor.getValue()).hasSize(5);
    assertThat(codeCaptor.getValue().get(0)).isEqualTo(MqttQoS.FAILURE);
    assertThat(codeCaptor.getValue().get(1)).isEqualTo(MqttQoS.FAILURE);
    assertThat(codeCaptor.getValue().get(2)).isEqualTo(MqttQoS.FAILURE);
    assertThat(codeCaptor.getValue().get(3)).isEqualTo(MqttQoS.AT_MOST_ONCE);
    // and sends an empty notification downstream with TTD -1
    assertEmptyNotificationHasBeenSentDownstream("tenant-1", "device-A", -1);
}
Also used : MqttSubscribeMessage(io.vertx.mqtt.messages.MqttSubscribeMessage) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MqttTopicSubscription(io.vertx.mqtt.MqttTopicSubscription) ArrayList(java.util.ArrayList) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) List(java.util.List) ArrayList(java.util.ArrayList) Test(org.junit.jupiter.api.Test)

Aggregations

CommandConsumer (org.eclipse.hono.client.command.CommandConsumer)23 Handler (io.vertx.core.Handler)15 ClientErrorException (org.eclipse.hono.client.ClientErrorException)14 Device (org.eclipse.hono.auth.Device)12 CommandContext (org.eclipse.hono.client.command.CommandContext)11 Future (io.vertx.core.Future)10 HttpURLConnection (java.net.HttpURLConnection)10 ServerErrorException (org.eclipse.hono.client.ServerErrorException)10 Command (org.eclipse.hono.client.command.Command)10 Test (org.junit.jupiter.api.Test)10 Sample (io.micrometer.core.instrument.Timer.Sample)9 Span (io.opentracing.Span)9 SpanContext (io.opentracing.SpanContext)9 Promise (io.vertx.core.Promise)9 Buffer (io.vertx.core.buffer.Buffer)9 List (java.util.List)9 Map (java.util.Map)9 Constants (org.eclipse.hono.util.Constants)9 Tags (io.opentracing.tag.Tags)8 AsyncResult (io.vertx.core.AsyncResult)8