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 vert.x by eclipse.
the class ClusteredEventBusTestBase method testPublish.
@Override
protected <T> void testPublish(T val, Consumer<T> consumer) {
int numNodes = 3;
startNodes(numNodes);
AtomicInteger count = new AtomicInteger();
class MyHandler implements Handler<Message<T>> {
@Override
public void handle(Message<T> msg) {
if (consumer == null) {
assertFalse(msg.isSend());
assertEquals(val, msg.body());
} else {
consumer.accept(msg.body());
}
if (count.incrementAndGet() == numNodes - 1) {
testComplete();
}
}
}
AtomicInteger registerCount = new AtomicInteger(0);
class MyRegisterHandler implements Handler<AsyncResult<Void>> {
@Override
public void handle(AsyncResult<Void> ar) {
assertTrue(ar.succeeded());
if (registerCount.incrementAndGet() == 2) {
vertices[0].eventBus().publish(ADDRESS1, val);
}
}
}
MessageConsumer reg = vertices[2].eventBus().<T>consumer(ADDRESS1).handler(new MyHandler());
reg.completionHandler(new MyRegisterHandler());
reg = vertices[1].eventBus().<T>consumer(ADDRESS1).handler(new MyHandler());
reg.completionHandler(new MyRegisterHandler());
vertices[0].eventBus().publish(ADDRESS1, val);
await();
}
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();
}
Aggregations