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;
});
});
}
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();
}));
}
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());
});
}
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);
}
Aggregations