use of io.vertx.ext.web.client.HttpResponse in project vertx-web by vert-x3.
the class OpenAPI3ParametersUnitTest method testQueryFormExplodeArray.
/**
* Test: query_form_explode_array
* Expected parameters sent:
* color: color=blue&color=black&color=brown
* Expected response: {"color":["blue","black","brown"]}
* @throws Exception
*/
@Test
public void testQueryFormExplodeArray() throws Exception {
routerFactory.addHandlerByOperationId("query_form_explode_array", routingContext -> {
RequestParameters params = routingContext.get("parsedParameters");
JsonObject res = new JsonObject();
RequestParameter color_query = params.queryParameter("color");
assertNotNull(color_query);
assertTrue(color_query.isArray());
res.put("color", new JsonArray(color_query.getArray().stream().map(param -> param.getString()).collect(Collectors.toList())));
routingContext.response().setStatusCode(200).setStatusMessage("OK").putHeader("content-type", "application/json; charset=utf-8").end(res.encode());
});
CountDownLatch latch = new CountDownLatch(1);
List<Object> color_query;
color_query = new ArrayList<>();
color_query.add("blue");
color_query.add("black");
color_query.add("brown");
startServer();
apiClient.queryFormExplodeArray(color_query, (AsyncResult<HttpResponse> ar) -> {
if (ar.succeeded()) {
assertEquals(200, ar.result().statusCode());
assertTrue("Expected: " + new JsonObject("{\"color\":[\"blue\",\"black\",\"brown\"]}").encode() + " Actual: " + ar.result().bodyAsJsonObject().encode(), new JsonObject("{\"color\":[\"blue\",\"black\",\"brown\"]}").equals(ar.result().bodyAsJsonObject()));
} else {
assertTrue(ar.cause().getMessage(), false);
}
latch.countDown();
});
awaitLatch(latch);
}
use of io.vertx.ext.web.client.HttpResponse in project vertx-web by vert-x3.
the class OpenAPI3ParametersUnitTest method testPathLabelNoexplodeArray.
/**
* Test: path_label_noexplode_array
* Expected parameters sent:
* color: .blue.black.brown
* Expected response: {"color":["blue","black","brown"]}
* @throws Exception
*/
@Test
public void testPathLabelNoexplodeArray() throws Exception {
routerFactory.addHandlerByOperationId("path_label_noexplode_array", routingContext -> {
RequestParameters params = routingContext.get("parsedParameters");
JsonObject res = new JsonObject();
RequestParameter color_path = params.pathParameter("color");
assertNotNull(color_path);
assertTrue(color_path.isArray());
res.put("color", new JsonArray(color_path.getArray().stream().map(param -> param.getString()).collect(Collectors.toList())));
routingContext.response().setStatusCode(200).setStatusMessage("OK").putHeader("content-type", "application/json; charset=utf-8").end(res.encode());
});
CountDownLatch latch = new CountDownLatch(1);
List<Object> color_path;
color_path = new ArrayList<>();
color_path.add("blue");
color_path.add("black");
color_path.add("brown");
startServer();
apiClient.pathLabelNoexplodeArray(color_path, (AsyncResult<HttpResponse> ar) -> {
if (ar.succeeded()) {
assertEquals(200, ar.result().statusCode());
assertTrue("Expected: " + new JsonObject("{\"color\":[\"blue\",\"black\",\"brown\"]}").encode() + " Actual: " + ar.result().bodyAsJsonObject().encode(), new JsonObject("{\"color\":[\"blue\",\"black\",\"brown\"]}").equals(ar.result().bodyAsJsonObject()));
} else {
assertTrue(ar.cause().getMessage(), false);
}
latch.countDown();
});
awaitLatch(latch);
}
use of io.vertx.ext.web.client.HttpResponse in project vertx-web by vert-x3.
the class OpenAPI3ParametersUnitTest method testHeaderSimpleNoexplodeArray.
/**
* Test: header_simple_noexplode_array
* Expected parameters sent:
* color: blue,black,brown
* Expected response: {"color":["blue","black","brown"]}
* @throws Exception
*/
@Test
public void testHeaderSimpleNoexplodeArray() throws Exception {
routerFactory.addHandlerByOperationId("header_simple_noexplode_array", routingContext -> {
RequestParameters params = routingContext.get("parsedParameters");
JsonObject res = new JsonObject();
RequestParameter color_header = params.headerParameter("color");
assertNotNull(color_header);
assertTrue(color_header.isArray());
res.put("color", new JsonArray(color_header.getArray().stream().map(param -> param.getString()).collect(Collectors.toList())));
routingContext.response().setStatusCode(200).setStatusMessage("OK").putHeader("content-type", "application/json; charset=utf-8").end(res.encode());
});
CountDownLatch latch = new CountDownLatch(1);
List<Object> color_header;
color_header = new ArrayList<>();
color_header.add("blue");
color_header.add("black");
color_header.add("brown");
startServer();
apiClient.headerSimpleNoexplodeArray(color_header, (AsyncResult<HttpResponse> ar) -> {
if (ar.succeeded()) {
assertEquals(200, ar.result().statusCode());
assertTrue("Expected: " + new JsonObject("{\"color\":[\"blue\",\"black\",\"brown\"]}").encode() + " Actual: " + ar.result().bodyAsJsonObject().encode(), new JsonObject("{\"color\":[\"blue\",\"black\",\"brown\"]}").equals(ar.result().bodyAsJsonObject()));
} else {
assertTrue(ar.cause().getMessage(), false);
}
latch.countDown();
});
awaitLatch(latch);
}
use of io.vertx.ext.web.client.HttpResponse in project hono by eclipse.
the class HttpTestBase method testHandleConcurrentUploadWithTtd.
/**
* Verifies that for two consecutive upload requests containing a TTD, sent in close succession so that the command
* triggered by the first request isn't sent before the adapter has received the second upload request, the HTTP
* adapter returns the command as response to the second upload request.
*
* @param ctx The test context.
* @throws InterruptedException if the test is interrupted before having completed.
*/
@Test
@Timeout(timeUnit = TimeUnit.SECONDS, value = 20)
public void testHandleConcurrentUploadWithTtd(final VertxTestContext ctx) throws InterruptedException {
final Tenant tenant = new Tenant();
final CountDownLatch firstMessageReceived = new CountDownLatch(1);
final CountDownLatch secondMessageReceived = new CountDownLatch(1);
// GIVEN a registered device
final VertxTestContext setup = new VertxTestContext();
helper.registry.addDeviceForTenant(tenantId, tenant, deviceId, PWD).compose(ok -> createConsumer(tenantId, msg -> {
logger.trace("received message: {}", msg);
msg.getTimeUntilDisconnectNotification().ifPresent(notification -> {
logger.debug("processing piggy backed message [ttd: {}]", notification.getTtd());
ctx.verify(() -> {
assertThat(notification.getTenantId()).isEqualTo(tenantId);
assertThat(notification.getDeviceId()).isEqualTo(deviceId);
});
});
switch(msg.getContentType()) {
case "text/msg1":
logger.debug("received first message");
firstMessageReceived.countDown();
break;
case "text/msg2":
logger.debug("received second message");
secondMessageReceived.countDown();
break;
default:
}
})).compose(c -> {
// might fail immediately because the link has not been established yet.
return httpClient.create(getEndpointUri(), Buffer.buffer("trigger msg"), MultiMap.caseInsensitiveMultiMap().add(HttpHeaders.CONTENT_TYPE, "application/trigger").add(HttpHeaders.AUTHORIZATION, authorization).add(HttpHeaders.ORIGIN, ORIGIN_URI).add(Constants.HEADER_QOS_LEVEL, "1"), ResponsePredicate.status(200, 300));
}).onComplete(setup.succeedingThenComplete());
assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue();
if (setup.failed()) {
ctx.failNow(setup.causeOfFailure());
return;
}
// WHEN the device sends a first upload request
MultiMap requestHeaders = MultiMap.caseInsensitiveMultiMap().add(HttpHeaders.CONTENT_TYPE, "text/msg1").add(HttpHeaders.AUTHORIZATION, authorization).add(HttpHeaders.ORIGIN, ORIGIN_URI).add(Constants.HEADER_TIME_TILL_DISCONNECT, "10");
final Future<HttpResponse<Buffer>> firstRequest = httpClient.create(getEndpointUri(), Buffer.buffer("hello one"), requestHeaders, ResponsePredicate.status(200, 300)).map(httpResponse -> {
logger.info("received response to first request");
return httpResponse;
});
logger.info("sent first request");
if (!firstMessageReceived.await(5, TimeUnit.SECONDS)) {
ctx.failNow(new IllegalStateException("first message not received in time"));
}
// followed by a second request
requestHeaders = MultiMap.caseInsensitiveMultiMap().add(HttpHeaders.CONTENT_TYPE, "text/msg2").add(HttpHeaders.AUTHORIZATION, authorization).add(HttpHeaders.ORIGIN, ORIGIN_URI).add(Constants.HEADER_TIME_TILL_DISCONNECT, "5");
final Future<HttpResponse<Buffer>> secondRequest = httpClient.create(getEndpointUri(), Buffer.buffer("hello two"), requestHeaders, ResponsePredicate.status(200, 300)).map(httpResponse -> {
logger.info("received response to second request");
return httpResponse;
});
logger.info("sent second request");
// wait for messages having been received
if (!secondMessageReceived.await(5, TimeUnit.SECONDS)) {
ctx.failNow(new IllegalStateException("second message not received in time"));
}
// send command
final JsonObject inputData = new JsonObject().put(COMMAND_JSON_KEY, (int) (Math.random() * 100));
final Future<Void> commandSent = helper.sendOneWayCommand(tenantId, deviceId, COMMAND_TO_SEND, "application/json", inputData.toBuffer(), 3000);
logger.info("sent one-way command to device");
// THEN both requests succeed
CompositeFuture.all(commandSent, firstRequest, secondRequest).onComplete(ctx.succeeding(ok -> {
ctx.verify(() -> {
// and the response to the second request contains a command
assertThat(secondRequest.result().getHeader(Constants.HEADER_COMMAND)).isEqualTo(COMMAND_TO_SEND);
// while the response to the first request is empty
assertThat(firstRequest.result().getHeader(Constants.HEADER_COMMAND)).isNull();
});
ctx.completeNow();
}));
}
use of io.vertx.ext.web.client.HttpResponse in project hono by eclipse.
the class HttpTestBase method testUploadMessages.
/**
* Uploads messages to the HTTP endpoint.
*
* @param ctx The test context to run on.
* @param tenantId The tenant that the device belongs to.
* @param messageConsumer Consumer that is invoked when a message was received.
* @param requestSender The test device that will publish the data.
* @param numberOfMessages The number of messages that are uploaded.
* @param expectedQos The expected QoS level, may be {@code null} leading to expecting the default for event or telemetry.
* @throws InterruptedException if the test is interrupted before it has finished.
*/
protected void testUploadMessages(final VertxTestContext ctx, final String tenantId, final Function<DownstreamMessage<? extends MessageContext>, Future<Void>> messageConsumer, final Function<Integer, Future<HttpResponse<Buffer>>> requestSender, final int numberOfMessages, final QoS expectedQos) throws InterruptedException {
final VertxTestContext messageSending = new VertxTestContext();
final Checkpoint messageSent = messageSending.checkpoint(numberOfMessages);
final Checkpoint messageReceived = messageSending.laxCheckpoint(numberOfMessages);
final AtomicInteger receivedMessageCount = new AtomicInteger(0);
final VertxTestContext setup = new VertxTestContext();
createConsumer(tenantId, msg -> {
logger.trace("received {}", msg);
ctx.verify(() -> {
DownstreamMessageAssertions.assertTelemetryMessageProperties(msg, tenantId);
assertThat(msg.getQos()).isEqualTo(getExpectedQoS(expectedQos));
assertAdditionalMessageProperties(msg);
});
Optional.ofNullable(messageConsumer).map(consumer -> consumer.apply(msg)).orElseGet(() -> Future.succeededFuture()).onComplete(attempt -> {
if (attempt.succeeded()) {
receivedMessageCount.incrementAndGet();
messageReceived.flag();
} else {
logger.error("failed to process message from device", attempt.cause());
messageSending.failNow(attempt.cause());
}
});
if (receivedMessageCount.get() % 20 == 0) {
logger.info("messages received: {}", receivedMessageCount.get());
}
}).onComplete(setup.succeedingThenComplete());
assertThat(setup.awaitCompletion(5, TimeUnit.SECONDS)).isTrue();
if (setup.failed()) {
ctx.failNow(setup.causeOfFailure());
return;
}
final long start = System.currentTimeMillis();
int messageCount = 0;
while (messageCount < numberOfMessages && !messageSending.failed()) {
messageCount++;
final int currentMessage = messageCount;
final CountDownLatch sending = new CountDownLatch(1);
requestSender.apply(currentMessage).compose(this::assertHttpResponse).onComplete(attempt -> {
try {
if (attempt.succeeded()) {
logger.debug("sent message {}", currentMessage);
messageSent.flag();
} else {
logger.info("failed to send message {}: {}", currentMessage, attempt.cause().getMessage());
messageSending.failNow(attempt.cause());
}
} finally {
sending.countDown();
}
});
sending.await();
if (currentMessage % 20 == 0) {
logger.info("messages sent: " + currentMessage);
}
}
final long timeToWait = Math.max(TEST_TIMEOUT_MILLIS - 50 - (System.currentTimeMillis() - testStartTimeMillis), 1);
assertThat(messageSending.awaitCompletion(timeToWait, TimeUnit.MILLISECONDS)).isTrue();
if (messageSending.failed()) {
logger.error("test execution failed", messageSending.causeOfFailure());
ctx.failNow(messageSending.causeOfFailure());
} else {
logger.info("successfully sent {} and received {} messages after {} milliseconds", messageCount, receivedMessageCount.get(), System.currentTimeMillis() - start);
ctx.completeNow();
}
}
Aggregations