Search in sources :

Example 81 with AsyncResult

use of io.vertx.core.AsyncResult in project vert.x by eclipse.

the class VertxImpl method close.

@Override
public synchronized void close(Handler<AsyncResult<Void>> completionHandler) {
    if (closed || eventBus == null) {
        // Just call the handler directly since pools shutdown
        if (completionHandler != null) {
            completionHandler.handle(Future.succeededFuture());
        }
        return;
    }
    closed = true;
    closeHooks.run(ar -> {
        deploymentManager.undeployAll(ar1 -> {
            if (haManager() != null) {
                haManager().stop();
            }
            addressResolver.close(ar2 -> {
                eventBus.close(ar3 -> {
                    closeClusterManager(ar4 -> {
                        Set<HttpServer> httpServers = new HashSet<>(sharedHttpServers.values());
                        Set<NetServerBase> netServers = new HashSet<>(sharedNetServers.values());
                        sharedHttpServers.clear();
                        sharedNetServers.clear();
                        int serverCount = httpServers.size() + netServers.size();
                        AtomicInteger serverCloseCount = new AtomicInteger();
                        Handler<AsyncResult<Void>> serverCloseHandler = res -> {
                            if (res.failed()) {
                                log.error("Failure in shutting down server", res.cause());
                            }
                            if (serverCloseCount.incrementAndGet() == serverCount) {
                                deleteCacheDirAndShutdown(completionHandler);
                            }
                        };
                        for (HttpServer server : httpServers) {
                            server.close(serverCloseHandler);
                        }
                        for (NetServerBase server : netServers) {
                            server.close(serverCloseHandler);
                        }
                        if (serverCount == 0) {
                            deleteCacheDirAndShutdown(completionHandler);
                        }
                    });
                });
            });
        });
    });
}
Also used : HttpServerImpl(io.vertx.core.http.impl.HttpServerImpl) NetServerImpl(io.vertx.core.net.impl.NetServerImpl) HttpClientImpl(io.vertx.core.http.impl.HttpClientImpl) HttpServer(io.vertx.core.http.HttpServer) NetClientImpl(io.vertx.core.net.impl.NetClientImpl) DummyVertxMetrics(io.vertx.core.metrics.impl.DummyVertxMetrics) Context(io.vertx.core.Context) InetAddress(java.net.InetAddress) EventBus(io.vertx.core.eventbus.EventBus) WindowsFileSystem(io.vertx.core.file.impl.WindowsFileSystem) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) DatagramSocketOptions(io.vertx.core.datagram.DatagramSocketOptions) Logger(io.vertx.core.logging.Logger) ThreadFactory(java.util.concurrent.ThreadFactory) ClusterManager(io.vertx.core.spi.cluster.ClusterManager) VertxMetricsFactory(io.vertx.core.spi.VertxMetricsFactory) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) VertxOptions(io.vertx.core.VertxOptions) Set(java.util.Set) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) EventLoop(io.netty.channel.EventLoop) ResourceLeakDetector(io.netty.util.ResourceLeakDetector) Future(io.vertx.core.Future) ServerID(io.vertx.core.net.impl.ServerID) InetSocketAddress(java.net.InetSocketAddress) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Executors(java.util.concurrent.Executors) NetClientOptions(io.vertx.core.net.NetClientOptions) DnsClient(io.vertx.core.dns.DnsClient) Objects(java.util.Objects) AddressResolverGroup(io.netty.resolver.AddressResolverGroup) NetServerOptions(io.vertx.core.net.NetServerOptions) PoolMetrics(io.vertx.core.spi.metrics.PoolMetrics) FileSystem(io.vertx.core.file.FileSystem) HttpClient(io.vertx.core.http.HttpClient) DatagramSocketImpl(io.vertx.core.datagram.impl.DatagramSocketImpl) VerticleFactory(io.vertx.core.spi.VerticleFactory) DatagramSocket(io.vertx.core.datagram.DatagramSocket) DnsClientImpl(io.vertx.core.dns.impl.DnsClientImpl) NetServerBase(io.vertx.core.net.impl.NetServerBase) HashMap(java.util.HashMap) LoggerFactory(io.vertx.core.logging.LoggerFactory) SharedData(io.vertx.core.shareddata.SharedData) VertxMetrics(io.vertx.core.spi.metrics.VertxMetrics) ArrayList(java.util.ArrayList) ConcurrentMap(java.util.concurrent.ConcurrentMap) TimeoutStream(io.vertx.core.TimeoutStream) HashSet(java.util.HashSet) ServiceHelper(io.vertx.core.ServiceHelper) SharedDataImpl(io.vertx.core.shareddata.impl.SharedDataImpl) AsyncResult(io.vertx.core.AsyncResult) HttpClientOptions(io.vertx.core.http.HttpClientOptions) NetClient(io.vertx.core.net.NetClient) Metrics(io.vertx.core.spi.metrics.Metrics) ExecutorService(java.util.concurrent.ExecutorService) EventBusImpl(io.vertx.core.eventbus.impl.EventBusImpl) Closeable(io.vertx.core.Closeable) EventLoopGroup(io.netty.channel.EventLoopGroup) Vertx(io.vertx.core.Vertx) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Verticle(io.vertx.core.Verticle) File(java.io.File) FileSystemImpl(io.vertx.core.file.impl.FileSystemImpl) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) DeploymentOptions(io.vertx.core.DeploymentOptions) NetServer(io.vertx.core.net.NetServer) HttpServerOptions(io.vertx.core.http.HttpServerOptions) ClusteredEventBus(io.vertx.core.eventbus.impl.clustered.ClusteredEventBus) Handler(io.vertx.core.Handler) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) NetServerBase(io.vertx.core.net.impl.NetServerBase) HttpServer(io.vertx.core.http.HttpServer) AsyncResult(io.vertx.core.AsyncResult) HashSet(java.util.HashSet)

Example 82 with AsyncResult

use of io.vertx.core.AsyncResult in project vert.x by eclipse.

the class NetServerBase method listen.

public synchronized void listen(Handler<? super C> handler, int port, String host, Handler<AsyncResult<Void>> listenHandler) {
    if (handler == null) {
        throw new IllegalStateException("Set connect handler first");
    }
    if (listening) {
        throw new IllegalStateException("Listen already called");
    }
    listening = true;
    listenContext = vertx.getOrCreateContext();
    registeredHandler = handler;
    synchronized (vertx.sharedNetServers()) {
        // Will be updated on bind for a wildcard port
        this.actualPort = port;
        id = new ServerID(port, host);
        NetServerBase shared = vertx.sharedNetServers().get(id);
        if (shared == null || port == 0) {
            // Wildcard port will imply a new actual server each time
            serverChannelGroup = new DefaultChannelGroup("vertx-acceptor-channels", GlobalEventExecutor.INSTANCE);
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(availableWorkers);
            bootstrap.channel(NioServerSocketChannel.class);
            sslHelper.validate(vertx);
            bootstrap.childHandler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    if (isPaused()) {
                        ch.close();
                        return;
                    }
                    ChannelPipeline pipeline = ch.pipeline();
                    NetServerBase.this.initChannel(ch.pipeline());
                    pipeline.addLast("handler", new ServerHandler(ch));
                }
            });
            applyConnectionOptions(bootstrap);
            handlerManager.addHandler(handler, listenContext);
            try {
                bindFuture = AsyncResolveConnectHelper.doBind(vertx, port, host, bootstrap);
                bindFuture.addListener(res -> {
                    if (res.succeeded()) {
                        Channel ch = res.result();
                        log.trace("Net server listening on " + host + ":" + ch.localAddress());
                        NetServerBase.this.actualPort = ((InetSocketAddress) ch.localAddress()).getPort();
                        NetServerBase.this.id = new ServerID(NetServerBase.this.actualPort, id.host);
                        serverChannelGroup.add(ch);
                        vertx.sharedNetServers().put(id, NetServerBase.this);
                        metrics = vertx.metricsSPI().createMetrics(new SocketAddressImpl(id.port, id.host), options);
                    } else {
                        vertx.sharedNetServers().remove(id);
                    }
                });
            } catch (Throwable t) {
                // Make sure we send the exception back through the handler (if any)
                if (listenHandler != null) {
                    vertx.runOnContext(v -> listenHandler.handle(Future.failedFuture(t)));
                } else {
                    // No handler - log so user can see failure
                    log.error(t);
                }
                listening = false;
                return;
            }
            if (port != 0) {
                vertx.sharedNetServers().put(id, this);
            }
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            actualServer = shared;
            this.actualPort = shared.actualPort();
            metrics = vertx.metricsSPI().createMetrics(new SocketAddressImpl(id.port, id.host), options);
            actualServer.handlerManager.addHandler(handler, listenContext);
        }
        // just add it to the future so it gets notified once the bind is complete
        actualServer.bindFuture.addListener(res -> {
            if (listenHandler != null) {
                AsyncResult<Void> ares;
                if (res.succeeded()) {
                    ares = Future.succeededFuture();
                } else {
                    listening = false;
                    ares = Future.failedFuture(res.cause());
                }
                listenContext.runOnContext(v -> listenHandler.handle(ares));
            } else if (res.failed()) {
                log.error("Failed to listen", res.cause());
                listening = false;
            }
        });
    }
    return;
}
Also used : DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ChannelOption(io.netty.channel.ChannelOption) ContextImpl(io.vertx.core.impl.ContextImpl) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) TCPMetrics(io.vertx.core.spi.metrics.TCPMetrics) LoggerFactory(io.vertx.core.logging.LoggerFactory) GlobalEventExecutor(io.netty.util.concurrent.GlobalEventExecutor) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) FixedRecvByteBufAllocator(io.netty.channel.FixedRecvByteBufAllocator) Map(java.util.Map) AsyncResult(io.vertx.core.AsyncResult) Logger(io.vertx.core.logging.Logger) Metrics(io.vertx.core.spi.metrics.Metrics) Closeable(io.vertx.core.Closeable) ChannelGroup(io.netty.channel.group.ChannelGroup) VertxInternal(io.vertx.core.impl.VertxInternal) ChannelInitializer(io.netty.channel.ChannelInitializer) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoop(io.netty.channel.EventLoop) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) NetServerOptions(io.vertx.core.net.NetServerOptions) SslHandler(io.netty.handler.ssl.SslHandler) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) Handler(io.vertx.core.Handler) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Channel(io.netty.channel.Channel) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 83 with AsyncResult

use of io.vertx.core.AsyncResult in project vert.x by eclipse.

the class Http2ServerConnection method sendPush.

synchronized void sendPush(int streamId, String host, HttpMethod method, MultiMap headers, String path, Handler<AsyncResult<HttpServerResponse>> completionHandler) {
    Http2Headers headers_ = new DefaultHttp2Headers();
    if (method == HttpMethod.OTHER) {
        throw new IllegalArgumentException("Cannot push HttpMethod.OTHER");
    } else {
        headers_.method(method.name());
    }
    headers_.path(path);
    headers_.scheme(isSsl() ? "https" : "http");
    if (host != null) {
        headers_.authority(host);
    }
    if (headers != null) {
        headers.forEach(header -> headers_.add(header.getKey(), header.getValue()));
    }
    handler.writePushPromise(streamId, headers_, new Handler<AsyncResult<Integer>>() {

        @Override
        public void handle(AsyncResult<Integer> ar) {
            if (ar.succeeded()) {
                synchronized (Http2ServerConnection.this) {
                    int promisedStreamId = ar.result();
                    String contentEncoding = HttpUtils.determineContentEncoding(headers_);
                    Http2Stream promisedStream = handler.connection().stream(promisedStreamId);
                    boolean writable = handler.encoder().flowController().isWritable(promisedStream);
                    Push push = new Push(promisedStream, contentEncoding, method, path, writable, completionHandler);
                    streams.put(promisedStreamId, push);
                    if (maxConcurrentStreams == null || concurrentStreams < maxConcurrentStreams) {
                        concurrentStreams++;
                        context.executeFromIO(push::complete);
                    } else {
                        pendingPushes.add(push);
                    }
                }
            } else {
                context.executeFromIO(() -> {
                    completionHandler.handle(Future.failedFuture(ar.cause()));
                });
            }
        }
    });
}
Also used : Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2Stream(io.netty.handler.codec.http2.Http2Stream) AsyncResult(io.vertx.core.AsyncResult)

Example 84 with AsyncResult

use of io.vertx.core.AsyncResult in project vert.x by eclipse.

the class DnsClientImpl method reverseLookup.

@Override
public DnsClient reverseLookup(String address, Handler<AsyncResult<String>> handler) {
    //        An other option would be to change address to be of type InetAddress.
    try {
        InetAddress inetAddress = InetAddress.getByName(address);
        byte[] addr = inetAddress.getAddress();
        StringBuilder reverseName = new StringBuilder(64);
        if (inetAddress instanceof Inet4Address) {
            // reverse ipv4 address
            reverseName.append(addr[3] & 0xff).append(".").append(addr[2] & 0xff).append(".").append(addr[1] & 0xff).append(".").append(addr[0] & 0xff);
        } else {
            // It is an ipv 6 address time to reverse it
            for (int i = 0; i < 16; i++) {
                reverseName.append(HEX_TABLE[(addr[15 - i] & 0xf)]);
                reverseName.append(".");
                reverseName.append(HEX_TABLE[(addr[15 - i] >> 4) & 0xf]);
                if (i != 15) {
                    reverseName.append(".");
                }
            }
        }
        reverseName.append(".in-addr.arpa");
        return resolvePTR(reverseName.toString(), handler);
    } catch (UnknownHostException e) {
        // Should never happen as we work with ip addresses as input
        // anyway just in case notify the handler
        actualCtx.runOnContext((v) -> handler.handle(Future.failedFuture(e)));
    }
    return this;
}
Also used : DatagramDnsQueryEncoder(io.netty.handler.codec.dns.DatagramDnsQueryEncoder) DnsRecord(io.netty.handler.codec.dns.DnsRecord) DnsResponse(io.netty.handler.codec.dns.DnsResponse) DnsException(io.vertx.core.dns.DnsException) ChannelOption(io.netty.channel.ChannelOption) ContextImpl(io.vertx.core.impl.ContextImpl) DefaultDnsQuestion(io.netty.handler.codec.dns.DefaultDnsQuestion) SrvRecord(io.vertx.core.dns.SrvRecord) ArrayList(java.util.ArrayList) InetAddress(java.net.InetAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DatagramChannel(io.netty.channel.socket.DatagramChannel) DnsSection(io.netty.handler.codec.dns.DnsSection) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) DnsResponseCode(io.vertx.core.dns.DnsResponseCode) AsyncResult(io.vertx.core.AsyncResult) DnsRecordType(io.netty.handler.codec.dns.DnsRecordType) VertxInternal(io.vertx.core.impl.VertxInternal) ChannelInitializer(io.netty.channel.ChannelInitializer) DatagramDnsQuery(io.netty.handler.codec.dns.DatagramDnsQuery) PartialPooledByteBufAllocator(io.vertx.core.net.impl.PartialPooledByteBufAllocator) ChannelPipeline(io.netty.channel.ChannelPipeline) Future(io.vertx.core.Future) Inet4Address(java.net.Inet4Address) InetSocketAddress(java.net.InetSocketAddress) UnknownHostException(java.net.UnknownHostException) RecordDecoder(io.vertx.core.dns.impl.decoder.RecordDecoder) ChannelFuture(io.netty.channel.ChannelFuture) DnsClient(io.vertx.core.dns.DnsClient) Objects(java.util.Objects) Bootstrap(io.netty.bootstrap.Bootstrap) List(java.util.List) NioDatagramChannel(io.netty.channel.socket.nio.NioDatagramChannel) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) DatagramDnsResponseDecoder(io.netty.handler.codec.dns.DatagramDnsResponseDecoder) MxRecord(io.vertx.core.dns.MxRecord) Handler(io.vertx.core.Handler) Collections(java.util.Collections) Inet4Address(java.net.Inet4Address) UnknownHostException(java.net.UnknownHostException) InetAddress(java.net.InetAddress)

Example 85 with AsyncResult

use of io.vertx.core.AsyncResult in project vert.x by eclipse.

the class HttpServerResponseImpl method doSendFile.

private void doSendFile(String filename, long offset, long length, Handler<AsyncResult<Void>> resultHandler) {
    synchronized (conn) {
        if (headWritten) {
            throw new IllegalStateException("Head already written");
        }
        checkWritten();
        File file = vertx.resolveFile(filename);
        if (!file.exists()) {
            if (resultHandler != null) {
                ContextImpl ctx = vertx.getOrCreateContext();
                ctx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(new FileNotFoundException())));
            } else {
                log.error("File not found: " + filename);
            }
            return;
        }
        long contentLength = Math.min(length, file.length() - offset);
        bytesWritten = contentLength;
        if (!contentLengthSet()) {
            putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength));
        }
        if (!contentTypeSet()) {
            String contentType = MimeMapping.getMimeTypeForFilename(filename);
            if (contentType != null) {
                putHeader(HttpHeaders.CONTENT_TYPE, contentType);
            }
        }
        prepareHeaders();
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, "r");
            conn.queueForWrite(response);
            conn.sendFile(raf, Math.min(offset, file.length()), contentLength);
        } catch (IOException e) {
            try {
                if (raf != null) {
                    raf.close();
                }
            } catch (IOException ignore) {
            }
            if (resultHandler != null) {
                ContextImpl ctx = vertx.getOrCreateContext();
                ctx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(e)));
            } else {
                log.error("Failed to send file", e);
            }
            return;
        }
        // write an empty last content to let the http encoder know the response is complete
        channelFuture = conn.writeToChannel(LastHttpContent.EMPTY_LAST_CONTENT);
        written = true;
        if (resultHandler != null) {
            ContextImpl ctx = vertx.getOrCreateContext();
            channelFuture.addListener(future -> {
                AsyncResult<Void> res;
                if (future.isSuccess()) {
                    res = Future.succeededFuture();
                } else {
                    res = Future.failedFuture(future.cause());
                }
                ctx.runOnContext((v) -> resultHandler.handle(res));
            });
        }
        if (!keepAlive) {
            closeConnAfterWrite();
        }
        conn.responseComplete();
        if (bodyEndHandler != null) {
            bodyEndHandler.handle(null);
        }
    }
}
Also used : RandomAccessFile(java.io.RandomAccessFile) HttpVersion(io.netty.handler.codec.http.HttpVersion) VertxInternal(io.vertx.core.impl.VertxInternal) ContextImpl(io.vertx.core.impl.ContextImpl) MultiMap(io.vertx.core.MultiMap) HttpHeaders(io.vertx.core.http.HttpHeaders) IOException(java.io.IOException) Future(io.vertx.core.Future) io.vertx.core.http(io.vertx.core.http) LoggerFactory(io.vertx.core.logging.LoggerFactory) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) Unpooled(io.netty.buffer.Unpooled) ChannelFuture(io.netty.channel.ChannelFuture) Nullable(io.vertx.codegen.annotations.Nullable) io.netty.handler.codec.http(io.netty.handler.codec.http) ByteBuf(io.netty.buffer.ByteBuf) Buffer(io.vertx.core.buffer.Buffer) HttpMethod(io.vertx.core.http.HttpMethod) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) Logger(io.vertx.core.logging.Logger) RandomAccessFile(java.io.RandomAccessFile) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) ContextImpl(io.vertx.core.impl.ContextImpl) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

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