Search in sources :

Example 36 with RegistrationAssertion

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

the class HttpBasedMessageMapping method mapDownstreamMessageRequest.

private void mapDownstreamMessageRequest(final MqttContext ctx, final ResourceIdentifier targetAddress, final RegistrationAssertion registrationInfo, final MapperEndpoint mapperEndpoint, final Handler<AsyncResult<MappedMessage>> resultHandler) {
    final MultiMap headers = MultiMap.caseInsensitiveMultiMap();
    JsonObject.mapFrom(registrationInfo).forEach(property -> {
        final Object value = property.getValue();
        if (value instanceof String) {
            // prevent strings from being enclosed in quotes
            headers.add(property.getKey(), (String) value);
        } else {
            headers.add(property.getKey(), Json.encode(value));
        }
    });
    headers.add(MessageHelper.APP_PROPERTY_ORIG_ADDRESS, ctx.message().topicName());
    if (ctx.contentType() != null) {
        headers.add(HttpHeaders.CONTENT_TYPE.toString(), ctx.contentType());
    }
    final Promise<MappedMessage> result = Promise.promise();
    webClient.post(mapperEndpoint.getPort(), mapperEndpoint.getHost(), mapperEndpoint.getUri()).putHeaders(headers).ssl(mapperEndpoint.isTlsEnabled()).sendBuffer(ctx.message().payload(), httpResponseAsyncResult -> {
        if (httpResponseAsyncResult.failed()) {
            LOG.debug("failed to map message [origin: {}] using mapping service [host: {}, port: {}, URI: {}]", ctx.authenticatedDevice(), mapperEndpoint.getHost(), mapperEndpoint.getPort(), mapperEndpoint.getUri(), httpResponseAsyncResult.cause());
            result.fail(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, httpResponseAsyncResult.cause()));
        } else {
            final HttpResponse<Buffer> httpResponse = httpResponseAsyncResult.result();
            if (httpResponse.statusCode() == HttpURLConnection.HTTP_OK) {
                final Map<String, String> additionalProperties = new HashMap<>();
                httpResponse.headers().forEach(entry -> additionalProperties.put(entry.getKey(), entry.getValue()));
                final String mappedDeviceId = Optional.ofNullable(additionalProperties.remove(MessageHelper.APP_PROPERTY_DEVICE_ID)).map(id -> {
                    LOG.debug("original {} has been mapped to [device-id: {}]", ctx.authenticatedDevice(), id);
                    return id;
                }).orElseGet(() -> targetAddress.getResourceId());
                result.complete(new MappedMessage(ResourceIdentifier.from(targetAddress.getEndpoint(), targetAddress.getTenantId(), mappedDeviceId), httpResponse.bodyAsBuffer(), additionalProperties));
            } else {
                LOG.debug("mapping service [host: {}, port: {}, URI: {}] returned unexpected status code: {}", mapperEndpoint.getHost(), mapperEndpoint.getPort(), mapperEndpoint.getUri(), httpResponse.statusCode());
                result.fail(new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE, "could not invoke configured mapping service"));
            }
        }
        resultHandler.handle(result.future());
    });
}
Also used : Buffer(io.vertx.core.buffer.Buffer) HttpURLConnection(java.net.HttpURLConnection) Json(io.vertx.core.json.Json) HttpResponse(io.vertx.ext.web.client.HttpResponse) WebClient(io.vertx.ext.web.client.WebClient) Command(org.eclipse.hono.client.command.Command) LoggerFactory(org.slf4j.LoggerFactory) MultiMap(io.vertx.core.MultiMap) HashMap(java.util.HashMap) Map(java.util.Map) MqttContext(org.eclipse.hono.adapter.mqtt.MqttContext) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) JsonObject(io.vertx.core.json.JsonObject) MappedMessage(org.eclipse.hono.adapter.mqtt.MappedMessage) AsyncResult(io.vertx.core.AsyncResult) Strings(org.eclipse.hono.util.Strings) Logger(org.slf4j.Logger) MapperEndpoint(org.eclipse.hono.config.MapperEndpoint) Promise(io.vertx.core.Promise) ServerErrorException(org.eclipse.hono.client.ServerErrorException) HttpHeaders(io.vertx.core.http.HttpHeaders) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) MessageHelper(org.eclipse.hono.util.MessageHelper) Future(io.vertx.core.Future) Objects(java.util.Objects) Buffer(io.vertx.core.buffer.Buffer) MqttProtocolAdapterProperties(org.eclipse.hono.adapter.mqtt.MqttProtocolAdapterProperties) Optional(java.util.Optional) Handler(io.vertx.core.Handler) MessageMapping(org.eclipse.hono.adapter.mqtt.MessageMapping) MultiMap(io.vertx.core.MultiMap) MappedMessage(org.eclipse.hono.adapter.mqtt.MappedMessage) HashMap(java.util.HashMap) JsonObject(io.vertx.core.json.JsonObject) ServerErrorException(org.eclipse.hono.client.ServerErrorException)

Example 37 with RegistrationAssertion

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

the class HttpBasedMessageMappingTest method testMapMessageSucceedsIfNoMapperIsSet.

/**
 * Verifies that the result returned by the mapping service contains the
 * original payload and target address if no downstream mapper has been defined for
 * the gateway.
 *
 * @param ctx The helper to use for running tests on vert.x.
 */
@Test
public void testMapMessageSucceedsIfNoMapperIsSet(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 MqttPublishMessage message = newMessage(MqttQoS.AT_LEAST_ONCE, TelemetryConstants.TELEMETRY_ENDPOINT);
    final MqttContext context = newContext(message, span, new Device(TEST_TENANT_ID, "gateway"));
    messageMapping.mapDownstreamMessage(context, targetAddress, new RegistrationAssertion("gateway")).onComplete(ctx.succeeding(mappedMessage -> {
        ctx.verify(() -> {
            assertThat(mappedMessage.getTargetAddress()).isEqualTo(targetAddress);
            assertThat(mappedMessage.getPayload()).isEqualTo(message.payload());
            assertThat(mappedMessage.getAdditionalProperties()).isEmpty();
            verify(mapperWebClient, never()).post(anyInt(), anyString(), anyString());
        });
        ctx.completeNow();
    }));
}
Also used : 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) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) MqttContext(org.eclipse.hono.adapter.mqtt.MqttContext) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) Device(org.eclipse.hono.auth.Device) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) Test(org.junit.jupiter.api.Test)

Example 38 with RegistrationAssertion

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

the class HttpBasedMessageMappingTest method testMapCommandSucceedsIfNoMapperIsSet.

/**
 * Verifies that the result returned by the mapping service contains the
 * original payload and target address if no upstream mapper has been defined for
 * the gateway.
 *
 * @param ctx The helper to use for running tests on vert.x.
 */
@Test
public void testMapCommandSucceedsIfNoMapperIsSet(final VertxTestContext ctx) {
    config.setMapperEndpoints(Map.of("mapper", MapperEndpoint.from("host", 1234, "/uri", false)));
    final Command command = mock(Command.class);
    final Buffer payload = Buffer.buffer("payload");
    when(command.getPayload()).thenReturn(payload);
    messageMapping.mapUpstreamMessage(new RegistrationAssertion("gateway"), command).onComplete(ctx.succeeding(mappedBuffer -> {
        ctx.verify(() -> {
            assertThat(mappedBuffer).isEqualTo(payload);
            verify(mapperWebClient, never()).post(anyInt(), anyString(), anyString());
        });
        ctx.completeNow();
    }));
}
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) Test(org.junit.jupiter.api.Test)

Example 39 with RegistrationAssertion

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

the class HttpBasedMessageMappingTest method testMapMessageSucceedsIfNoMapperEndpointIsConfigured.

/**
 * Verifies that the result returned by the mapping service contains the
 * original payload and target address if no downstream mapper endpoint has been configured
 * for the adapter.
 *
 * @param ctx The helper to use for running tests on vert.x.
 */
@Test
public void testMapMessageSucceedsIfNoMapperEndpointIsConfigured(final VertxTestContext ctx) {
    final ResourceIdentifier targetAddress = ResourceIdentifier.from(TelemetryConstants.TELEMETRY_ENDPOINT, TEST_TENANT_ID, "gateway");
    final MqttPublishMessage message = newMessage(MqttQoS.AT_LEAST_ONCE, TelemetryConstants.TELEMETRY_ENDPOINT);
    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()).isEqualTo(targetAddress);
            assertThat(mappedMessage.getPayload()).isEqualTo(message.payload());
            assertThat(mappedMessage.getAdditionalProperties()).isEmpty();
            verify(mapperWebClient, never()).post(anyInt(), anyString(), anyString());
        });
        ctx.completeNow();
    }));
}
Also used : 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) ResourceIdentifier(org.eclipse.hono.util.ResourceIdentifier) MqttContext(org.eclipse.hono.adapter.mqtt.MqttContext) MqttPublishMessage(io.vertx.mqtt.messages.MqttPublishMessage) Device(org.eclipse.hono.auth.Device) RegistrationAssertion(org.eclipse.hono.util.RegistrationAssertion) Test(org.junit.jupiter.api.Test)

Example 40 with RegistrationAssertion

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

the class HttpBasedMessageMappingTest method testMapCommandSucceedsIfNoMapperEndpointIsConfigured.

/**
 * Verifies that the result returned by the mapping service contains the
 * original payload and target address if no upstream mapper endpoint has been configured
 * for the adapter.
 *
 * @param ctx The helper to use for running tests on vert.x.
 */
@Test
public void testMapCommandSucceedsIfNoMapperEndpointIsConfigured(final VertxTestContext ctx) {
    final RegistrationAssertion assertion = new RegistrationAssertion("gateway").setUpstreamMessageMapper("mapper");
    final Command command = mock(Command.class);
    final Buffer payload = Buffer.buffer("payload");
    when(command.getPayload()).thenReturn(payload);
    messageMapping.mapUpstreamMessage(assertion, command).onComplete(ctx.succeeding(mappedBuffer -> {
        ctx.verify(() -> {
            assertThat(mappedBuffer).isEqualTo(payload);
            verify(mapperWebClient, never()).post(anyInt(), anyString(), anyString());
        });
        ctx.completeNow();
    }));
}
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) 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