Search in sources :

Example 6 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)

Example 7 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 8 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 9 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 10 with AsyncResult

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.");
    }
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) Vertx(io.vertx.core.Vertx) VertxOptions(io.vertx.core.VertxOptions) AsyncResult(io.vertx.core.AsyncResult) VertxFactoryImpl(io.vertx.core.impl.VertxFactoryImpl)

Aggregations

AsyncResult (io.vertx.core.AsyncResult)20 Handler (io.vertx.core.Handler)15 Future (io.vertx.core.Future)14 Buffer (io.vertx.core.buffer.Buffer)10 ContextImpl (io.vertx.core.impl.ContextImpl)8 VertxInternal (io.vertx.core.impl.VertxInternal)8 Logger (io.vertx.core.logging.Logger)8 LoggerFactory (io.vertx.core.logging.LoggerFactory)8 ByteBuf (io.netty.buffer.ByteBuf)7 Unpooled (io.netty.buffer.Unpooled)6 Map (java.util.Map)6 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)6 Channel (io.netty.channel.Channel)5 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)5 ChannelPipeline (io.netty.channel.ChannelPipeline)5 SslHandler (io.netty.handler.ssl.SslHandler)5 Context (io.vertx.core.Context)5 MultiMap (io.vertx.core.MultiMap)5 NetSocket (io.vertx.core.net.NetSocket)5 File (java.io.File)5