use of io.vertx.core.AsyncResult in project vert.x by eclipse.
the class AsynchronousLockTest method testAcquireOnExecuteBlocking.
@Test
public void testAcquireOnExecuteBlocking() {
Vertx vertx = getVertx();
SharedData sharedData = vertx.sharedData();
AtomicReference<Long> start = new AtomicReference<>();
vertx.<Lock>executeBlocking(future -> {
CountDownLatch acquireLatch = new CountDownLatch(1);
AtomicReference<AsyncResult<Lock>> lockReference = new AtomicReference<>();
sharedData.getLock("foo", ar -> {
lockReference.set(ar);
acquireLatch.countDown();
});
try {
awaitLatch(acquireLatch);
AsyncResult<Lock> ar = lockReference.get();
if (ar.succeeded()) {
future.complete(ar.result());
} else {
future.fail(ar.cause());
}
} catch (InterruptedException e) {
future.fail(e);
}
}, ar -> {
if (ar.succeeded()) {
start.set(System.currentTimeMillis());
vertx.setTimer(1000, tid -> {
ar.result().release();
});
vertx.executeBlocking(future -> {
CountDownLatch acquireLatch = new CountDownLatch(1);
AtomicReference<AsyncResult<Lock>> lockReference = new AtomicReference<>();
sharedData.getLock("foo", ar2 -> {
lockReference.set(ar2);
acquireLatch.countDown();
});
try {
awaitLatch(acquireLatch);
AsyncResult<Lock> ar3 = lockReference.get();
if (ar3.succeeded()) {
future.complete(ar3.result());
} else {
future.fail(ar3.cause());
}
} catch (InterruptedException e) {
future.fail(e);
}
}, ar4 -> {
if (ar4.succeeded()) {
assertTrue(System.currentTimeMillis() - start.get() >= 1000);
testComplete();
} else {
fail(ar4.cause());
}
});
} else {
fail(ar.cause());
}
});
await();
}
use of io.vertx.core.AsyncResult in project vert.x by eclipse.
the class NetClientImpl method connect.
private void connect(int port, String host, Handler<AsyncResult<NetSocket>> connectHandler, int remainingAttempts) {
Objects.requireNonNull(host, "No null host accepted");
Objects.requireNonNull(connectHandler, "No null connectHandler accepted");
ContextImpl context = vertx.getOrCreateContext();
sslHelper.validate(vertx);
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(context.nettyEventLoop());
bootstrap.channel(NioSocketChannel.class);
applyConnectionOptions(bootstrap);
ChannelProvider channelProvider;
if (options.getProxyOptions() == null) {
channelProvider = ChannelProvider.INSTANCE;
} else {
channelProvider = ProxyChannelProvider.INSTANCE;
}
Handler<Channel> channelInitializer = ch -> {
if (sslHelper.isSSL()) {
SslHandler sslHandler = sslHelper.createSslHandler(vertx, host, port);
ch.pipeline().addLast("ssl", sslHandler);
}
ChannelPipeline pipeline = ch.pipeline();
if (logEnabled) {
pipeline.addLast("logging", new LoggingHandler());
}
if (sslHelper.isSSL()) {
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
}
if (options.getIdleTimeout() > 0) {
pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout()));
}
pipeline.addLast("handler", new VertxNetHandler<NetSocketImpl>(ch, socketMap) {
@Override
protected void handleMsgReceived(Object msg) {
ByteBuf buf = (ByteBuf) msg;
conn.handleDataReceived(Buffer.buffer(buf));
}
});
};
Handler<AsyncResult<Channel>> channelHandler = res -> {
if (res.succeeded()) {
Channel ch = res.result();
if (sslHelper.isSSL()) {
SslHandler sslHandler = (SslHandler) ch.pipeline().get("ssl");
io.netty.util.concurrent.Future<Channel> fut = sslHandler.handshakeFuture();
fut.addListener(future2 -> {
if (future2.isSuccess()) {
connected(context, ch, connectHandler, host, port);
} else {
failed(context, ch, future2.cause(), connectHandler);
}
});
} else {
connected(context, ch, connectHandler, host, port);
}
} else {
if (remainingAttempts > 0 || remainingAttempts == -1) {
context.executeFromIO(() -> {
log.debug("Failed to create connection. Will retry in " + options.getReconnectInterval() + " milliseconds");
vertx.setTimer(options.getReconnectInterval(), tid -> connect(port, host, connectHandler, remainingAttempts == -1 ? remainingAttempts : remainingAttempts - 1));
});
} else {
failed(context, null, res.cause(), connectHandler);
}
}
};
channelProvider.connect(vertx, bootstrap, options.getProxyOptions(), host, port, channelInitializer, channelHandler);
}
use of io.vertx.core.AsyncResult in project vert.x by eclipse.
the class HttpTest method sendFile.
private void sendFile(String fileName, String contentExpected, boolean handler) throws Exception {
File fileToSend = setupFile(fileName, contentExpected);
CountDownLatch latch;
if (handler) {
latch = new CountDownLatch(2);
} else {
latch = new CountDownLatch(1);
}
server.requestHandler(req -> {
if (handler) {
Handler<AsyncResult<Void>> completionHandler = onSuccess(v -> latch.countDown());
req.response().sendFile(fileToSend.getAbsolutePath(), completionHandler);
} else {
req.response().sendFile(fileToSend.getAbsolutePath());
}
});
server.listen(onSuccess(s -> {
client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI, resp -> {
assertEquals(200, resp.statusCode());
assertEquals("text/html", resp.headers().get("Content-Type"));
resp.bodyHandler(buff -> {
assertEquals(contentExpected, buff.toString());
assertEquals(fileToSend.length(), Long.parseLong(resp.headers().get("content-length")));
latch.countDown();
});
}).end();
}));
assertTrue("Timed out waiting for test to complete.", latch.await(10, TimeUnit.SECONDS));
testComplete();
}
use of io.vertx.core.AsyncResult in project vert.x by eclipse.
the class FutureTest method testFailFutureToHandler.
@Test
public void testFailFutureToHandler() {
Throwable cause = new Throwable();
Consumer<Handler<AsyncResult<String>>> consumer = handler -> {
handler.handle(Future.failedFuture(cause));
};
Future<String> fut = Future.future();
consumer.accept(fut);
assertTrue(fut.isComplete());
assertTrue(fut.failed());
assertEquals(cause, fut.cause());
}
use of io.vertx.core.AsyncResult in project camel by apache.
the class VertxComponent method doStart.
@Override
protected void doStart() throws Exception {
super.doStart();
if (vertx == null) {
if (vertxFactory == null) {
vertxFactory = new VertxFactoryImpl();
}
if (vertxOptions == null) {
vertxOptions = new VertxOptions();
if (ObjectHelper.isNotEmpty(host)) {
vertxOptions.setClusterHost(host);
vertxOptions.setClustered(true);
}
if (port > 0) {
vertxOptions.setClusterPort(port);
vertxOptions.setClustered(true);
}
}
// we are creating vertx so we should handle its lifecycle
createdVertx = true;
final CountDownLatch latch = new CountDownLatch(1);
// lets using a host / port if a host name is specified
if (vertxOptions.isClustered()) {
LOG.info("Creating Clustered Vertx {}:{}", vertxOptions.getClusterHost(), vertxOptions.getClusterPort());
// use the async api as we want to wait for the eventbus to be ready before we are in started state
vertxFactory.clusteredVertx(vertxOptions, new Handler<AsyncResult<Vertx>>() {
@Override
public void handle(AsyncResult<Vertx> event) {
if (event.cause() != null) {
LOG.warn("Error creating Clustered Vertx " + host + ":" + port + " due " + event.cause().getMessage(), event.cause());
} else if (event.succeeded()) {
vertx = event.result();
LOG.info("EventBus is ready: {}", vertx);
}
latch.countDown();
}
});
} else {
LOG.info("Creating Non-Clustered Vertx");
vertx = vertxFactory.vertx();
LOG.info("EventBus is ready: {}", vertx);
latch.countDown();
}
if (latch.getCount() > 0) {
LOG.info("Waiting for EventBus to be ready using {} sec as timeout", timeout);
latch.await(timeout, TimeUnit.SECONDS);
}
} else {
LOG.debug("Using Vert.x instance set on the component level.");
}
}
Aggregations