use of io.vertx.core.Promise in project vert.x by eclipse.
the class NodeInfoTest method testFailedFutureForUnknownNode.
@Test
public void testFailedFutureForUnknownNode() {
startNodes(2);
ClusterManager clusterManager = ((VertxInternal) vertices[0]).getClusterManager();
// Create unknown node identifier
String unknown = String.join("", clusterManager.getNodes());
// Needed as callback might be done from non Vert.x thread
disableThreadChecks();
Promise<NodeInfo> promise = Promise.promise();
clusterManager.getNodeInfo(unknown, promise);
promise.future().onComplete(onFailure(t -> testComplete()));
await();
}
use of io.vertx.core.Promise in project vert.x by eclipse.
the class Http1xTLSTest method testSharedServer.
@Test
public void testSharedServer() throws Exception {
int num = VertxOptions.DEFAULT_EVENT_LOOP_POOL_SIZE;
Assume.assumeTrue(num > 1);
List<String> expected = Arrays.asList("chunk-1", "chunk-2", "chunk-3");
client = vertx.createHttpClient(new HttpClientOptions().setMaxPoolSize(num).setSsl(true).setTrustAll(true));
AtomicInteger connCount = new AtomicInteger();
List<String> sessionIds = Collections.synchronizedList(new ArrayList<>());
client.connectionHandler(conn -> {
sessionIds.add(ByteBufUtil.hexDump(conn.sslSession().getId()));
connCount.incrementAndGet();
});
CountDownLatch listenLatch = new CountDownLatch(1);
vertx.deployVerticle(() -> new AbstractVerticle() {
HttpServer server;
@Override
public void start(Promise<Void> startPromise) {
server = vertx.createHttpServer(new HttpServerOptions().setSsl(true).setKeyStoreOptions(Cert.SERVER_JKS.get()).setHost(DEFAULT_HTTPS_HOST).setPort(DEFAULT_HTTPS_PORT)).requestHandler(req -> {
HttpServerResponse resp = req.response().setChunked(true);
expected.forEach(resp::write);
resp.end();
});
server.listen(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST).<Void>mapEmpty().onComplete(startPromise);
}
}, new DeploymentOptions().setInstances(num), onSuccess(v -> listenLatch.countDown()));
awaitLatch(listenLatch);
CountDownLatch connectionLatch = new CountDownLatch(num);
for (int i = 0; i < num; i++) {
client.request(HttpMethod.GET, DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, DEFAULT_TEST_URI).onComplete(onSuccess(request -> {
connectionLatch.countDown();
}));
if (i == 0) {
// Wait until the first connection is established to ensure other connections can reuse the session id
waitUntil(() -> connectionLatch.getCount() == num - 1);
}
}
awaitLatch(connectionLatch);
assertEquals(num, sessionIds.size());
assertEquals(1, new HashSet<>(sessionIds).size());
}
use of io.vertx.core.Promise in project vert.x by eclipse.
the class Http1xClientConnectionTest method testResetStreamRequestSent.
@Test
public void testResetStreamRequestSent() throws Exception {
waitFor(1);
Promise<Void> continuation = Promise.promise();
server.requestHandler(req -> {
continuation.complete();
});
startServer(testAddress);
client.connect(testAddress).onComplete(onSuccess(conn -> {
AtomicInteger evictions = new AtomicInteger();
conn.evictionHandler(v -> {
evictions.incrementAndGet();
});
conn.createStream((ContextInternal) vertx.getOrCreateContext(), onSuccess(stream -> {
Exception cause = new Exception();
stream.closeHandler(v -> {
assertEquals(1, evictions.get());
complete();
});
continuation.future().onSuccess(v -> {
stream.reset(cause);
});
stream.writeHead(new HttpRequestHead(HttpMethod.GET, "/", MultiMap.caseInsensitiveMultiMap(), "localhost:8080", "", null), false, Unpooled.EMPTY_BUFFER, false, new StreamPriority(), false, null);
}));
}));
await();
}
use of io.vertx.core.Promise in project hono by eclipse.
the class KafkaBasedCommandSender method sendCommand.
/**
* {@inheritDoc}
*
* <p>
* The replyId is not used in the Kafka based implementation. It can be set to {@code null}.
* If set it will be ignored.
* <p>
* If the timeout duration is {@code null} then the default timeout value of
* {@value DEFAULT_COMMAND_TIMEOUT_IN_MS} ms is used.
*/
@Override
public Future<DownstreamMessage<KafkaMessageContext>> sendCommand(final String tenantId, final String deviceId, final String command, final String contentType, final Buffer data, final String replyId, final Map<String, Object> properties, final Duration timeout, final SpanContext context) {
Objects.requireNonNull(tenantId);
Objects.requireNonNull(deviceId);
Objects.requireNonNull(command);
final long timeoutInMs = Optional.ofNullable(timeout).map(t -> {
if (t.isNegative()) {
throw new IllegalArgumentException("command timeout duration must be >= 0");
}
return t.toMillis();
}).orElse(DEFAULT_COMMAND_TIMEOUT_IN_MS);
final String correlationId = correlationIdSupplier.get();
final Span span = TracingHelper.buildChildSpan(tracer, context, "send command and receive response", getClass().getSimpleName()).withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).withTag(TracingHelper.TAG_TENANT_ID, tenantId).withTag(TracingHelper.TAG_DEVICE_ID, deviceId).withTag(TracingHelper.TAG_CORRELATION_ID, correlationId).start();
final ExpiringCommandPromise expiringCommandPromise = new ExpiringCommandPromise(correlationId, timeoutInMs, // Remove the corresponding pending response entry if times out
x -> removePendingCommandResponse(tenantId, correlationId), span);
subscribeForCommandResponse(tenantId, span).compose(ok -> {
// Store the correlation id and the expiring command promise
pendingCommandResponses.computeIfAbsent(tenantId, k -> new ConcurrentHashMap<>()).put(correlationId, expiringCommandPromise);
return sendCommand(tenantId, deviceId, command, contentType, data, correlationId, properties, true, "send command", span.context()).onSuccess(sent -> {
LOGGER.debug("sent command [correlation-id: {}], waiting for response", correlationId);
span.log("sent command, waiting for response");
}).onFailure(error -> {
LOGGER.debug("error sending command", error);
// To ensure that the span is not already finished.
if (!expiringCommandPromise.future().isComplete()) {
TracingHelper.logError(span, "error sending command", error);
}
removePendingCommandResponse(tenantId, correlationId);
expiringCommandPromise.tryCompleteAndCancelTimer(Future.failedFuture(error));
});
});
return expiringCommandPromise.future().onComplete(o -> span.finish());
}
use of io.vertx.core.Promise in project hono by eclipse.
the class AmqpServiceBase method startInsecureServer.
private Future<Void> startInsecureServer() {
if (isInsecurePortEnabled()) {
final int insecurePort = determineInsecurePort();
final Promise<Void> result = Promise.promise();
final ProtonServerOptions options = createInsecureServerOptions();
insecureServer = createProtonServer(options).connectHandler(this::onRemoteConnectionOpenInsecurePort).listen(insecurePort, getConfig().getInsecurePortBindAddress(), bindAttempt -> {
if (bindAttempt.succeeded()) {
if (getInsecurePort() == getInsecurePortDefaultValue()) {
log.info("server listens on standard insecure port [{}:{}]", getInsecurePortBindAddress(), getInsecurePort());
} else {
log.warn("server listens on non-standard insecure port [{}:{}], default is {}", getInsecurePortBindAddress(), getInsecurePort(), getInsecurePortDefaultValue());
}
result.complete();
} else {
log.error("cannot bind to insecure port", bindAttempt.cause());
result.fail(bindAttempt.cause());
}
});
return result.future();
} else {
log.info("insecure port is not enabled");
return Future.succeededFuture();
}
}
Aggregations