Search in sources :

Example 1 with RegistrationAssertion

use of org.eclipse.hono.util.RegistrationAssertion 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 RegistrationAssertion

use of org.eclipse.hono.util.RegistrationAssertion 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 RegistrationAssertion

use of org.eclipse.hono.util.RegistrationAssertion in project hono by eclipse.

the class ResourceTestBase method givenAnAdapter.

CoapProtocolAdapter givenAnAdapter(final CoapAdapterProperties configuration) {
    adapter = mock(CoapProtocolAdapter.class);
    when(adapter.checkMessageLimit(any(TenantObject.class), anyLong(), any())).thenReturn(Future.succeededFuture());
    when(adapter.getCommandConsumerFactory()).thenReturn(commandConsumerFactory);
    when(adapter.getCommandResponseSender(any(MessagingType.class), any(TenantObject.class))).thenReturn(commandResponseSender);
    when(adapter.getConfig()).thenReturn(configuration);
    when(adapter.getDownstreamMessageProperties(any(TelemetryExecutionContext.class))).thenReturn(new HashMap<>());
    when(adapter.getEventSender(any(TenantObject.class))).thenReturn(eventSender);
    when(adapter.getInsecureEndpoint()).thenReturn(mock(Endpoint.class));
    when(adapter.getMetrics()).thenReturn(metrics);
    when(adapter.getRegistrationAssertion(anyString(), anyString(), any(), (SpanContext) any())).thenAnswer(invocation -> {
        final String deviceId = invocation.getArgument(1);
        final RegistrationAssertion regAssertion = new RegistrationAssertion(deviceId);
        return Future.succeededFuture(regAssertion);
    });
    when(adapter.getSecureEndpoint()).thenReturn(mock(Endpoint.class));
    when(adapter.getTelemetrySender(any(TenantObject.class))).thenReturn(telemetrySender);
    when(adapter.getTenantClient()).thenReturn(tenantClient);
    when(adapter.getTimeUntilDisconnect(any(TenantObject.class), any())).thenCallRealMethod();
    when(adapter.getTypeName()).thenReturn(Constants.PROTOCOL_ADAPTER_TYPE_COAP);
    when(adapter.isAdapterEnabled(any(TenantObject.class))).thenAnswer(invocation -> Future.succeededFuture(invocation.getArgument(0)));
    doAnswer(invocation -> {
        final Handler<Void> codeToRun = invocation.getArgument(0);
        codeToRun.handle(null);
        return null;
    }).when(adapter).runOnContext(VertxMockSupport.anyHandler());
    when(adapter.sendTtdEvent(anyString(), anyString(), any(), anyInt(), any())).thenReturn(Future.succeededFuture());
    return adapter;
}
Also used : TenantObject(org.eclipse.hono.util.TenantObject) Endpoint(org.eclipse.californium.core.network.Endpoint) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) MessagingType(org.eclipse.hono.util.MessagingType) TelemetryExecutionContext(org.eclipse.hono.util.TelemetryExecutionContext) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString)

Example 4 with RegistrationAssertion

use of org.eclipse.hono.util.RegistrationAssertion in project hono by eclipse.

the class HttpBasedMessageMappingTest method testMapCommandSucceeds.

/**
 * Verifies that the result returned by the upstream mapping service contains the
 * mapped payload.
 *
 * @param ctx The helper to use for running tests on vert.x.
 */
@SuppressWarnings("unchecked")
@Test
public void testMapCommandSucceeds(final VertxTestContext ctx) {
    config.setMapperEndpoints(Map.of("mapper", MapperEndpoint.from("host", 1234, "/uri", false)));
    final HttpRequest<Buffer> httpRequest = mock(HttpRequest.class, withSettings().defaultAnswer(RETURNS_SELF));
    final Buffer payload = Buffer.buffer("payload");
    final Buffer responseBody = Buffer.buffer("changed");
    final HttpResponse<Buffer> httpResponse = mock(HttpResponse.class);
    when(httpResponse.bodyAsBuffer()).thenReturn(responseBody);
    when(httpResponse.statusCode()).thenReturn(HttpURLConnection.HTTP_OK);
    when(mapperWebClient.post(anyInt(), anyString(), anyString())).thenReturn(httpRequest);
    final Command command = mock(Command.class);
    when(command.getPayload()).thenReturn(payload);
    final RegistrationAssertion assertion = new RegistrationAssertion("gateway").setUpstreamMessageMapper("mapper");
    messageMapping.mapUpstreamMessage(assertion, command).onComplete(ctx.succeeding(mappedBuffer -> {
        ctx.verify(() -> {
            assertThat(mappedBuffer).isEqualTo(responseBody);
            verify(mapperWebClient, times(1)).post(anyInt(), anyString(), anyString());
        });
        ctx.completeNow();
    }));
    final ArgumentCaptor<Handler<AsyncResult<HttpResponse<Buffer>>>> handleCaptor = VertxMockSupport.argumentCaptorHandler();
    verify(httpRequest).sendBuffer(any(Buffer.class), handleCaptor.capture());
    handleCaptor.getValue().handle(Future.succeededFuture(httpResponse));
}
Also used : Buffer(io.vertx.core.buffer.Buffer) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HttpURLConnection(java.net.HttpURLConnection) VertxTestContext(io.vertx.junit5.VertxTestContext) BeforeEach(org.junit.jupiter.api.BeforeEach) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) HttpResponse(io.vertx.ext.web.client.HttpResponse) WebClient(io.vertx.ext.web.client.WebClient) Command(org.eclipse.hono.client.command.Command) MultiMap(io.vertx.core.MultiMap) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) Constants(org.eclipse.hono.util.Constants) RETURNS_SELF(org.mockito.Mockito.RETURNS_SELF) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) ArgumentCaptor(org.mockito.ArgumentCaptor) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Map(java.util.Map) MqttContext(org.eclipse.hono.adapter.mqtt.MqttContext) TracingMockSupport(org.eclipse.hono.test.TracingMockSupport) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) AsyncResult(io.vertx.core.AsyncResult) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) MapperEndpoint(org.eclipse.hono.config.MapperEndpoint) ServerErrorException(org.eclipse.hono.client.ServerErrorException) HttpHeaders(io.vertx.core.http.HttpHeaders) Mockito.times(org.mockito.Mockito.times) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) Device(org.eclipse.hono.auth.Device) Mockito.verify(org.mockito.Mockito.verify) HttpRequest(io.vertx.ext.web.client.HttpRequest) Test(org.junit.jupiter.api.Test) Mockito.never(org.mockito.Mockito.never) URLEncoder(java.net.URLEncoder) Buffer(io.vertx.core.buffer.Buffer) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) MqttProtocolAdapterProperties(org.eclipse.hono.adapter.mqtt.MqttProtocolAdapterProperties) Span(io.opentracing.Span) Mockito.withSettings(org.mockito.Mockito.withSettings) Handler(io.vertx.core.Handler) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) Command(org.eclipse.hono.client.command.Command) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) Handler(io.vertx.core.Handler) HttpResponse(io.vertx.ext.web.client.HttpResponse) Test(org.junit.jupiter.api.Test)

Example 5 with RegistrationAssertion

use of org.eclipse.hono.util.RegistrationAssertion in project hono by eclipse.

the class HttpBasedMessageMappingTest method testMapMessageSucceeds.

/**
 * Verifies that the result returned by the mapping service contains the
 * mapped payload, device ID and additional properties.
 *
 * @param ctx The helper to use for running tests on vert.x.
 */
@SuppressWarnings("unchecked")
@Test
public void testMapMessageSucceeds(final VertxTestContext ctx) {
    config.setMapperEndpoints(Map.of("mapper", MapperEndpoint.from("host", 1234, "/uri", false)));
    final ResourceIdentifier targetAddress = ResourceIdentifier.from(TelemetryConstants.TELEMETRY_ENDPOINT, TEST_TENANT_ID, "gateway");
    final String newDeviceId = "new-device";
    final HttpRequest<Buffer> httpRequest = mock(HttpRequest.class, withSettings().defaultAnswer(RETURNS_SELF));
    final MultiMap responseHeaders = MultiMap.caseInsensitiveMultiMap();
    responseHeaders.add(MessageHelper.APP_PROPERTY_DEVICE_ID, newDeviceId);
    responseHeaders.add("foo", "bar");
    final Buffer responseBody = Buffer.buffer("changed");
    final HttpResponse<Buffer> httpResponse = mock(HttpResponse.class);
    when(httpResponse.headers()).thenReturn(responseHeaders);
    when(httpResponse.bodyAsBuffer()).thenReturn(responseBody);
    when(httpResponse.statusCode()).thenReturn(HttpURLConnection.HTTP_OK);
    when(mapperWebClient.post(anyInt(), anyString(), anyString())).thenReturn(httpRequest);
    final String topic = String.format("%s/?content-type=%s", TelemetryConstants.TELEMETRY_ENDPOINT, URLEncoder.encode("text/plain", StandardCharsets.UTF_8));
    final MqttPublishMessage message = newMessage(MqttQoS.AT_LEAST_ONCE, topic);
    final MqttContext context = newContext(message, span, new Device(TEST_TENANT_ID, "gateway"));
    final RegistrationAssertion assertion = new RegistrationAssertion("gateway").setDownstreamMessageMapper("mapper");
    messageMapping.mapDownstreamMessage(context, targetAddress, assertion).onComplete(ctx.succeeding(mappedMessage -> {
        ctx.verify(() -> {
            assertThat(mappedMessage.getTargetAddress().getResourceId()).isEqualTo("new-device");
            assertThat(mappedMessage.getPayload()).isEqualTo(responseBody);
            assertThat(mappedMessage.getAdditionalProperties()).doesNotContainKey(MessageHelper.APP_PROPERTY_DEVICE_ID);
            assertThat(mappedMessage.getAdditionalProperties()).containsEntry("foo", "bar");
        });
        ctx.completeNow();
    }));
    final ArgumentCaptor<Handler<AsyncResult<HttpResponse<Buffer>>>> handleCaptor = VertxMockSupport.argumentCaptorHandler();
    verify(httpRequest).sendBuffer(any(Buffer.class), handleCaptor.capture());
    handleCaptor.getValue().handle(Future.succeededFuture(httpResponse));
    final ArgumentCaptor<MultiMap> headersCaptor = ArgumentCaptor.forClass(MultiMap.class);
    verify(httpRequest).putHeaders(headersCaptor.capture());
    final MultiMap addedHeaders = headersCaptor.getValue();
    assertThat(addedHeaders.contains(MessageHelper.APP_PROPERTY_ORIG_ADDRESS, topic, false)).isTrue();
    assertThat(addedHeaders.contains(HttpHeaders.CONTENT_TYPE.toString(), "text/plain", false));
}
Also used : Buffer(io.vertx.core.buffer.Buffer) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) HttpURLConnection(java.net.HttpURLConnection) VertxTestContext(io.vertx.junit5.VertxTestContext) BeforeEach(org.junit.jupiter.api.BeforeEach) MqttQoS(io.netty.handler.codec.mqtt.MqttQoS) HttpResponse(io.vertx.ext.web.client.HttpResponse) WebClient(io.vertx.ext.web.client.WebClient) Command(org.eclipse.hono.client.command.Command) MultiMap(io.vertx.core.MultiMap) MqttEndpoint(io.vertx.mqtt.MqttEndpoint) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) Constants(org.eclipse.hono.util.Constants) RETURNS_SELF(org.mockito.Mockito.RETURNS_SELF) TelemetryConstants(org.eclipse.hono.util.TelemetryConstants) ArgumentCaptor(org.mockito.ArgumentCaptor) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Map(java.util.Map) MqttContext(org.eclipse.hono.adapter.mqtt.MqttContext) TracingMockSupport(org.eclipse.hono.test.TracingMockSupport) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) AsyncResult(io.vertx.core.AsyncResult) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) MapperEndpoint(org.eclipse.hono.config.MapperEndpoint) ServerErrorException(org.eclipse.hono.client.ServerErrorException) HttpHeaders(io.vertx.core.http.HttpHeaders) Mockito.times(org.mockito.Mockito.times) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) Mockito.when(org.mockito.Mockito.when) Truth.assertThat(com.google.common.truth.Truth.assertThat) MessageHelper(org.eclipse.hono.util.MessageHelper) VertxExtension(io.vertx.junit5.VertxExtension) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) Device(org.eclipse.hono.auth.Device) Mockito.verify(org.mockito.Mockito.verify) HttpRequest(io.vertx.ext.web.client.HttpRequest) Test(org.junit.jupiter.api.Test) Mockito.never(org.mockito.Mockito.never) URLEncoder(java.net.URLEncoder) Buffer(io.vertx.core.buffer.Buffer) VertxMockSupport(org.eclipse.hono.test.VertxMockSupport) MqttProtocolAdapterProperties(org.eclipse.hono.adapter.mqtt.MqttProtocolAdapterProperties) Span(io.opentracing.Span) Mockito.withSettings(org.mockito.Mockito.withSettings) Handler(io.vertx.core.Handler) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) Mockito.mock(org.mockito.Mockito.mock) MqttContext(org.eclipse.hono.adapter.mqtt.MqttContext) Device(org.eclipse.hono.auth.Device) Handler(io.vertx.core.Handler) HttpResponse(io.vertx.ext.web.client.HttpResponse) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) MultiMap(io.vertx.core.MultiMap) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) Test(org.junit.jupiter.api.Test)

Aggregations

RegistrationAssertion (org.eclipse.hono.util.RegistrationAssertion)42 Future (io.vertx.core.Future)31 HttpURLConnection (java.net.HttpURLConnection)29 MessageHelper (org.eclipse.hono.util.MessageHelper)29 Map (java.util.Map)27 Span (io.opentracing.Span)26 TenantObject (org.eclipse.hono.util.TenantObject)26 Buffer (io.vertx.core.buffer.Buffer)24 Constants (org.eclipse.hono.util.Constants)22 ServerErrorException (org.eclipse.hono.client.ServerErrorException)21 Device (org.eclipse.hono.auth.Device)20 Test (org.junit.jupiter.api.Test)20 ClientErrorException (org.eclipse.hono.client.ClientErrorException)18 Handler (io.vertx.core.Handler)17 Objects (java.util.Objects)17 ResourceIdentifier (org.eclipse.hono.util.ResourceIdentifier)17 HashMap (java.util.HashMap)16 Command (org.eclipse.hono.client.command.Command)16 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)16 SpanContext (io.opentracing.SpanContext)15