Search in sources :

Example 36 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project intellij-community by JetBrains.

the class ChannelRegistrar method close.

private void close(boolean shutdownEventLoopGroup) {
    ServerChannel serverChannel = this.serverChannel.get();
    if (serverChannel == null) {
        LOG.assertTrue(clientChannels.isEmpty());
        return;
    } else if (!this.serverChannel.compareAndSet(serverChannel, null)) {
        return;
    }
    EventLoopGroup eventLoopGroup = shutdownEventLoopGroup ? serverChannel.eventLoop().parent() : null;
    try {
        long start = System.currentTimeMillis();
        Channel[] clientChannels = this.clientChannels.toArray(new Channel[] {});
        this.clientChannels.clear();
        final CountDownLatch countDown = new CountDownLatch(clientChannels.length + 1);
        GenericFutureListener<ChannelFuture> listener = new GenericFutureListener<ChannelFuture>() {

            @Override
            public void operationComplete(@NotNull ChannelFuture future) throws Exception {
                try {
                    Throwable cause = future.cause();
                    if (cause != null) {
                        LOG.warn(cause);
                    }
                } finally {
                    countDown.countDown();
                }
            }
        };
        serverChannel.close().addListener(listener);
        for (Channel channel : clientChannels) {
            channel.close().addListener(listener);
        }
        try {
            countDown.await(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            LOG.warn("Cannot close all channels for 10 seconds, channels: " + Arrays.toString(clientChannels));
        }
        long duration = System.currentTimeMillis() - start;
        if (duration > 1000) {
            LOG.info("Close all channels took " + duration + " ms: " + (duration / 60000) + " min " + ((duration % 60000) / 1000) + "sec");
        }
    } finally {
        if (eventLoopGroup != null) {
            eventLoopGroup.shutdownGracefully(1, 2, TimeUnit.NANOSECONDS);
        }
    }
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) NotNull(org.jetbrains.annotations.NotNull)

Example 37 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project tesla by linking12.

the class ConnectionFlow method fail.

@SuppressWarnings({ "unchecked", "rawtypes" })
public void fail(final Throwable cause) {
    final ConnectionState lastStateBeforeFailure = serverConnection.getCurrentState();
    serverConnection.disconnect().addListener(new GenericFutureListener() {

        @Override
        public void operationComplete(Future future) throws Exception {
            synchronized (connectLock) {
                if (!clientConnection.serverConnectionFailed(serverConnection, lastStateBeforeFailure, cause)) {
                    serverConnection.become(ConnectionState.DISCONNECTED);
                    notifyThreadsWaitingForConnection();
                }
            }
        }
    });
}
Also used : Future(io.netty.util.concurrent.Future) ConnectionState(io.github.tesla.gateway.netty.transmit.ConnectionState) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener)

Example 38 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project flink by apache.

the class HandlerUtils method transferFile.

public static void transferFile(ChannelHandlerContext ctx, File file, HttpRequest httpRequest) throws FlinkException {
    final RandomAccessFile randomAccessFile;
    try {
        randomAccessFile = new RandomAccessFile(file, "r");
    } catch (FileNotFoundException e) {
        throw new FlinkException("Can not find file " + file + ".", e);
    }
    try {
        final long fileLength = randomAccessFile.length();
        final FileChannel fileChannel = randomAccessFile.getChannel();
        try {
            HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
            response.headers().set(CONTENT_TYPE, "text/plain");
            if (HttpHeaders.isKeepAlive(httpRequest)) {
                response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
            }
            HttpHeaders.setContentLength(response, fileLength);
            // write the initial line and the header.
            ctx.write(response);
            // write the content.
            final ChannelFuture lastContentFuture;
            final GenericFutureListener<Future<? super Void>> completionListener = future -> {
                fileChannel.close();
                randomAccessFile.close();
            };
            if (ctx.pipeline().get(SslHandler.class) == null) {
                ctx.write(new DefaultFileRegion(fileChannel, 0, fileLength), ctx.newProgressivePromise()).addListener(completionListener);
                lastContentFuture = ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);
            } else {
                lastContentFuture = ctx.writeAndFlush(new HttpChunkedInput(new ChunkedFile(randomAccessFile, 0, fileLength, 8192)), ctx.newProgressivePromise()).addListener(completionListener);
            // HttpChunkedInput will write the end marker (LastHttpContent) for us.
            }
            // close the connection, if no keep-alive is needed
            if (!HttpHeaders.isKeepAlive(httpRequest)) {
                lastContentFuture.addListener(ChannelFutureListener.CLOSE);
            }
        } catch (IOException ex) {
            fileChannel.close();
            throw ex;
        }
    } catch (IOException ioe) {
        try {
            randomAccessFile.close();
        } catch (IOException e) {
            throw new FlinkException("Close file or channel error.", e);
        }
        throw new FlinkException("Could not transfer file " + file + " to the client.", ioe);
    }
}
Also used : ChannelFuture(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture) RestMapperUtils(org.apache.flink.runtime.rest.util.RestMapperUtils) FlinkException(org.apache.flink.util.FlinkException) RandomAccessFile(java.io.RandomAccessFile) ChannelFutureListener(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFutureListener) OK(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus.OK) LastHttpContent(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.LastHttpContent) LoggerFactory(org.slf4j.LoggerFactory) CompletableFuture(java.util.concurrent.CompletableFuture) Future(org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future) HTTP_1_1(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpVersion.HTTP_1_1) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) HttpResponseStatus(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponseStatus) DefaultFileRegion(org.apache.flink.shaded.netty4.io.netty.channel.DefaultFileRegion) HttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponse) HttpHeaders(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpHeaders) ObjectMapper(org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper) Map(java.util.Map) ConfigConstants(org.apache.flink.configuration.ConfigConstants) HttpRequest(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpRequest) CONNECTION(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpHeaders.Names.CONNECTION) Nonnull(javax.annotation.Nonnull) ChannelFuture(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture) ErrorResponseBody(org.apache.flink.runtime.rest.messages.ErrorResponseBody) ChannelHandlerContext(org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext) CONTENT_TYPE(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE) HttpChunkedInput(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpChunkedInput) Logger(org.slf4j.Logger) RestConstants(org.apache.flink.runtime.rest.util.RestConstants) GenericFutureListener(org.apache.flink.shaded.netty4.io.netty.util.concurrent.GenericFutureListener) StringWriter(java.io.StringWriter) Unpooled(org.apache.flink.shaded.netty4.io.netty.buffer.Unpooled) IOException(java.io.IOException) ByteBuf(org.apache.flink.shaded.netty4.io.netty.buffer.ByteBuf) SslHandler(org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) ResponseBody(org.apache.flink.runtime.rest.messages.ResponseBody) ChunkedFile(org.apache.flink.shaded.netty4.io.netty.handler.stream.ChunkedFile) FileChannel(java.nio.channels.FileChannel) FileChannel(java.nio.channels.FileChannel) ChunkedFile(org.apache.flink.shaded.netty4.io.netty.handler.stream.ChunkedFile) FileNotFoundException(java.io.FileNotFoundException) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpResponse) IOException(java.io.IOException) DefaultFileRegion(org.apache.flink.shaded.netty4.io.netty.channel.DefaultFileRegion) FlinkException(org.apache.flink.util.FlinkException) SslHandler(org.apache.flink.shaded.netty4.io.netty.handler.ssl.SslHandler) HttpChunkedInput(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpChunkedInput) RandomAccessFile(java.io.RandomAccessFile) DefaultHttpResponse(org.apache.flink.shaded.netty4.io.netty.handler.codec.http.DefaultHttpResponse) CompletableFuture(java.util.concurrent.CompletableFuture) Future(org.apache.flink.shaded.netty4.io.netty.util.concurrent.Future) ChannelFuture(org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture)

Example 39 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project ratpack by ratpack.

the class DefaultResponseTransmitter method transmitter.

@Override
public Subscriber<ByteBuf> transmitter(HttpResponseStatus responseStatus) {
    return new Subscriber<ByteBuf>() {

        private Subscription subscription;

        private final AtomicBoolean done = new AtomicBoolean();

        private final ChannelFutureListener cancelOnFailure = future -> {
            if (!future.isSuccess()) {
                cancel();
            }
        };

        private final GenericFutureListener<Future<? super Void>> cancelOnCloseListener = c -> cancel();

        private void cancel() {
            channel.closeFuture().removeListener(cancelOnCloseListener);
            if (done.compareAndSet(false, true)) {
                subscription.cancel();
                post(responseStatus);
            }
        }

        @Override
        public void onSubscribe(Subscription subscription) {
            if (subscription == null) {
                throw new NullPointerException("'subscription' is null");
            }
            if (this.subscription != null) {
                subscription.cancel();
                return;
            }
            this.subscription = subscription;
            ChannelFuture channelFuture = pre(responseStatus, true);
            if (channelFuture == null) {
                subscription.cancel();
                isKeepAlive = false;
                notifyListeners(responseStatus);
            } else {
                channelFuture.addListener(f -> {
                    if (f.isSuccess() && channel.isOpen()) {
                        channel.closeFuture().addListener(cancelOnCloseListener);
                        if (channel.isWritable()) {
                            this.subscription.request(1);
                        }
                        onWritabilityChanged = () -> {
                            if (channel.isWritable() && !done.get()) {
                                this.subscription.request(1);
                            }
                        };
                    } else {
                        cancel();
                    }
                });
            }
        }

        @Override
        public void onNext(ByteBuf o) {
            o.touch();
            if (channel.isOpen()) {
                channel.writeAndFlush(new DefaultHttpContent(o)).addListener(cancelOnFailure);
                if (channel.isWritable()) {
                    subscription.request(1);
                }
            } else {
                o.release();
                cancel();
            }
        }

        @Override
        public void onError(Throwable t) {
            if (t == null) {
                throw new NullPointerException("error is null");
            }
            LOGGER.warn("Exception thrown transmitting stream", t);
            if (done.compareAndSet(false, true)) {
                channel.closeFuture().removeListener(cancelOnCloseListener);
                post(responseStatus);
            }
        }

        @Override
        public void onComplete() {
            if (done.compareAndSet(false, true)) {
                channel.closeFuture().removeListener(cancelOnCloseListener);
                post(responseStatus);
            }
        }
    };
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Subscriber(org.reactivestreams.Subscriber) Subscription(org.reactivestreams.Subscription) ByteBuf(io.netty.buffer.ByteBuf) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener)

Example 40 with GenericFutureListener

use of io.netty.util.concurrent.GenericFutureListener in project herddb by diennea.

the class NettyChannel method sendOneWayMessage.

@Override
public void sendOneWayMessage(Message message, SendResultCallback callback) {
    if (message.getMessageId() == null) {
        message.assignMessageId();
    }
    io.netty.channel.Channel _socket = this.socket;
    if (_socket == null || !_socket.isOpen()) {
        callback.messageSent(message, new Exception(this + " connection is closed"));
        return;
    }
    _socket.writeAndFlush(message).addListener(new GenericFutureListener() {

        @Override
        public void operationComplete(Future future) throws Exception {
            if (future.isSuccess()) {
                callback.messageSent(message, null);
            } else {
                LOGGER.log(Level.SEVERE, this + ": error " + future.cause(), future.cause());
                callback.messageSent(message, future.cause());
                close();
            }
        }
    });
}
Also used : Future(io.netty.util.concurrent.Future) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) IOException(java.io.IOException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException)

Aggregations

GenericFutureListener (io.netty.util.concurrent.GenericFutureListener)70 Future (io.netty.util.concurrent.Future)44 ChannelFuture (io.netty.channel.ChannelFuture)32 Channel (io.netty.channel.Channel)19 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)18 IOException (java.io.IOException)18 List (java.util.List)15 InetSocketAddress (java.net.InetSocketAddress)13 ArrayList (java.util.ArrayList)13 Map (java.util.Map)12 ChannelOption (io.netty.channel.ChannelOption)10 Future (io.vertx.core.Future)10 Handler (io.vertx.core.Handler)10 ContextInternal (io.vertx.core.impl.ContextInternal)10 VertxInternal (io.vertx.core.impl.VertxInternal)10 Logger (org.slf4j.Logger)10 LoggerFactory (org.slf4j.LoggerFactory)9 Bootstrap (io.netty.bootstrap.Bootstrap)8 LoggingHandler (io.netty.handler.logging.LoggingHandler)8 AsyncResult (io.vertx.core.AsyncResult)8