Search in sources :

Example 1 with GenericFutureListener

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

the class NettyConnector method apply.

@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback jerseyCallback) {
    final CompletableFuture<Object> settableFuture = new CompletableFuture<>();
    final URI requestUri = jerseyRequest.getUri();
    String host = requestUri.getHost();
    int port = requestUri.getPort() != -1 ? requestUri.getPort() : "https".equals(requestUri.getScheme()) ? 443 : 80;
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                // Enable HTTPS if necessary.
                if ("https".equals(requestUri.getScheme())) {
                    // making client authentication optional for now; it could be extracted to configurable property
                    JdkSslContext jdkSslContext = new JdkSslContext(client.getSslContext(), true, ClientAuth.NONE);
                    p.addLast(jdkSslContext.newHandler(ch.alloc()));
                }
                // http proxy
                Configuration config = jerseyRequest.getConfiguration();
                final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI);
                if (proxyUri != null) {
                    final URI u = getProxyUri(proxyUri);
                    final String userName = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_USERNAME, String.class);
                    final String password = ClientProperties.getValue(config.getProperties(), ClientProperties.PROXY_PASSWORD, String.class);
                    p.addLast(new HttpProxyHandler(new InetSocketAddress(u.getHost(), u.getPort() == -1 ? 8080 : u.getPort()), userName, password));
                }
                p.addLast(new HttpClientCodec());
                p.addLast(new ChunkedWriteHandler());
                p.addLast(new HttpContentDecompressor());
                p.addLast(new JerseyClientHandler(NettyConnector.this, jerseyRequest, jerseyCallback, settableFuture));
            }
        });
        // connect timeout
        Integer connectTimeout = ClientProperties.getValue(jerseyRequest.getConfiguration().getProperties(), ClientProperties.CONNECT_TIMEOUT, 0);
        if (connectTimeout > 0) {
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
        }
        // Make the connection attempt.
        final Channel ch = b.connect(host, port).sync().channel();
        // guard against prematurely closed channel
        final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> closeListener = new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {

            @Override
            public void operationComplete(io.netty.util.concurrent.Future<? super Void> future) throws Exception {
                if (!settableFuture.isDone()) {
                    settableFuture.completeExceptionally(new IOException("Channel closed."));
                }
            }
        };
        ch.closeFuture().addListener(closeListener);
        HttpRequest nettyRequest;
        if (jerseyRequest.hasEntity()) {
            nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        } else {
            nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        }
        // headers
        for (final Map.Entry<String, List<String>> e : jerseyRequest.getStringHeaders().entrySet()) {
            nettyRequest.headers().add(e.getKey(), e.getValue());
        }
        // host header - http 1.1
        nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost());
        if (jerseyRequest.hasEntity()) {
            if (jerseyRequest.getLengthLong() == -1) {
                HttpUtil.setTransferEncodingChunked(nettyRequest, true);
            } else {
                nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong());
            }
        }
        if (jerseyRequest.hasEntity()) {
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
            final JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ch);
            jerseyRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {

                @Override
                public OutputStream getOutputStream(int contentLength) throws IOException {
                    return jerseyChunkedInput;
                }
            });
            if (HttpUtil.isTransferEncodingChunked(nettyRequest)) {
                ch.write(new HttpChunkedInput(jerseyChunkedInput));
            } else {
                ch.write(jerseyChunkedInput);
            }
            executorService.execute(new Runnable() {

                @Override
                public void run() {
                    // close listener is not needed any more.
                    ch.closeFuture().removeListener(closeListener);
                    try {
                        jerseyRequest.writeEntity();
                    } catch (IOException e) {
                        jerseyCallback.failure(e);
                        settableFuture.completeExceptionally(e);
                    }
                }
            });
            ch.flush();
        } else {
            // close listener is not needed any more.
            ch.closeFuture().removeListener(closeListener);
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
        }
    } catch (InterruptedException e) {
        settableFuture.completeExceptionally(e);
        return settableFuture;
    }
    return settableFuture;
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Configuration(javax.ws.rs.core.Configuration) InetSocketAddress(java.net.InetSocketAddress) OutputStream(java.io.OutputStream) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) URI(java.net.URI) OutboundMessageContext(org.glassfish.jersey.message.internal.OutboundMessageContext) CompletableFuture(java.util.concurrent.CompletableFuture) HttpChunkedInput(io.netty.handler.codec.http.HttpChunkedInput) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) Bootstrap(io.netty.bootstrap.Bootstrap) List(java.util.List) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) JerseyChunkedInput(org.glassfish.jersey.netty.connector.internal.JerseyChunkedInput) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) DefaultHttpRequest(io.netty.handler.codec.http.DefaultHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) JdkSslContext(io.netty.handler.ssl.JdkSslContext) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ProcessingException(javax.ws.rs.ProcessingException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) CompletableFuture(java.util.concurrent.CompletableFuture) Future(java.util.concurrent.Future) HttpProxyHandler(io.netty.handler.proxy.HttpProxyHandler) Map(java.util.Map)

Example 2 with GenericFutureListener

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

the class Http2TestUtil method newVoidPromise.

static ChannelPromise newVoidPromise(final Channel channel) {
    return new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE) {

        @Override
        public ChannelPromise addListener(GenericFutureListener<? extends Future<? super Void>> listener) {
            throw new AssertionFailedError();
        }

        @Override
        public ChannelPromise addListeners(GenericFutureListener<? extends Future<? super Void>>... listeners) {
            throw new AssertionFailedError();
        }

        @Override
        public boolean isVoid() {
            return true;
        }

        @Override
        public boolean tryFailure(Throwable cause) {
            channel().pipeline().fireExceptionCaught(cause);
            return true;
        }

        @Override
        public ChannelPromise setFailure(Throwable cause) {
            tryFailure(cause);
            return this;
        }

        @Override
        public ChannelPromise unvoid() {
            ChannelPromise promise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE);
            promise.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        channel().pipeline().fireExceptionCaught(future.cause());
                    }
                }
            });
            return promise;
        }
    };
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) DefaultChannelPromise(io.netty.channel.DefaultChannelPromise) ChannelFuture(io.netty.channel.ChannelFuture) Future(io.netty.util.concurrent.Future) ChannelPromise(io.netty.channel.ChannelPromise) DefaultChannelPromise(io.netty.channel.DefaultChannelPromise) AssertionFailedError(junit.framework.AssertionFailedError) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) ChannelFutureListener(io.netty.channel.ChannelFutureListener)

Example 3 with GenericFutureListener

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

the class ReentrantChannelTest method testCloseInFlush.

@Test
public void testCloseInFlush() throws Exception {
    LocalAddress addr = new LocalAddress("testCloseInFlush");
    ServerBootstrap sb = getLocalServerBootstrap();
    sb.bind(addr).sync().channel();
    Bootstrap cb = getLocalClientBootstrap();
    setInterest(Event.WRITE, Event.FLUSH, Event.CLOSE, Event.EXCEPTION);
    Channel clientChannel = cb.connect(addr).sync().channel();
    clientChannel.pipeline().addLast(new ChannelOutboundHandlerAdapter() {

        @Override
        public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
            promise.addListener(new GenericFutureListener<Future<? super Void>>() {

                @Override
                public void operationComplete(Future<? super Void> future) throws Exception {
                    ctx.channel().close();
                }
            });
            super.write(ctx, msg, promise);
            ctx.channel().flush();
        }
    });
    clientChannel.write(createTestBuf(2000)).sync();
    clientChannel.closeFuture().sync();
    assertLog("WRITE\nFLUSH\nCLOSE\n");
}
Also used : LocalAddress(io.netty.channel.local.LocalAddress) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ClosedChannelException(java.nio.channels.ClosedChannelException) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Future(io.netty.util.concurrent.Future) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Test(org.junit.jupiter.api.Test)

Example 4 with GenericFutureListener

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

the class TCPServerBase method listen.

private synchronized io.netty.util.concurrent.Future<Channel> listen(SocketAddress localAddress, ContextInternal context) {
    if (listening) {
        throw new IllegalStateException("Listen already called");
    }
    this.listenContext = context;
    this.listening = true;
    this.eventLoop = context.nettyEventLoop();
    SocketAddress bindAddress;
    Map<ServerID, TCPServerBase> sharedNetServers = vertx.sharedTCPServers((Class<TCPServerBase>) getClass());
    synchronized (sharedNetServers) {
        actualPort = localAddress.port();
        String hostOrPath = localAddress.isInetSocket() ? localAddress.host() : localAddress.path();
        TCPServerBase main;
        boolean shared;
        ServerID id;
        if (actualPort > 0 || localAddress.isDomainSocket()) {
            id = new ServerID(actualPort, hostOrPath);
            main = sharedNetServers.get(id);
            shared = true;
            bindAddress = localAddress;
        } else {
            if (actualPort < 0) {
                id = new ServerID(actualPort, hostOrPath + "/" + -actualPort);
                main = sharedNetServers.get(id);
                shared = true;
                bindAddress = SocketAddress.inetSocketAddress(0, localAddress.host());
            } else {
                id = new ServerID(actualPort, hostOrPath);
                main = null;
                shared = false;
                bindAddress = localAddress;
            }
        }
        if (main == null) {
            try {
                sslHelper = createSSLHelper();
                sslHelper.validate(vertx);
                worker = childHandler(listenContext, localAddress, sslHelper);
                servers = new HashSet<>();
                servers.add(this);
                channelBalancer = new ServerChannelLoadBalancer(vertx.getAcceptorEventLoopGroup().next());
                channelBalancer.addWorker(eventLoop, worker);
                ServerBootstrap bootstrap = new ServerBootstrap();
                bootstrap.group(vertx.getAcceptorEventLoopGroup(), channelBalancer.workers());
                if (sslHelper.isSSL()) {
                    bootstrap.childOption(ChannelOption.ALLOCATOR, PartialPooledByteBufAllocator.INSTANCE);
                } else {
                    bootstrap.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
                }
                bootstrap.childHandler(channelBalancer);
                applyConnectionOptions(localAddress.isDomainSocket(), bootstrap);
                bindFuture = AsyncResolveConnectHelper.doBind(vertx, bindAddress, bootstrap);
                bindFuture.addListener((GenericFutureListener<io.netty.util.concurrent.Future<Channel>>) res -> {
                    if (res.isSuccess()) {
                        Channel ch = res.getNow();
                        log.trace("Net server listening on " + hostOrPath + ":" + ch.localAddress());
                        if (shared) {
                            ch.closeFuture().addListener((ChannelFutureListener) channelFuture -> {
                                synchronized (sharedNetServers) {
                                    sharedNetServers.remove(id);
                                }
                            });
                        }
                        if (bindAddress.isInetSocket()) {
                            actualPort = ((InetSocketAddress) ch.localAddress()).getPort();
                        }
                        listenContext.addCloseHook(this);
                        metrics = createMetrics(localAddress);
                    } else {
                        if (shared) {
                            synchronized (sharedNetServers) {
                                sharedNetServers.remove(id);
                            }
                        }
                        listening = false;
                    }
                });
            } catch (Throwable t) {
                listening = false;
                return vertx.getAcceptorEventLoopGroup().next().newFailedFuture(t);
            }
            if (shared) {
                sharedNetServers.put(id, this);
            }
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            actualServer = main;
            metrics = main.metrics;
            sslHelper = main.sslHelper;
            worker = childHandler(listenContext, localAddress, sslHelper);
            actualServer.servers.add(this);
            actualServer.channelBalancer.addWorker(eventLoop, worker);
            listenContext.addCloseHook(this);
        }
    }
    return actualServer.bindFuture;
}
Also used : ChannelOption(io.netty.channel.ChannelOption) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) ContextInternal(io.vertx.core.impl.ContextInternal) TCPMetrics(io.vertx.core.spi.metrics.TCPMetrics) Context(io.vertx.core.Context) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) CompositeFuture(io.vertx.core.CompositeFuture) ChannelFutureListener(io.netty.channel.ChannelFutureListener) Map(java.util.Map) AsyncResult(io.vertx.core.AsyncResult) SocketAddress(io.vertx.core.net.SocketAddress) Logger(io.vertx.core.impl.logging.Logger) Closeable(io.vertx.core.Closeable) PromiseInternal(io.vertx.core.impl.future.PromiseInternal) VertxInternal(io.vertx.core.impl.VertxInternal) Promise(io.vertx.core.Promise) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener) Set(java.util.Set) MetricsProvider(io.vertx.core.spi.metrics.MetricsProvider) PooledByteBufAllocator(io.netty.buffer.PooledByteBufAllocator) EventLoop(io.netty.channel.EventLoop) PartialPooledByteBufAllocator(io.vertx.core.buffer.impl.PartialPooledByteBufAllocator) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) NetServerOptions(io.vertx.core.net.NetServerOptions) List(java.util.List) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Handler(io.vertx.core.Handler) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) ChannelFutureListener(io.netty.channel.ChannelFutureListener) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) CompositeFuture(io.vertx.core.CompositeFuture) Future(io.vertx.core.Future) ChannelFuture(io.netty.channel.ChannelFuture) SocketAddress(io.vertx.core.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 5 with GenericFutureListener

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

the class DatagramSocketImpl method listen.

private Future<DatagramSocket> listen(SocketAddress local) {
    AddressResolver resolver = context.owner().addressResolver();
    PromiseInternal<Void> promise = context.promise();
    io.netty.util.concurrent.Future<InetSocketAddress> f1 = resolver.resolveHostname(context.nettyEventLoop(), local.host());
    f1.addListener((GenericFutureListener<io.netty.util.concurrent.Future<InetSocketAddress>>) res1 -> {
        if (res1.isSuccess()) {
            ChannelFuture f2 = channel.bind(new InetSocketAddress(res1.getNow().getAddress(), local.port()));
            if (metrics != null) {
                f2.addListener((GenericFutureListener<io.netty.util.concurrent.Future<Void>>) res2 -> {
                    if (res2.isSuccess()) {
                        metrics.listening(local.host(), localAddress());
                    }
                });
            }
            f2.addListener(promise);
        } else {
            promise.fail(res1.cause());
        }
    });
    return promise.future().map(this);
}
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) Future(io.vertx.core.Future) ChannelFuture(io.netty.channel.ChannelFuture) GenericFutureListener(io.netty.util.concurrent.GenericFutureListener)

Aggregations

GenericFutureListener (io.netty.util.concurrent.GenericFutureListener)25 ChannelFuture (io.netty.channel.ChannelFuture)11 Future (io.netty.util.concurrent.Future)10 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