Search in sources :

Example 31 with HttpResponse

use of io.vertx.ext.web.client.HttpResponse in project hono by eclipse.

the class HttpTestBase method testUploadMessagesWithTtdThatReplyWithOneWayCommand.

/**
 * Verifies that the HTTP adapter delivers a command to a device and accepts the corresponding
 * response from the device.
 *
 * @param endpointConfig The endpoints to use for sending/receiving commands.
 * @param ctx The test context.
 * @throws InterruptedException if the test fails.
 */
@ParameterizedTest(name = IntegrationTestSupport.PARAMETERIZED_TEST_NAME_PATTERN)
@MethodSource("commandAndControlVariants")
public void testUploadMessagesWithTtdThatReplyWithOneWayCommand(final HttpCommandEndpointConfiguration endpointConfig, final VertxTestContext ctx) throws InterruptedException {
    final Tenant tenant = new Tenant();
    final VertxTestContext setup = new VertxTestContext();
    final MultiMap requestHeaders = MultiMap.caseInsensitiveMultiMap().add(HttpHeaders.CONTENT_TYPE, "text/plain").add(HttpHeaders.AUTHORIZATION, authorization).add(HttpHeaders.ORIGIN, ORIGIN_URI).add(Constants.HEADER_TIME_TILL_DISCONNECT, "4");
    helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, PWD).onComplete(setup.succeedingThenComplete());
    assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue();
    if (setup.failed()) {
        ctx.failNow(setup.causeOfFailure());
        return;
    }
    final String commandTargetDeviceId = endpointConfig.isSubscribeAsGateway() ? helper.setupGatewayDeviceBlocking(tenantId, deviceId, 5) : deviceId;
    final String subscribingDeviceId = endpointConfig.isSubscribeAsGatewayForSingleDevice() ? commandTargetDeviceId : deviceId;
    testUploadMessages(ctx, tenantId, msg -> {
        return msg.getTimeUntilDisconnectNotification().map(notification -> {
            logger.trace("received piggy backed message [ttd: {}]: {}", notification.getTtd(), msg);
            ctx.verify(() -> {
                assertThat(notification.getTenantId()).isEqualTo(tenantId);
                assertThat(notification.getDeviceId()).isEqualTo(subscribingDeviceId);
            });
            // now ready to send a command
            final JsonObject inputData = new JsonObject().put(COMMAND_JSON_KEY, (int) (Math.random() * 100));
            return helper.sendOneWayCommand(tenantId, commandTargetDeviceId, COMMAND_TO_SEND, "application/json", inputData.toBuffer(), notification.getMillisecondsUntilExpiry());
        }).orElseGet(Future::succeededFuture);
    }, count -> {
        final Buffer payload = Buffer.buffer("hello " + count);
        return sendHttpRequestForGatewayOrDevice(payload, requestHeaders, endpointConfig, commandTargetDeviceId, true).map(httpResponse -> {
            ctx.verify(() -> {
                // assert that the response contains a one-way command
                assertWithMessage("response no. %s '%s' header", count, Constants.HEADER_COMMAND).that(httpResponse.getHeader(Constants.HEADER_COMMAND)).isNotNull();
                assertThat(httpResponse.getHeader(Constants.HEADER_COMMAND)).isEqualTo(COMMAND_TO_SEND);
                assertThat(httpResponse.getHeader(HttpHeaders.CONTENT_TYPE.toString())).isEqualTo("application/json");
                assertThat(httpResponse.getHeader(Constants.HEADER_COMMAND_REQUEST_ID)).isNull();
            });
            return httpResponse;
        });
    });
}
Also used : HttpURLConnection(java.net.HttpURLConnection) KeyPair(java.security.KeyPair) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) ResponsePredicate(io.vertx.ext.web.client.predicate.ResponsePredicate) DownstreamMessage(org.eclipse.hono.application.client.DownstreamMessage) LoggerFactory(org.slf4j.LoggerFactory) MultiMap(io.vertx.core.MultiMap) Tenant(org.eclipse.hono.service.management.tenant.Tenant) Timeout(io.vertx.junit5.Timeout) GeneralSecurityException(java.security.GeneralSecurityException) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BeforeAll(org.junit.jupiter.api.BeforeAll) JsonObject(io.vertx.core.json.JsonObject) Tenants(org.eclipse.hono.tests.Tenants) MethodSource(org.junit.jupiter.params.provider.MethodSource) Device(org.eclipse.hono.service.management.device.Device) MessageContext(org.eclipse.hono.application.client.MessageContext) SubscriberRole(org.eclipse.hono.tests.CommandEndpointConfiguration.SubscriberRole) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) MetricsTags(org.eclipse.hono.service.metric.MetricsTags) Set(java.util.Set) HttpHeaders(io.vertx.core.http.HttpHeaders) DownstreamMessageAssertions(org.eclipse.hono.tests.DownstreamMessageAssertions) UUID(java.util.UUID) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) TestInfo(org.junit.jupiter.api.TestInfo) Test(org.junit.jupiter.api.Test) CountDownLatch(java.util.concurrent.CountDownLatch) Base64(java.util.Base64) Stream(java.util.stream.Stream) Buffer(io.vertx.core.buffer.Buffer) Optional(java.util.Optional) Checkpoint(io.vertx.junit5.Checkpoint) QoS(org.eclipse.hono.util.QoS) VertxTestContext(io.vertx.junit5.VertxTestContext) X500Principal(javax.security.auth.x500.X500Principal) HttpResponse(io.vertx.ext.web.client.HttpResponse) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) Function(java.util.function.Function) Constants(org.eclipse.hono.util.Constants) CompositeFuture(io.vertx.core.CompositeFuture) HttpClientOptions(io.vertx.core.http.HttpClientOptions) PemTrustOptions(io.vertx.core.net.PemTrustOptions) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) Logger(org.slf4j.Logger) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) Truth.assertThat(com.google.common.truth.Truth.assertThat) TimeUnit(java.util.concurrent.TimeUnit) Adapter(org.eclipse.hono.util.Adapter) AfterEach(org.junit.jupiter.api.AfterEach) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) CrudHttpClient(org.eclipse.hono.tests.CrudHttpClient) MessageConsumer(org.eclipse.hono.application.client.MessageConsumer) Handler(io.vertx.core.Handler) Collections(java.util.Collections) Buffer(io.vertx.core.buffer.Buffer) MultiMap(io.vertx.core.MultiMap) Tenant(org.eclipse.hono.service.management.tenant.Tenant) VertxTestContext(io.vertx.junit5.VertxTestContext) JsonObject(io.vertx.core.json.JsonObject) Future(io.vertx.core.Future) CompositeFuture(io.vertx.core.CompositeFuture) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 32 with HttpResponse

use of io.vertx.ext.web.client.HttpResponse in project hono by eclipse.

the class DeviceManagementIT method testUpdateDeviceSucceeds.

/**
 * Verifies that the registration information provided when updating
 * a device replaces the existing information.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testUpdateDeviceSucceeds(final VertxTestContext ctx) {
    final JsonObject originalData = new JsonObject().put("ext", new JsonObject().put("key1", "value1").put("key2", "value2")).put(RegistrationConstants.FIELD_ENABLED, Boolean.TRUE);
    final JsonObject updatedData = new JsonObject().put("ext", new JsonObject().put("newKey1", "newValue1")).put(RegistrationConstants.FIELD_ENABLED, Boolean.FALSE);
    final AtomicReference<String> latestVersion = new AtomicReference<>();
    final AtomicReference<Instant> creationTime = new AtomicReference<>();
    registry.registerDevice(tenantId, deviceId, originalData.mapTo(Device.class)).compose(httpResponse -> {
        latestVersion.set(httpResponse.getHeader(HttpHeaders.ETAG.toString()));
        ctx.verify(() -> assertThat(latestVersion.get()).isNotNull());
        return registry.getRegistrationInfo(tenantId, deviceId);
    }).compose(httpResponse -> {
        final String resourceVersion = httpResponse.getHeader(HttpHeaders.ETAG.toString());
        ctx.verify(() -> {
            assertThat(latestVersion.get()).isEqualTo(resourceVersion);
            final var deviceStatus = getDeviceStatus(httpResponse.bodyAsJsonObject());
            assertThat(deviceStatus).isNotNull();
            assertThat(deviceStatus.getCreationTime()).isNotNull();
            assertThat(deviceStatus.getLastUpdate()).isNull();
            creationTime.set(deviceStatus.getCreationTime());
        });
        return registry.updateDevice(tenantId, deviceId, updatedData);
    }).compose(httpResponse -> {
        final String updatedVersion = httpResponse.getHeader(HttpHeaders.ETAG.toString());
        ctx.verify(() -> {
            assertThat(updatedVersion).isNotNull();
            assertThat(updatedVersion).isNotEqualTo(latestVersion.get());
            latestVersion.set(updatedVersion);
        });
        return registry.getRegistrationInfo(tenantId, deviceId);
    }).onComplete(ctx.succeeding(httpResponse -> {
        final String resourceVersion = httpResponse.getHeader(HttpHeaders.ETAG.toString());
        ctx.verify(() -> {
            assertThat(latestVersion.get()).isEqualTo(resourceVersion);
            assertRegistrationInformation(httpResponse, updatedData.mapTo(Device.class), creationTime.get(), true);
        });
        ctx.completeNow();
    }));
}
Also used : HttpURLConnection(java.net.HttpURLConnection) VertxTestContext(io.vertx.junit5.VertxTestContext) BeforeEach(org.junit.jupiter.api.BeforeEach) Arrays(java.util.Arrays) HttpResponse(io.vertx.ext.web.client.HttpResponse) MultiMap(io.vertx.core.MultiMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Nested(org.junit.jupiter.api.Nested) Timeout(io.vertx.junit5.Timeout) CompositeFuture(io.vertx.core.CompositeFuture) Matcher(java.util.regex.Matcher) IntegrationTestSupport(org.eclipse.hono.tests.IntegrationTestSupport) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) SearchResult(org.eclipse.hono.service.management.SearchResult) Map(java.util.Map) Assertions(org.assertj.core.api.Assertions) JsonObject(io.vertx.core.json.JsonObject) TypeReference(com.fasterxml.jackson.core.type.TypeReference) RegistryManagementConstants(org.eclipse.hono.util.RegistryManagementConstants) EnabledIf(org.junit.jupiter.api.condition.EnabledIf) Device(org.eclipse.hono.service.management.device.Device) DeviceWithId(org.eclipse.hono.service.management.device.DeviceWithId) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) JacksonCodec(io.vertx.core.json.jackson.JacksonCodec) HttpHeaders(io.vertx.core.http.HttpHeaders) RegistrationConstants(org.eclipse.hono.util.RegistrationConstants) Truth.assertThat(com.google.common.truth.Truth.assertThat) Instant(java.time.Instant) DeviceStatus(org.eclipse.hono.service.management.device.DeviceStatus) VertxExtension(io.vertx.junit5.VertxExtension) TimeUnit(java.util.concurrent.TimeUnit) Test(org.junit.jupiter.api.Test) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) CrudHttpClient(org.eclipse.hono.tests.CrudHttpClient) DeviceRegistryHttpClient(org.eclipse.hono.tests.DeviceRegistryHttpClient) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) Device(org.eclipse.hono.service.management.device.Device) Instant(java.time.Instant) JsonObject(io.vertx.core.json.JsonObject) AtomicReference(java.util.concurrent.atomic.AtomicReference) Test(org.junit.jupiter.api.Test)

Example 33 with HttpResponse

use of io.vertx.ext.web.client.HttpResponse 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 34 with HttpResponse

use of io.vertx.ext.web.client.HttpResponse in project vertx-swagger by bobxwang.

the class IndexVerticleTest method TestIndex.

@Test
public void TestIndex(TestContext context) {
    Async async = context.async();
    VertxOptions vertxOptions = new VertxOptions();
    vertxOptions.setMaxEventLoopExecuteTime(Long.MAX_VALUE);
    vertxOptions.setMaxWorkerExecuteTime(Long.MAX_VALUE);
    final Vertx vertx = Vertx.vertx(vertxOptions);
    vertx.createHttpServer().requestHandler(req -> req.response().putHeader("Content-Type", "text/plain").end("OK")).listen(8080, context.asyncAssertSuccess(s -> {
        WebClient webClient = WebClient.create(vertx);
        webClient.get(8080, "localhost", "/").send(ar -> {
            if (ar.succeeded()) {
                HttpResponse<Buffer> response = ar.result();
                context.assertTrue(response.headers().contains("Content-Type"));
                context.assertEquals("text/plain", response.getHeader("Content-Type"));
                context.assertEquals("OK", response.bodyAsString());
                webClient.close();
                async.complete();
            } else {
                async.resolve(Future.failedFuture(ar.cause()));
            }
        });
    }));
    async.awaitSuccess(5000);
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) HttpResponse(io.vertx.ext.web.client.HttpResponse) Buffer(io.vertx.core.buffer.Buffer) WebClient(io.vertx.ext.web.client.WebClient) Vertx(io.vertx.core.Vertx) RunWith(org.junit.runner.RunWith) VertxOptions(io.vertx.core.VertxOptions) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) Future(io.vertx.core.Future) Async(io.vertx.ext.unit.Async) HttpResponse(io.vertx.ext.web.client.HttpResponse) Vertx(io.vertx.core.Vertx) VertxOptions(io.vertx.core.VertxOptions) WebClient(io.vertx.ext.web.client.WebClient) Test(org.junit.Test)

Aggregations

HttpResponse (io.vertx.ext.web.client.HttpResponse)34 JsonObject (io.vertx.core.json.JsonObject)28 Handler (io.vertx.core.Handler)27 Map (java.util.Map)27 StandardCharsets (java.nio.charset.StandardCharsets)25 AsyncResult (io.vertx.core.AsyncResult)22 List (java.util.List)22 CountDownLatch (java.util.concurrent.CountDownLatch)21 HashMap (java.util.HashMap)20 ArrayList (java.util.ArrayList)19 Test (org.junit.Test)18 OpenAPI (io.swagger.v3.oas.models.OpenAPI)17 OpenAPIV3Parser (io.swagger.v3.parser.OpenAPIV3Parser)17 ParseOptions (io.swagger.v3.parser.core.models.ParseOptions)17 Buffer (io.vertx.core.buffer.Buffer)17 HttpServerOptions (io.vertx.core.http.HttpServerOptions)17 JsonArray (io.vertx.core.json.JsonArray)17 RoutingContext (io.vertx.ext.web.RoutingContext)17 RequestParameter (io.vertx.ext.web.api.RequestParameter)17 RequestParameters (io.vertx.ext.web.api.RequestParameters)17