Search in sources :

Example 11 with ChannelFuture

use of io.netty.channel.ChannelFuture in project vert.x by eclipse.

the class ProxyChannelProvider method connect.

@Override
public void connect(VertxInternal vertx, Bootstrap bootstrap, ProxyOptions options, String host, int port, Handler<Channel> channelInitializer, Handler<AsyncResult<Channel>> channelHandler) {
    final String proxyHost = options.getHost();
    final int proxyPort = options.getPort();
    final String proxyUsername = options.getUsername();
    final String proxyPassword = options.getPassword();
    final ProxyType proxyType = options.getType();
    vertx.resolveAddress(proxyHost, dnsRes -> {
        if (dnsRes.succeeded()) {
            InetAddress address = dnsRes.result();
            InetSocketAddress proxyAddr = new InetSocketAddress(address, proxyPort);
            ProxyHandler proxy;
            switch(proxyType) {
                default:
                case HTTP:
                    proxy = proxyUsername != null && proxyPassword != null ? new HttpProxyHandler(proxyAddr, proxyUsername, proxyPassword) : new HttpProxyHandler(proxyAddr);
                    break;
                case SOCKS5:
                    proxy = proxyUsername != null && proxyPassword != null ? new Socks5ProxyHandler(proxyAddr, proxyUsername, proxyPassword) : new Socks5ProxyHandler(proxyAddr);
                    break;
                case SOCKS4:
                    proxy = proxyUsername != null ? new Socks4ProxyHandler(proxyAddr, proxyUsername) : new Socks4ProxyHandler(proxyAddr);
                    break;
            }
            bootstrap.resolver(NoopAddressResolverGroup.INSTANCE);
            InetSocketAddress targetAddress = InetSocketAddress.createUnresolved(host, port);
            bootstrap.handler(new ChannelInitializer<Channel>() {

                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addFirst("proxy", proxy);
                    pipeline.addLast(new ChannelInboundHandlerAdapter() {

                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            if (evt instanceof ProxyConnectionEvent) {
                                pipeline.remove(proxy);
                                pipeline.remove(this);
                                channelInitializer.handle(ch);
                                channelHandler.handle(Future.succeededFuture(ch));
                            }
                            ctx.fireUserEventTriggered(evt);
                        }

                        @Override
                        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                            channelHandler.handle(Future.failedFuture(cause));
                        }
                    });
                }
            });
            ChannelFuture future = bootstrap.connect(targetAddress);
            future.addListener(res -> {
                if (!res.isSuccess()) {
                    channelHandler.handle(Future.failedFuture(res.cause()));
                }
            });
        } else {
            channelHandler.handle(Future.failedFuture(dnsRes.cause()));
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ProxyHandler(io.netty.handler.proxy.ProxyHandler) HttpProxyHandler(io.netty.handler.proxy.HttpProxyHandler) Socks4ProxyHandler(io.netty.handler.proxy.Socks4ProxyHandler) Socks5ProxyHandler(io.netty.handler.proxy.Socks5ProxyHandler) InetSocketAddress(java.net.InetSocketAddress) Channel(io.netty.channel.Channel) ProxyConnectionEvent(io.netty.handler.proxy.ProxyConnectionEvent) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Socks4ProxyHandler(io.netty.handler.proxy.Socks4ProxyHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) Socks5ProxyHandler(io.netty.handler.proxy.Socks5ProxyHandler) HttpProxyHandler(io.netty.handler.proxy.HttpProxyHandler) ProxyType(io.vertx.core.net.ProxyType) InetAddress(java.net.InetAddress) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter)

Example 12 with ChannelFuture

use of io.netty.channel.ChannelFuture in project vert.x by eclipse.

the class ChannelProvider method connect.

public void connect(VertxInternal vertx, Bootstrap bootstrap, ProxyOptions options, String host, int port, Handler<Channel> channelInitializer, Handler<AsyncResult<Channel>> channelHandler) {
    bootstrap.resolver(vertx.nettyAddressResolverGroup());
    bootstrap.handler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel channel) throws Exception {
            channelInitializer.handle(channel);
        }
    });
    ChannelFuture fut = bootstrap.connect(host, port);
    fut.addListener(res -> {
        if (res.isSuccess()) {
            channelHandler.handle(Future.succeededFuture(fut.channel()));
        } else {
            channelHandler.handle(Future.failedFuture(res.cause()));
        }
    });
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel)

Example 13 with ChannelFuture

use of io.netty.channel.ChannelFuture in project vert.x by eclipse.

the class Http2ClientTest method testClearText.

private void testClearText(boolean upgrade) throws Exception {
    ServerBootstrap bootstrap = createH2CServer((dec, enc) -> new Http2EventAdapter() {

        @Override
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
            enc.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("200"), 0, true, ctx.newPromise());
            ctx.flush();
        }
    }, upgrade);
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTP_HOST, DEFAULT_HTTP_PORT).sync();
    try {
        client.close();
        client = vertx.createHttpClient(clientOptions.setUseAlpn(false).setSsl(false).setHttp2ClearTextUpgrade(upgrade));
        client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
            assertEquals(HttpVersion.HTTP_2, resp.version());
            testComplete();
        }).exceptionHandler(this::fail).end();
        await();
    } finally {
        s.channel().close().sync();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap)

Example 14 with ChannelFuture

use of io.netty.channel.ChannelFuture in project vert.x by eclipse.

the class Http2ClientTest method testGet.

@Test
public void testGet() throws Exception {
    ServerBootstrap bootstrap = createH2Server((decoder, encoder) -> new Http2EventAdapter() {

        @Override
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
            vertx.runOnContext(v -> {
                assertTrue(endStream);
                encoder.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("200"), 0, true, ctx.newPromise());
                ctx.flush();
            });
        }

        @Override
        public void onGoAwayRead(ChannelHandlerContext ctx, int lastStreamId, long errorCode, ByteBuf debugData) throws Http2Exception {
            vertx.runOnContext(v -> {
                testComplete();
            });
        }
    });
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    try {
        HttpClientRequest req = client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath");
        req.handler(resp -> {
            Context ctx = vertx.getOrCreateContext();
            assertOnIOContext(ctx);
            resp.endHandler(v -> {
                assertOnIOContext(ctx);
                req.connection().close();
            });
        }).end();
        await();
    } finally {
        s.channel().close().sync();
    }
}
Also used : Arrays(java.util.Arrays) JksOptions(io.vertx.core.net.JksOptions) BiFunction(java.util.function.BiFunction) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) AsciiString(io.netty.util.AsciiString) Cert(io.vertx.test.core.tls.Cert) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Exception(io.netty.handler.codec.http2.Http2Exception) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) AbstractHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder) StreamResetException(io.vertx.core.http.StreamResetException) ChannelInitializer(io.netty.channel.ChannelInitializer) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) Http2FrameListener(io.netty.handler.codec.http2.Http2FrameListener) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Http2Headers(io.netty.handler.codec.http2.Http2Headers) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Http2Error(io.netty.handler.codec.http2.Http2Error) GZIPOutputStream(java.util.zip.GZIPOutputStream) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) HttpServerRequest(io.vertx.core.http.HttpServerRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) io.vertx.core(io.vertx.core) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpClientRequest(io.vertx.core.http.HttpClientRequest) ByteBuf(io.netty.buffer.ByteBuf) ConnectException(java.net.ConnectException) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) SocketAddress(io.vertx.core.net.SocketAddress) EventLoopGroup(io.netty.channel.EventLoopGroup) VertxInternal(io.vertx.core.impl.VertxInternal) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) SSLHelper(io.vertx.core.net.impl.SSLHelper) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) Http2Settings(io.netty.handler.codec.http2.Http2Settings) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) Http2ServerUpgradeCodec(io.netty.handler.codec.http2.Http2ServerUpgradeCodec) HttpMethod(io.vertx.core.http.HttpMethod) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2CodecUtil(io.netty.handler.codec.http2.Http2CodecUtil) HttpServerUpgradeHandler(io.netty.handler.codec.http.HttpServerUpgradeHandler) ChannelFuture(io.netty.channel.ChannelFuture) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Http2Exception(io.netty.handler.codec.http2.Http2Exception) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) Test(org.junit.Test)

Example 15 with ChannelFuture

use of io.netty.channel.ChannelFuture in project vert.x by eclipse.

the class Http2ClientTest method testStreamError.

@Test
public void testStreamError() throws Exception {
    waitFor(3);
    ServerBootstrap bootstrap = createH2Server((dec, enc) -> new Http2EventAdapter() {

        @Override
        public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
            enc.writeHeaders(ctx, streamId, new DefaultHttp2Headers().status("200"), 0, false, ctx.newPromise());
            // Send a corrupted frame on purpose to check we get the corresponding error in the request exception handler
            // the error is : greater padding value 0c -> 1F
            // ChannelFuture a = encoder.frameWriter().writeData(request.context, id, Buffer.buffer("hello").getByteBuf(), 12, false, request.context.newPromise());
            // normal frame    : 00 00 12 00 08 00 00 00 03 0c 68 65 6c 6c 6f 00 00 00 00 00 00 00 00 00 00 00 00
            // corrupted frame : 00 00 12 00 08 00 00 00 03 1F 68 65 6c 6c 6f 00 00 00 00 00 00 00 00 00 00 00 00
            ctx.channel().write(Buffer.buffer(new byte[] { 0x00, 0x00, 0x12, 0x00, 0x08, 0x00, 0x00, 0x00, (byte) (streamId & 0xFF), 0x1F, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }).getByteBuf());
            ctx.flush();
        }
    });
    ChannelFuture s = bootstrap.bind(DEFAULT_HTTPS_HOST, DEFAULT_HTTPS_PORT).sync();
    try {
        Context ctx = vertx.getOrCreateContext();
        ctx.runOnContext(v -> {
            client.get(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, "/somepath", resp -> {
                resp.exceptionHandler(err -> {
                    assertOnIOContext(ctx);
                    if (err instanceof Http2Exception) {
                        complete();
                    }
                });
            }).connectionHandler(conn -> {
                conn.exceptionHandler(err -> {
                    assertOnIOContext(ctx);
                    if (err instanceof Http2Exception) {
                        complete();
                    }
                });
            }).exceptionHandler(err -> {
                assertOnIOContext(ctx);
                if (err instanceof Http2Exception) {
                    complete();
                }
            }).sendHead();
        });
        await();
    } finally {
        s.channel().close().sync();
    }
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Arrays(java.util.Arrays) JksOptions(io.vertx.core.net.JksOptions) BiFunction(java.util.function.BiFunction) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) AsciiString(io.netty.util.AsciiString) Cert(io.vertx.test.core.tls.Cert) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Exception(io.netty.handler.codec.http2.Http2Exception) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) AbstractHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder) StreamResetException(io.vertx.core.http.StreamResetException) ChannelInitializer(io.netty.channel.ChannelInitializer) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) Http2FrameListener(io.netty.handler.codec.http2.Http2FrameListener) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Http2Headers(io.netty.handler.codec.http2.Http2Headers) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Http2Error(io.netty.handler.codec.http2.Http2Error) GZIPOutputStream(java.util.zip.GZIPOutputStream) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) HttpServerRequest(io.vertx.core.http.HttpServerRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) io.vertx.core(io.vertx.core) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpClientRequest(io.vertx.core.http.HttpClientRequest) ByteBuf(io.netty.buffer.ByteBuf) ConnectException(java.net.ConnectException) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) SocketAddress(io.vertx.core.net.SocketAddress) EventLoopGroup(io.netty.channel.EventLoopGroup) VertxInternal(io.vertx.core.impl.VertxInternal) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) SSLHelper(io.vertx.core.net.impl.SSLHelper) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) Http2Settings(io.netty.handler.codec.http2.Http2Settings) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) Http2ServerUpgradeCodec(io.netty.handler.codec.http2.Http2ServerUpgradeCodec) HttpMethod(io.vertx.core.http.HttpMethod) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2CodecUtil(io.netty.handler.codec.http2.Http2CodecUtil) HttpServerUpgradeHandler(io.netty.handler.codec.http.HttpServerUpgradeHandler) Http2Exception(io.netty.handler.codec.http2.Http2Exception) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) Test(org.junit.Test)

Aggregations

ChannelFuture (io.netty.channel.ChannelFuture)361 Test (org.junit.Test)128 Channel (io.netty.channel.Channel)114 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)102 Bootstrap (io.netty.bootstrap.Bootstrap)93 ChannelFutureListener (io.netty.channel.ChannelFutureListener)86 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)86 ByteBuf (io.netty.buffer.ByteBuf)81 InetSocketAddress (java.net.InetSocketAddress)78 EventLoopGroup (io.netty.channel.EventLoopGroup)71 IOException (java.io.IOException)69 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)68 ChannelPipeline (io.netty.channel.ChannelPipeline)63 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)59 ClosedChannelException (java.nio.channels.ClosedChannelException)56 AtomicReference (java.util.concurrent.atomic.AtomicReference)47 ArrayList (java.util.ArrayList)46 ChannelInitializer (io.netty.channel.ChannelInitializer)45 Http2Headers (io.netty.handler.codec.http2.Http2Headers)44 SslHandler (io.netty.handler.ssl.SslHandler)44