Search in sources :

Example 16 with GenericFutureListener

use of org.apache.flink.shaded.netty4.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 17 with GenericFutureListener

use of org.apache.flink.shaded.netty4.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)

Example 18 with GenericFutureListener

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.GenericFutureListener in project vert.x by eclipse.

the class DatagramSocketImpl method send.

@Override
public Future<Void> send(Buffer packet, int port, String host) {
    Objects.requireNonNull(packet, "no null packet accepted");
    Objects.requireNonNull(host, "no null host accepted");
    if (port < 0 || port > 65535) {
        throw new IllegalArgumentException("port out of range:" + port);
    }
    AddressResolver resolver = context.owner().addressResolver();
    PromiseInternal<Void> promise = context.promise();
    io.netty.util.concurrent.Future<InetSocketAddress> f1 = resolver.resolveHostname(context.nettyEventLoop(), host);
    f1.addListener((GenericFutureListener<io.netty.util.concurrent.Future<InetSocketAddress>>) res1 -> {
        if (res1.isSuccess()) {
            ChannelFuture f2 = channel.writeAndFlush(new DatagramPacket(packet.getByteBuf(), new InetSocketAddress(f1.getNow().getAddress(), port)));
            if (metrics != null) {
                f2.addListener(fut -> {
                    if (fut.isSuccess()) {
                        metrics.bytesWritten(null, SocketAddress.inetSocketAddress(port, host), packet.length());
                    }
                });
            }
            f2.addListener(promise);
        } else {
            promise.fail(res1.cause());
        }
    });
    return promise.future();
}
Also used : ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) DatagramSocket(io.vertx.core.datagram.DatagramSocket) Arguments(io.vertx.core.impl.Arguments) ContextInternal(io.vertx.core.impl.ContextInternal) ConnectionBase(io.vertx.core.net.impl.ConnectionBase) InetAddress(java.net.InetAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) DatagramChannel(io.netty.channel.socket.DatagramChannel) ByteBuf(io.netty.buffer.ByteBuf) WriteStream(io.vertx.core.streams.WriteStream) DatagramPacket(io.netty.channel.socket.DatagramPacket) InternetProtocolFamily(io.netty.channel.socket.InternetProtocolFamily) AsyncResult(io.vertx.core.AsyncResult) DatagramSocketOptions(io.vertx.core.datagram.DatagramSocketOptions) MaxMessagesRecvByteBufAllocator(io.netty.channel.MaxMessagesRecvByteBufAllocator) SocketAddress(io.vertx.core.net.SocketAddress) VertxHandler(io.vertx.core.net.impl.VertxHandler) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) VertxInternal(io.vertx.core.impl.VertxInternal) Transport(io.vertx.core.net.impl.transport.Transport) AddressResolver(io.vertx.core.impl.AddressResolver) NetworkInterface(java.net.NetworkInterface) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) UnknownHostException(java.net.UnknownHostException) ChannelFuture(io.netty.channel.ChannelFuture) Nullable(io.vertx.codegen.annotations.Nullable) Objects(java.util.Objects) Buffer(io.vertx.core.buffer.Buffer) io.vertx.core.spi.metrics(io.vertx.core.spi.metrics) Handler(io.vertx.core.Handler) ChannelFuture(io.netty.channel.ChannelFuture) AddressResolver(io.vertx.core.impl.AddressResolver) InetSocketAddress(java.net.InetSocketAddress) DatagramPacket(io.netty.channel.socket.DatagramPacket) Future(io.vertx.core.Future) ChannelFuture(io.netty.channel.ChannelFuture)

Example 19 with GenericFutureListener

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.GenericFutureListener in project vert.x by eclipse.

the class VertxImpl method deleteCacheDirAndShutdown.

@SuppressWarnings("unchecked")
private void deleteCacheDirAndShutdown(Handler<AsyncResult<Void>> completionHandler) {
    executeBlockingInternal(fut -> {
        try {
            fileResolver.close();
            fut.complete();
        } catch (IOException e) {
            fut.tryFail(e);
        }
    }, ar -> {
        workerPool.close();
        internalWorkerPool.close();
        new ArrayList<>(namedWorkerPools.values()).forEach(WorkerPool::close);
        acceptorEventLoopGroup.shutdownGracefully(0, 10, TimeUnit.SECONDS).addListener(new GenericFutureListener() {

            @Override
            public void operationComplete(io.netty.util.concurrent.Future future) throws Exception {
                if (!future.isSuccess()) {
                    log.warn("Failure in shutting down acceptor event loop group", future.cause());
                }
                eventLoopGroup.shutdownGracefully(0, 10, TimeUnit.SECONDS).addListener(new GenericFutureListener() {

                    @Override
                    public void operationComplete(io.netty.util.concurrent.Future future) throws Exception {
                        if (!future.isSuccess()) {
                            log.warn("Failure in shutting down event loop group", future.cause());
                        }
                        if (metrics != null) {
                            metrics.close();
                        }
                        if (tracer != null) {
                            tracer.close();
                        }
                        checker.close();
                        if (completionHandler != null) {
                            eventLoopThreadFactory.newThread(() -> {
                                completionHandler.handle(Future.succeededFuture());
                            }).start();
                        }
                    }
                });
            }
        });
    });
}
Also used : java.util.concurrent(java.util.concurrent) Future(io.vertx.core.Future) IOException(java.io.IOException) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) IOException(java.io.IOException)

Example 20 with GenericFutureListener

use of org.apache.flink.shaded.netty4.io.netty.util.concurrent.GenericFutureListener in project vert.x by eclipse.

the class NetClientImpl method connectInternal.

public void connectInternal(ProxyOptions proxyOptions, SocketAddress remoteAddress, SocketAddress peerAddress, String serverName, boolean ssl, boolean useAlpn, boolean registerWriteHandlers, Promise<NetSocket> connectHandler, ContextInternal context, int remainingAttempts) {
    checkClosed();
    EventLoop eventLoop = context.nettyEventLoop();
    if (eventLoop.inEventLoop()) {
        Objects.requireNonNull(connectHandler, "No null connectHandler accepted");
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventLoop);
        bootstrap.option(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
        vertx.transport().configure(options, remoteAddress.isDomainSocket(), bootstrap);
        ChannelProvider channelProvider = new ChannelProvider(bootstrap, sslHelper, context).proxyOptions(proxyOptions);
        channelProvider.handler(ch -> connected(context, ch, connectHandler, remoteAddress, channelProvider.applicationProtocol(), registerWriteHandlers));
        io.netty.util.concurrent.Future<Channel> fut = channelProvider.connect(remoteAddress, peerAddress, serverName, ssl, useAlpn);
        fut.addListener((GenericFutureListener<io.netty.util.concurrent.Future<Channel>>) future -> {
            if (!future.isSuccess()) {
                Throwable cause = future.cause();
                boolean connectError = cause instanceof ConnectException || cause instanceof FileNotFoundException;
                if (connectError && (remainingAttempts > 0 || remainingAttempts == -1)) {
                    context.emit(v -> {
                        log.debug("Failed to create connection. Will retry in " + options.getReconnectInterval() + " milliseconds");
                        vertx.setTimer(options.getReconnectInterval(), tid -> connectInternal(proxyOptions, remoteAddress, peerAddress, serverName, ssl, useAlpn, registerWriteHandlers, connectHandler, context, remainingAttempts == -1 ? remainingAttempts : remainingAttempts - 1));
                    });
                } else {
                    failed(context, null, cause, connectHandler);
                }
            }
        });
    } else {
        eventLoop.execute(() -> connectInternal(proxyOptions, remoteAddress, peerAddress, serverName, ssl, useAlpn, registerWriteHandlers, connectHandler, context, remainingAttempts));
    }
}
Also used : ChannelOption(io.netty.channel.ChannelOption) LoggingHandler(io.netty.handler.logging.LoggingHandler) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) DefaultChannelGroup(io.netty.channel.group.DefaultChannelGroup) ContextInternal(io.vertx.core.impl.ContextInternal) TCPMetrics(io.vertx.core.spi.metrics.TCPMetrics) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) ConnectException(java.net.ConnectException) AsyncResult(io.vertx.core.AsyncResult) NetClient(io.vertx.core.net.NetClient) Metrics(io.vertx.core.spi.metrics.Metrics) SocketAddress(io.vertx.core.net.SocketAddress) Logger(io.vertx.core.impl.logging.Logger) Closeable(io.vertx.core.Closeable) ProxyOptions(io.vertx.core.net.ProxyOptions) ChannelGroup(io.netty.channel.group.ChannelGroup) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) VertxInternal(io.vertx.core.impl.VertxInternal) Predicate(java.util.function.Predicate) Promise(io.vertx.core.Promise) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoop(io.netty.channel.EventLoop) PartialPooledByteBufAllocator(io.vertx.core.buffer.impl.PartialPooledByteBufAllocator) Future(io.vertx.core.Future) FileNotFoundException(java.io.FileNotFoundException) NetClientOptions(io.vertx.core.net.NetClientOptions) Channel(io.netty.channel.Channel) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Bootstrap(io.netty.bootstrap.Bootstrap) IdleStateHandler(io.netty.handler.timeout.IdleStateHandler) CloseFuture(io.vertx.core.impl.CloseFuture) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) Handler(io.vertx.core.Handler) NetSocket(io.vertx.core.net.NetSocket) Channel(io.netty.channel.Channel) FileNotFoundException(java.io.FileNotFoundException) EventLoop(io.netty.channel.EventLoop) Bootstrap(io.netty.bootstrap.Bootstrap) Future(io.vertx.core.Future) CloseFuture(io.vertx.core.impl.CloseFuture) ChannelGroupFuture(io.netty.channel.group.ChannelGroupFuture) ConnectException(java.net.ConnectException)

Aggregations

GenericFutureListener (io.netty.util.concurrent.GenericFutureListener)26 ChannelFuture (io.netty.channel.ChannelFuture)11 Future (io.netty.util.concurrent.Future)11 Channel (io.netty.channel.Channel)7 InetSocketAddress (java.net.InetSocketAddress)7 Map (java.util.Map)7 Future (io.vertx.core.Future)5 Handler (io.vertx.core.Handler)5 ContextInternal (io.vertx.core.impl.ContextInternal)5 VertxInternal (io.vertx.core.impl.VertxInternal)5 IOException (java.io.IOException)5 Bootstrap (io.netty.bootstrap.Bootstrap)4 ChannelFutureListener (io.netty.channel.ChannelFutureListener)4 ChannelOption (io.netty.channel.ChannelOption)4 AsyncResult (io.vertx.core.AsyncResult)4 PromiseInternal (io.vertx.core.impl.future.PromiseInternal)4 SocketAddress (io.vertx.core.net.SocketAddress)4 List (java.util.List)4 Test (org.junit.Test)4 Logger (org.slf4j.Logger)4