Search in sources :

Example 1 with AsyncResult

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);
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) ContextImpl(io.vertx.core.impl.ContextImpl) TCPMetrics(io.vertx.core.spi.metrics.TCPMetrics) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) LoggerFactory(io.vertx.core.logging.LoggerFactory) ByteBuf(io.netty.buffer.ByteBuf) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator) Map(java.util.Map) AsyncResult(io.vertx.core.AsyncResult) Logger(io.vertx.core.logging.Logger) NetClient(io.vertx.core.net.NetClient) Metrics(io.vertx.core.spi.metrics.Metrics) Closeable(io.vertx.core.Closeable) VertxInternal(io.vertx.core.impl.VertxInternal) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) ChannelPipeline(io.netty.channel.ChannelPipeline) Future(io.vertx.core.Future) NetClientOptions(io.vertx.core.net.NetClientOptions) Objects(java.util.Objects) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Handler(io.vertx.core.Handler) NetSocket(io.vertx.core.net.NetSocket) LoggingHandler(io.netty.handler.logging.LoggingHandler) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) ContextImpl(io.vertx.core.impl.ContextImpl) ByteBuf(io.netty.buffer.ByteBuf) SslHandler(io.netty.handler.ssl.SslHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) Bootstrap(io.netty.bootstrap.Bootstrap) Future(io.vertx.core.Future) AsyncResult(io.vertx.core.AsyncResult)

Example 2 with AsyncResult

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();
}
Also used : VertxException(io.vertx.core.VertxException) MultiMap(io.vertx.core.MultiMap) TimeoutException(java.util.concurrent.TimeoutException) Context(io.vertx.core.Context) InetAddress(java.net.InetAddress) HttpFrame(io.vertx.core.http.HttpFrame) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) TestLoggerFactory(io.vertx.test.netty.TestLoggerFactory) HttpHeaders(io.vertx.core.http.HttpHeaders) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) UUID(java.util.UUID) Future(io.vertx.core.Future) FileNotFoundException(java.io.FileNotFoundException) Nullable(io.vertx.codegen.annotations.Nullable) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) DefaultHttpHeaders(io.netty.handler.codec.http.DefaultHttpHeaders) HttpServerResponse(io.vertx.core.http.HttpServerResponse) AbstractVerticle(io.vertx.core.AbstractVerticle) WorkerContext(io.vertx.core.impl.WorkerContext) UnsupportedEncodingException(java.io.UnsupportedEncodingException) HttpClient(io.vertx.core.http.HttpClient) NetSocket(io.vertx.core.net.NetSocket) IntStream(java.util.stream.IntStream) HeadersAdaptor(io.vertx.core.http.impl.HeadersAdaptor) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) TestUtils.assertNullPointerException(io.vertx.test.core.TestUtils.assertNullPointerException) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HttpClientRequest(io.vertx.core.http.HttpClientRequest) HttpClientResponse(io.vertx.core.http.HttpClientResponse) OutputStreamWriter(java.io.OutputStreamWriter) Assume(org.junit.Assume) AsyncResult(io.vertx.core.AsyncResult) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) BufferedWriter(java.io.BufferedWriter) Vertx(io.vertx.core.Vertx) FileOutputStream(java.io.FileOutputStream) Test(org.junit.Test) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) EventLoopContext(io.vertx.core.impl.EventLoopContext) URLEncoder(java.net.URLEncoder) Rule(org.junit.Rule) DeploymentOptions(io.vertx.core.DeploymentOptions) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerOptions(io.vertx.core.http.HttpServerOptions) InternalLoggerFactory(io.netty.util.internal.logging.InternalLoggerFactory) Handler(io.vertx.core.Handler) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) TemporaryFolder(org.junit.rules.TemporaryFolder) TestUtils.assertIllegalArgumentException(io.vertx.test.core.TestUtils.assertIllegalArgumentException) CountDownLatch(java.util.concurrent.CountDownLatch) File(java.io.File) AsyncResult(io.vertx.core.AsyncResult)

Example 3 with AsyncResult

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());
}
Also used : Arrays(java.util.Arrays) NoStackTraceThrowable(io.vertx.core.impl.NoStackTraceThrowable) BiFunction(java.util.function.BiFunction) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) Future(io.vertx.core.Future) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) Consumer(java.util.function.Consumer) CompositeFuture(io.vertx.core.CompositeFuture) List(java.util.List) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) Collections(java.util.Collections) NoStackTraceThrowable(io.vertx.core.impl.NoStackTraceThrowable) Handler(io.vertx.core.Handler) Test(org.junit.Test)

Example 4 with AsyncResult

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();
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Handler(io.vertx.core.Handler) AsyncResult(io.vertx.core.AsyncResult)

Example 5 with AsyncResult

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();
}
Also used : AtomicReference(java.util.concurrent.atomic.AtomicReference) Vertx(io.vertx.core.Vertx) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncResult(io.vertx.core.AsyncResult) SharedData(io.vertx.core.shareddata.SharedData) Lock(io.vertx.core.shareddata.Lock) Test(org.junit.Test)

Aggregations

AsyncResult (io.vertx.core.AsyncResult)162 Handler (io.vertx.core.Handler)106 Test (org.junit.Test)72 JsonObject (io.vertx.core.json.JsonObject)68 CountDownLatch (java.util.concurrent.CountDownLatch)62 Future (io.vertx.core.Future)59 List (java.util.List)49 RequestParameter (io.vertx.ext.web.api.RequestParameter)48 RequestParameters (io.vertx.ext.web.api.RequestParameters)48 HashMap (java.util.HashMap)45 Map (java.util.Map)42 IOException (java.io.IOException)41 ArrayList (java.util.ArrayList)40 Vertx (io.vertx.core.Vertx)35 Collectors (java.util.stream.Collectors)35 RoutingContext (io.vertx.ext.web.RoutingContext)28 Buffer (io.vertx.core.buffer.Buffer)24 StandardCharsets (java.nio.charset.StandardCharsets)23 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)23 Consumer (java.util.function.Consumer)23