Search in sources :

Example 1 with Device

use of org.eclipse.hono.auth.Device in project hono by eclipse.

the class AbstractVertxBasedHttpProtocolAdapter method doUploadMessage.

private void doUploadMessage(final HttpContext ctx, final String tenant, final String deviceId, final Buffer payload, final String contentType, final MetricsTags.EndpointType endpoint) {
    if (!ctx.hasValidQoS()) {
        HttpUtils.badRequest(ctx.getRoutingContext(), "unsupported QoS-Level header value");
        return;
    }
    if (!isPayloadOfIndicatedType(payload, contentType)) {
        HttpUtils.badRequest(ctx.getRoutingContext(), String.format("content type [%s] does not match payload", contentType));
        return;
    }
    final MetricsTags.QoS qos = getQoSLevel(endpoint, ctx.getRequestedQos());
    final Device authenticatedDevice = ctx.getAuthenticatedDevice();
    final String gatewayId = authenticatedDevice != null && !deviceId.equals(authenticatedDevice.getDeviceId()) ? authenticatedDevice.getDeviceId() : null;
    final Span currentSpan = TracingHelper.buildChildSpan(tracer, TracingHandler.serverSpanContext(ctx.getRoutingContext()), "upload " + endpoint.getCanonicalName(), getTypeName()).withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).withTag(TracingHelper.TAG_TENANT_ID, tenant).withTag(TracingHelper.TAG_DEVICE_ID, deviceId).withTag(TracingHelper.TAG_AUTHENTICATED.getKey(), authenticatedDevice != null).withTag(TracingHelper.TAG_QOS, qos.name()).start();
    final Promise<Void> responseReady = Promise.promise();
    final Future<RegistrationAssertion> tokenTracker = getRegistrationAssertion(tenant, deviceId, authenticatedDevice, currentSpan.context());
    final int payloadSize = Optional.ofNullable(payload).map(ok -> payload.length()).orElse(0);
    final Future<TenantObject> tenantTracker = getTenantConfiguration(tenant, currentSpan.context());
    final Future<TenantObject> tenantValidationTracker = tenantTracker.compose(tenantObject -> CompositeFuture.all(isAdapterEnabled(tenantObject), checkMessageLimit(tenantObject, payloadSize, currentSpan.context())).map(success -> tenantObject));
    // we only need to consider TTD if the device and tenant are enabled and the adapter
    // is enabled for the tenant
    final Future<Integer> ttdTracker = CompositeFuture.all(tenantValidationTracker, tokenTracker).compose(ok -> {
        final Integer ttdParam = getTimeUntilDisconnectFromRequest(ctx);
        return getTimeUntilDisconnect(tenantTracker.result(), ttdParam).map(effectiveTtd -> {
            if (effectiveTtd != null) {
                currentSpan.setTag(MessageHelper.APP_PROPERTY_DEVICE_TTD, effectiveTtd);
            }
            return effectiveTtd;
        });
    });
    final Future<CommandConsumer> commandConsumerTracker = ttdTracker.compose(ttd -> createCommandConsumer(ttd, tenantTracker.result(), deviceId, gatewayId, ctx.getRoutingContext(), responseReady, currentSpan));
    commandConsumerTracker.compose(ok -> {
        final Map<String, Object> props = getDownstreamMessageProperties(ctx);
        Optional.ofNullable(commandConsumerTracker.result()).map(c -> ttdTracker.result()).ifPresent(ttd -> props.put(MessageHelper.APP_PROPERTY_DEVICE_TTD, ttd));
        props.put(MessageHelper.APP_PROPERTY_QOS, ctx.getRequestedQos().ordinal());
        customizeDownstreamMessageProperties(props, ctx);
        setTtdRequestConnectionCloseHandler(ctx.getRoutingContext(), commandConsumerTracker.result(), tenant, deviceId, currentSpan);
        if (EndpointType.EVENT.equals(endpoint)) {
            ctx.getTimeToLive().ifPresent(ttl -> props.put(MessageHelper.SYS_HEADER_PROPERTY_TTL, ttl.toSeconds()));
            return CompositeFuture.all(getEventSender(tenantValidationTracker.result()).sendEvent(tenantTracker.result(), tokenTracker.result(), contentType, payload, props, currentSpan.context()), responseReady.future()).map(s -> (Void) null);
        } else {
            // unsettled
            return CompositeFuture.all(getTelemetrySender(tenantValidationTracker.result()).sendTelemetry(tenantTracker.result(), tokenTracker.result(), ctx.getRequestedQos(), contentType, payload, props, currentSpan.context()), responseReady.future()).map(s -> (Void) null);
        }
    }).compose(proceed -> {
        // request and the CommandConsumer from the current request has not been closed yet
        return Optional.ofNullable(commandConsumerTracker.result()).map(consumer -> consumer.close(currentSpan.context()).otherwise(thr -> {
            TracingHelper.logError(currentSpan, thr);
            return (Void) null;
        })).orElseGet(Future::succeededFuture);
    }).map(proceed -> {
        if (ctx.response().closed()) {
            log.debug("failed to send http response for [{}] message from device [tenantId: {}, deviceId: {}]: response already closed", endpoint, tenant, deviceId);
            TracingHelper.logError(currentSpan, "failed to send HTTP response to device: response already closed");
            currentSpan.finish();
            // close the response here, ensuring that the TracingHandler bodyEndHandler gets called
            ctx.response().end();
        } else {
            final CommandContext commandContext = ctx.get(CommandContext.KEY_COMMAND_CONTEXT);
            setResponsePayload(ctx.response(), commandContext, currentSpan);
            ctx.getRoutingContext().addBodyEndHandler(ok -> {
                log.trace("successfully processed [{}] message for device [tenantId: {}, deviceId: {}]", endpoint, tenant, deviceId);
                if (commandContext != null) {
                    commandContext.getTracingSpan().log("forwarded command to device in HTTP response body");
                    commandContext.accept();
                    metrics.reportCommand(commandContext.getCommand().isOneWay() ? Direction.ONE_WAY : Direction.REQUEST, tenant, tenantTracker.result(), ProcessingOutcome.FORWARDED, commandContext.getCommand().getPayloadSize(), getMicrometerSample(commandContext));
                }
                metrics.reportTelemetry(endpoint, tenant, tenantTracker.result(), ProcessingOutcome.FORWARDED, qos, payloadSize, ctx.getTtdStatus(), getMicrometerSample(ctx.getRoutingContext()));
                currentSpan.finish();
            });
            ctx.response().exceptionHandler(t -> {
                log.debug("failed to send http response for [{}] message from device [tenantId: {}, deviceId: {}]", endpoint, tenant, deviceId, t);
                if (commandContext != null) {
                    TracingHelper.logError(commandContext.getTracingSpan(), "failed to forward command to device in HTTP response body", t);
                    commandContext.release(t);
                    metrics.reportCommand(commandContext.getCommand().isOneWay() ? Direction.ONE_WAY : Direction.REQUEST, tenant, tenantTracker.result(), ProcessingOutcome.UNDELIVERABLE, commandContext.getCommand().getPayloadSize(), getMicrometerSample(commandContext));
                }
                currentSpan.log("failed to send HTTP response to device");
                TracingHelper.logError(currentSpan, t);
                currentSpan.finish();
            });
            ctx.response().end();
        }
        return proceed;
    }).recover(t -> {
        log.debug("cannot process [{}] message from device [tenantId: {}, deviceId: {}]", endpoint, tenant, deviceId, t);
        final boolean responseClosedPrematurely = ctx.response().closed();
        final Future<Void> commandConsumerClosedTracker = Optional.ofNullable(commandConsumerTracker.result()).map(consumer -> consumer.close(currentSpan.context()).onFailure(thr -> TracingHelper.logError(currentSpan, thr))).orElseGet(Future::succeededFuture);
        final CommandContext commandContext = ctx.get(CommandContext.KEY_COMMAND_CONTEXT);
        if (commandContext != null) {
            TracingHelper.logError(commandContext.getTracingSpan(), "command won't be forwarded to device in HTTP response body, HTTP request handling failed", t);
            commandContext.release(t);
            currentSpan.log("released command for device");
        }
        final ProcessingOutcome outcome;
        if (ClientErrorException.class.isInstance(t)) {
            outcome = ProcessingOutcome.UNPROCESSABLE;
            ctx.fail(t);
        } else {
            outcome = ProcessingOutcome.UNDELIVERABLE;
            final String errorMessage = t instanceof ServerErrorException ? ((ServerErrorException) t).getClientFacingMessage() : null;
            HttpUtils.serviceUnavailable(ctx.getRoutingContext(), 2, Strings.isNullOrEmpty(errorMessage) ? "temporarily unavailable" : errorMessage);
        }
        if (responseClosedPrematurely) {
            log.debug("failed to send http response for [{}] message from device [tenantId: {}, deviceId: {}]: response already closed", endpoint, tenant, deviceId);
            TracingHelper.logError(currentSpan, "failed to send HTTP response to device: response already closed");
        }
        metrics.reportTelemetry(endpoint, tenant, tenantTracker.result(), outcome, qos, payloadSize, ctx.getTtdStatus(), getMicrometerSample(ctx.getRoutingContext()));
        TracingHelper.logError(currentSpan, t);
        commandConsumerClosedTracker.onComplete(res -> currentSpan.finish());
        return Future.failedFuture(t);
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) HttpServer(io.vertx.core.http.HttpServer) Router(io.vertx.ext.web.Router) RoutingContext(io.vertx.ext.web.RoutingContext) BodyHandler(io.vertx.ext.web.handler.BodyHandler) Tags(io.opentracing.tag.Tags) ProcessingOutcome(org.eclipse.hono.service.metric.MetricsTags.ProcessingOutcome) EndpointType(org.eclipse.hono.service.metric.MetricsTags.EndpointType) TtdStatus(org.eclipse.hono.service.metric.MetricsTags.TtdStatus) DeviceCredentials(org.eclipse.hono.adapter.auth.device.DeviceCredentials) References(io.opentracing.References) Duration(java.time.Duration) Map(java.util.Map) WebSpanDecorator(org.eclipse.hono.service.http.WebSpanDecorator) TracingHelper(org.eclipse.hono.tracing.TracingHelper) CommandContext(org.eclipse.hono.client.command.CommandContext) MetricsTags(org.eclipse.hono.service.metric.MetricsTags) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) Objects(java.util.Objects) List(java.util.List) ComponentMetaDataDecorator(org.eclipse.hono.service.http.ComponentMetaDataDecorator) TenantTraceSamplingHelper(org.eclipse.hono.tracing.TenantTraceSamplingHelper) Buffer(io.vertx.core.buffer.Buffer) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) HttpServerResponse(io.vertx.core.http.HttpServerResponse) DefaultFailureHandler(org.eclipse.hono.service.http.DefaultFailureHandler) Optional(java.util.Optional) Span(io.opentracing.Span) HttpContext(org.eclipse.hono.service.http.HttpContext) Command(org.eclipse.hono.client.command.Command) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Constants(org.eclipse.hono.util.Constants) ArrayList(java.util.ArrayList) TracingHandler(org.eclipse.hono.service.http.TracingHandler) CompositeFuture(io.vertx.core.CompositeFuture) HttpUtils(org.eclipse.hono.service.http.HttpUtils) AsyncResult(io.vertx.core.AsyncResult) Strings(org.eclipse.hono.util.Strings) Route(io.vertx.ext.web.Route) CredentialsApiAuthProvider(org.eclipse.hono.adapter.auth.device.CredentialsApiAuthProvider) AbstractProtocolAdapterBase(org.eclipse.hono.adapter.AbstractProtocolAdapterBase) Direction(org.eclipse.hono.service.metric.MetricsTags.Direction) Promise(io.vertx.core.Promise) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Sample(io.micrometer.core.instrument.Timer.Sample) CommandResponse(org.eclipse.hono.client.command.CommandResponse) TenantObject(org.eclipse.hono.util.TenantObject) SpanContext(io.opentracing.SpanContext) HttpServerOptions(io.vertx.core.http.HttpServerOptions) NoopSpan(io.opentracing.noop.NoopSpan) Handler(io.vertx.core.Handler) CommandContext(org.eclipse.hono.client.command.CommandContext) Device(org.eclipse.hono.auth.Device) Span(io.opentracing.Span) NoopSpan(io.opentracing.noop.NoopSpan) ProcessingOutcome(org.eclipse.hono.service.metric.MetricsTags.ProcessingOutcome) TenantObject(org.eclipse.hono.util.TenantObject) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) MetricsTags(org.eclipse.hono.service.metric.MetricsTags) Future(io.vertx.core.Future) CompositeFuture(io.vertx.core.CompositeFuture) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with Device

use of org.eclipse.hono.auth.Device in project hono by eclipse.

the class AbstractVertxBasedHttpProtocolAdapter method uploadCommandResponseMessage.

/**
 * Uploads a command response message to Hono.
 *
 * @param ctx The routing context of the HTTP request.
 * @param tenant The tenant of the device from which the command response was received.
 * @param deviceId The device from which the command response was received.
 * @param commandRequestId The id of the command that the response has been sent in reply to.
 * @param responseStatus The HTTP status code that the device has provided in its request to indicate
 *                       the outcome of processing the command (may be {@code null}).
 * @throws NullPointerException if ctx, tenant or deviceId are {@code null}.
 */
public final void uploadCommandResponseMessage(final HttpContext ctx, final String tenant, final String deviceId, final String commandRequestId, final Integer responseStatus) {
    Objects.requireNonNull(ctx);
    Objects.requireNonNull(tenant);
    Objects.requireNonNull(deviceId);
    final Buffer payload = ctx.getRoutingContext().getBody();
    final String contentType = ctx.getContentType();
    log.debug("processing response to command [tenantId: {}, deviceId: {}, cmd-req-id: {}, status code: {}]", tenant, deviceId, commandRequestId, responseStatus);
    final Device authenticatedDevice = ctx.getAuthenticatedDevice();
    final Span currentSpan = TracingHelper.buildChildSpan(tracer, TracingHandler.serverSpanContext(ctx.getRoutingContext()), "upload Command response", getTypeName()).withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).withTag(TracingHelper.TAG_TENANT_ID, tenant).withTag(TracingHelper.TAG_DEVICE_ID, deviceId).withTag(Constants.HEADER_COMMAND_RESPONSE_STATUS, responseStatus).withTag(Constants.HEADER_COMMAND_REQUEST_ID, commandRequestId).withTag(TracingHelper.TAG_AUTHENTICATED.getKey(), authenticatedDevice != null).start();
    final CommandResponse cmdResponseOrNull = CommandResponse.fromRequestId(commandRequestId, tenant, deviceId, payload, contentType, responseStatus);
    final Future<TenantObject> tenantTracker = getTenantConfiguration(tenant, currentSpan.context());
    final Future<CommandResponse> commandResponseTracker = cmdResponseOrNull != null ? Future.succeededFuture(cmdResponseOrNull) : Future.failedFuture(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, String.format("command-request-id [%s] or status code [%s] is missing/invalid", commandRequestId, responseStatus)));
    final int payloadSize = Optional.ofNullable(payload).map(Buffer::length).orElse(0);
    CompositeFuture.all(tenantTracker, commandResponseTracker).compose(commandResponse -> {
        final Future<RegistrationAssertion> deviceRegistrationTracker = getRegistrationAssertion(tenant, deviceId, authenticatedDevice, currentSpan.context());
        final Future<Void> tenantValidationTracker = CompositeFuture.all(isAdapterEnabled(tenantTracker.result()), checkMessageLimit(tenantTracker.result(), payloadSize, currentSpan.context())).map(ok -> null);
        return CompositeFuture.all(tenantValidationTracker, deviceRegistrationTracker).compose(ok -> sendCommandResponse(tenantTracker.result(), deviceRegistrationTracker.result(), commandResponseTracker.result(), currentSpan.context())).map(delivery -> {
            log.trace("delivered command response [command-request-id: {}] to application", commandRequestId);
            currentSpan.log("delivered command response to application");
            currentSpan.finish();
            metrics.reportCommand(Direction.RESPONSE, tenant, tenantTracker.result(), ProcessingOutcome.FORWARDED, payloadSize, getMicrometerSample(ctx.getRoutingContext()));
            ctx.response().setStatusCode(HttpURLConnection.HTTP_ACCEPTED);
            ctx.response().end();
            return delivery;
        });
    }).otherwise(t -> {
        log.debug("could not send command response [command-request-id: {}] to application", commandRequestId, t);
        TracingHelper.logError(currentSpan, t);
        currentSpan.finish();
        metrics.reportCommand(Direction.RESPONSE, tenant, tenantTracker.result(), ProcessingOutcome.from(t), payloadSize, getMicrometerSample(ctx.getRoutingContext()));
        ctx.fail(t);
        return null;
    });
}
Also used : Buffer(io.vertx.core.buffer.Buffer) HttpURLConnection(java.net.HttpURLConnection) HttpServer(io.vertx.core.http.HttpServer) Router(io.vertx.ext.web.Router) RoutingContext(io.vertx.ext.web.RoutingContext) BodyHandler(io.vertx.ext.web.handler.BodyHandler) Tags(io.opentracing.tag.Tags) ProcessingOutcome(org.eclipse.hono.service.metric.MetricsTags.ProcessingOutcome) EndpointType(org.eclipse.hono.service.metric.MetricsTags.EndpointType) TtdStatus(org.eclipse.hono.service.metric.MetricsTags.TtdStatus) DeviceCredentials(org.eclipse.hono.adapter.auth.device.DeviceCredentials) References(io.opentracing.References) Duration(java.time.Duration) Map(java.util.Map) WebSpanDecorator(org.eclipse.hono.service.http.WebSpanDecorator) TracingHelper(org.eclipse.hono.tracing.TracingHelper) CommandContext(org.eclipse.hono.client.command.CommandContext) MetricsTags(org.eclipse.hono.service.metric.MetricsTags) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) Objects(java.util.Objects) List(java.util.List) ComponentMetaDataDecorator(org.eclipse.hono.service.http.ComponentMetaDataDecorator) TenantTraceSamplingHelper(org.eclipse.hono.tracing.TenantTraceSamplingHelper) Buffer(io.vertx.core.buffer.Buffer) CommandConsumer(org.eclipse.hono.client.command.CommandConsumer) HttpServerResponse(io.vertx.core.http.HttpServerResponse) DefaultFailureHandler(org.eclipse.hono.service.http.DefaultFailureHandler) Optional(java.util.Optional) Span(io.opentracing.Span) HttpContext(org.eclipse.hono.service.http.HttpContext) Command(org.eclipse.hono.client.command.Command) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Constants(org.eclipse.hono.util.Constants) ArrayList(java.util.ArrayList) TracingHandler(org.eclipse.hono.service.http.TracingHandler) CompositeFuture(io.vertx.core.CompositeFuture) HttpUtils(org.eclipse.hono.service.http.HttpUtils) AsyncResult(io.vertx.core.AsyncResult) Strings(org.eclipse.hono.util.Strings) Route(io.vertx.ext.web.Route) CredentialsApiAuthProvider(org.eclipse.hono.adapter.auth.device.CredentialsApiAuthProvider) AbstractProtocolAdapterBase(org.eclipse.hono.adapter.AbstractProtocolAdapterBase) Direction(org.eclipse.hono.service.metric.MetricsTags.Direction) Promise(io.vertx.core.Promise) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Sample(io.micrometer.core.instrument.Timer.Sample) CommandResponse(org.eclipse.hono.client.command.CommandResponse) TenantObject(org.eclipse.hono.util.TenantObject) SpanContext(io.opentracing.SpanContext) HttpServerOptions(io.vertx.core.http.HttpServerOptions) NoopSpan(io.opentracing.noop.NoopSpan) Handler(io.vertx.core.Handler) TenantObject(org.eclipse.hono.util.TenantObject) Device(org.eclipse.hono.auth.Device) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Future(io.vertx.core.Future) CompositeFuture(io.vertx.core.CompositeFuture) CommandResponse(org.eclipse.hono.client.command.CommandResponse) Span(io.opentracing.Span) NoopSpan(io.opentracing.noop.NoopSpan)

Example 3 with Device

use of org.eclipse.hono.auth.Device in project hono by eclipse.

the class VertxBasedHttpProtocolAdapter method handlePostTelemetry.

void handlePostTelemetry(final RoutingContext ctx) {
    if (Device.class.isInstance(ctx.user())) {
        final Device device = (Device) ctx.user();
        uploadTelemetryMessage(HttpContext.from(ctx), device.getTenantId(), device.getDeviceId());
    } else {
        handle401(ctx);
    }
}
Also used : Device(org.eclipse.hono.auth.Device)

Example 4 with Device

use of org.eclipse.hono.auth.Device in project hono by eclipse.

the class TelemetryResourceTest method testUploadTelemetryWithQoS1.

/**
 * Verifies that the adapter waits for a the AMQP Messaging Network to accept a
 * forwarded telemetry message that has been published using a CON message,
 * before responding with a 2.04 status to the device.
 */
@Test
public void testUploadTelemetryWithQoS1() {
    // GIVEN an adapter with a downstream telemetry consumer attached
    givenAnAdapter(properties);
    final Promise<Void> outcome = Promise.promise();
    givenATelemetrySenderForAnyTenant(outcome);
    final var resource = givenAResource(adapter);
    // WHEN a device publishes an telemetry message with QoS 1
    final Buffer payload = Buffer.buffer("some payload");
    final CoapExchange coapExchange = newCoapExchange(payload, Type.CON, MediaTypeRegistry.TEXT_PLAIN);
    final Device authenticatedDevice = new Device("tenant", "device");
    final CoapContext context = CoapContext.fromRequest(coapExchange, authenticatedDevice, authenticatedDevice, "device", span);
    resource.handlePostRequest(context);
    // THEN the message is being forwarded downstream
    assertTelemetryMessageHasBeenSentDownstream(QoS.AT_LEAST_ONCE, "tenant", "device", "text/plain");
    // and the device does not get a response
    verify(coapExchange, never()).respond(any(Response.class));
    // until the telemetry message has been accepted
    outcome.complete();
    verify(coapExchange).respond(argThat((Response res) -> ResponseCode.CHANGED.equals(res.getCode())));
    verify(metrics).reportTelemetry(eq(MetricsTags.EndpointType.TELEMETRY), eq("tenant"), any(), eq(MetricsTags.ProcessingOutcome.FORWARDED), eq(MetricsTags.QoS.AT_LEAST_ONCE), eq(payload.length()), eq(TtdStatus.NONE), any());
}
Also used : Buffer(io.vertx.core.buffer.Buffer) Response(org.eclipse.californium.core.coap.Response) Device(org.eclipse.hono.auth.Device) CoapExchange(org.eclipse.californium.core.server.resources.CoapExchange) Test(org.junit.jupiter.api.Test)

Example 5 with Device

use of org.eclipse.hono.auth.Device in project hono by eclipse.

the class TelemetryResourceTest method testUploadTelemetryWithOneWayCommand.

/**
 * Verifies that the adapter includes a command in the response to a telemetry request.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testUploadTelemetryWithOneWayCommand(final VertxTestContext ctx) {
    // GIVEN an adapter with a downstream telemetry consumer attached
    givenAnAdapter(properties);
    givenATelemetrySenderForAnyTenant();
    final var resource = givenAResource(adapter);
    // and a commandConsumerFactory that upon creating a consumer will invoke it with a command
    final Sample commandTimer = mock(Sample.class);
    final CommandContext commandContext = givenAOneWayCommandContext("tenant", "device", "doThis", null, null);
    when(commandContext.get(anyString())).thenReturn(commandTimer);
    when(commandConsumerFactory.createCommandConsumer(eq("tenant"), eq("device"), VertxMockSupport.anyHandler(), any(), any())).thenAnswer(invocation -> {
        final Handler<CommandContext> consumer = invocation.getArgument(2);
        consumer.handle(commandContext);
        return Future.succeededFuture(commandConsumer);
    });
    // WHEN a device publishes a telemetry message with a hono-ttd parameter
    final Buffer payload = Buffer.buffer("some payload");
    final OptionSet options = new OptionSet();
    options.addUriQuery(String.format("%s=%d", Constants.HEADER_TIME_TILL_DISCONNECT, 20));
    options.setContentFormat(MediaTypeRegistry.TEXT_PLAIN);
    final CoapExchange coapExchange = newCoapExchange(payload, Type.CON, options);
    final Device authenticatedDevice = new Device("tenant", "device");
    final CoapContext context = CoapContext.fromRequest(coapExchange, authenticatedDevice, authenticatedDevice, "device", span);
    resource.handlePostRequest(context).onComplete(ctx.succeeding(ok -> {
        ctx.verify(() -> {
            // THEN the message is being forwarded downstream
            assertTelemetryMessageHasBeenSentDownstream(QoS.AT_LEAST_ONCE, "tenant", "device", "text/plain");
            // correctly reported
            verify(metrics).reportTelemetry(eq(MetricsTags.EndpointType.TELEMETRY), eq("tenant"), any(), eq(ProcessingOutcome.FORWARDED), eq(MetricsTags.QoS.AT_LEAST_ONCE), eq(payload.length()), eq(TtdStatus.COMMAND), any());
            // and the device gets a response which contains a (one-way) command
            verify(coapExchange).respond(argThat((Response res) -> ResponseCode.CHANGED == res.getCode() && CommandConstants.COMMAND_ENDPOINT.equals(res.getOptions().getLocationPathString()) && res.getOptions().getLocationQueryString().endsWith("=doThis") && res.getPayloadSize() == 0));
            verify(metrics).reportCommand(eq(Direction.ONE_WAY), eq("tenant"), any(), eq(ProcessingOutcome.FORWARDED), eq(0), eq(commandTimer));
        });
        ctx.completeNow();
    }));
}
Also used : Buffer(io.vertx.core.buffer.Buffer) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HttpURLConnection(java.net.HttpURLConnection) ResponseCode(org.eclipse.californium.core.coap.CoAP.ResponseCode) VertxTestContext(io.vertx.junit5.VertxTestContext) CoapExchange(org.eclipse.californium.core.server.resources.CoapExchange) Response(org.eclipse.californium.core.coap.Response) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) ClientErrorException(org.eclipse.hono.client.ClientErrorException) Constants(org.eclipse.hono.util.Constants) Timeout(io.vertx.junit5.Timeout) ProcessingOutcome(org.eclipse.hono.service.metric.MetricsTags.ProcessingOutcome) TtdStatus(org.eclipse.hono.service.metric.MetricsTags.TtdStatus) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) MediaTypeRegistry(org.eclipse.californium.core.coap.MediaTypeRegistry) CommandConstants(org.eclipse.hono.util.CommandConstants) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) Type(org.eclipse.californium.core.coap.CoAP.Type) Direction(org.eclipse.hono.service.metric.MetricsTags.Direction) NoopTracerFactory(io.opentracing.noop.NoopTracerFactory) Promise(io.vertx.core.Promise) CommandContext(org.eclipse.hono.client.command.CommandContext) MetricsTags(org.eclipse.hono.service.metric.MetricsTags) ServerErrorException(org.eclipse.hono.client.ServerErrorException) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) Sample(io.micrometer.core.instrument.Timer.Sample) VertxExtension(io.vertx.junit5.VertxExtension) EventConstants(org.eclipse.hono.util.EventConstants) Future(io.vertx.core.Future) Device(org.eclipse.hono.auth.Device) Mockito.verify(org.mockito.Mockito.verify) TenantObject(org.eclipse.hono.util.TenantObject) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) Mockito.never(org.mockito.Mockito.never) Buffer(io.vertx.core.buffer.Buffer) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) OptionSet(org.eclipse.californium.core.coap.OptionSet) Handler(io.vertx.core.Handler) QoS(org.eclipse.hono.util.QoS) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) Response(org.eclipse.californium.core.coap.Response) CommandContext(org.eclipse.hono.client.command.CommandContext) Sample(io.micrometer.core.instrument.Timer.Sample) Device(org.eclipse.hono.auth.Device) OptionSet(org.eclipse.californium.core.coap.OptionSet) CoapExchange(org.eclipse.californium.core.server.resources.CoapExchange) Test(org.junit.jupiter.api.Test)

Aggregations

Device (org.eclipse.hono.auth.Device)115 HttpURLConnection (java.net.HttpURLConnection)74 Test (org.junit.jupiter.api.Test)72 Future (io.vertx.core.Future)69 ClientErrorException (org.eclipse.hono.client.ClientErrorException)67 Buffer (io.vertx.core.buffer.Buffer)66 Handler (io.vertx.core.Handler)63 TenantObject (org.eclipse.hono.util.TenantObject)63 Promise (io.vertx.core.Promise)59 Constants (org.eclipse.hono.util.Constants)58 Span (io.opentracing.Span)55 RegistrationAssertion (org.eclipse.hono.util.RegistrationAssertion)55 SpanContext (io.opentracing.SpanContext)53 VertxTestContext (io.vertx.junit5.VertxTestContext)52 VertxExtension (io.vertx.junit5.VertxExtension)51 MessageHelper (org.eclipse.hono.util.MessageHelper)51 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)51 Mockito.when (org.mockito.Mockito.when)51 Truth.assertThat (com.google.common.truth.Truth.assertThat)50 ResourceIdentifier (org.eclipse.hono.util.ResourceIdentifier)47