Search in sources :

Example 16 with HttpClientCodec

use of io.netty.handler.codec.http.HttpClientCodec in project netty by netty.

the class WebSocketClientHandshaker method finishHandshake.

/**
     * Validates and finishes the opening handshake initiated by {@link #handshake}}.
     *
     * @param channel
     *            Channel
     * @param response
     *            HTTP response containing the closing handshake details
     */
public final void finishHandshake(Channel channel, FullHttpResponse response) {
    verify(response);
    // Verify the subprotocol that we received from the server.
    // This must be one of our expected subprotocols - or null/empty if we didn't want to speak a subprotocol
    String receivedProtocol = response.headers().get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
    receivedProtocol = receivedProtocol != null ? receivedProtocol.trim() : null;
    String expectedProtocol = expectedSubprotocol != null ? expectedSubprotocol : "";
    boolean protocolValid = false;
    if (expectedProtocol.isEmpty() && receivedProtocol == null) {
        // No subprotocol required and none received
        protocolValid = true;
        // null or "" - we echo what the user requested
        setActualSubprotocol(expectedSubprotocol);
    } else if (!expectedProtocol.isEmpty() && receivedProtocol != null && !receivedProtocol.isEmpty()) {
        // We require a subprotocol and received one -> verify it
        for (String protocol : expectedProtocol.split(",")) {
            if (protocol.trim().equals(receivedProtocol)) {
                protocolValid = true;
                setActualSubprotocol(receivedProtocol);
                break;
            }
        }
    }
    if (!protocolValid) {
        throw new WebSocketHandshakeException(String.format("Invalid subprotocol. Actual: %s. Expected one of: %s", receivedProtocol, expectedSubprotocol));
    }
    setHandshakeComplete();
    final ChannelPipeline p = channel.pipeline();
    // Remove decompressor from pipeline if its in use
    HttpContentDecompressor decompressor = p.get(HttpContentDecompressor.class);
    if (decompressor != null) {
        p.remove(decompressor);
    }
    // Remove aggregator if present before
    HttpObjectAggregator aggregator = p.get(HttpObjectAggregator.class);
    if (aggregator != null) {
        p.remove(aggregator);
    }
    ChannelHandlerContext ctx = p.context(HttpResponseDecoder.class);
    if (ctx == null) {
        ctx = p.context(HttpClientCodec.class);
        if (ctx == null) {
            throw new IllegalStateException("ChannelPipeline does not contain " + "a HttpRequestEncoder or HttpClientCodec");
        }
        final HttpClientCodec codec = (HttpClientCodec) ctx.handler();
        // Remove the encoder part of the codec as the user may start writing frames after this method returns.
        codec.removeOutboundHandler();
        p.addAfter(ctx.name(), "ws-decoder", newWebsocketDecoder());
        // Delay the removal of the decoder so the user can setup the pipeline if needed to handle
        // WebSocketFrame messages.
        // See https://github.com/netty/netty/issues/4533
        channel.eventLoop().execute(new Runnable() {

            @Override
            public void run() {
                p.remove(codec);
            }
        });
    } else {
        if (p.get(HttpRequestEncoder.class) != null) {
            // Remove the encoder part of the codec as the user may start writing frames after this method returns.
            p.remove(HttpRequestEncoder.class);
        }
        final ChannelHandlerContext context = ctx;
        p.addAfter(context.name(), "ws-decoder", newWebsocketDecoder());
        // Delay the removal of the decoder so the user can setup the pipeline if needed to handle
        // WebSocketFrame messages.
        // See https://github.com/netty/netty/issues/4533
        channel.eventLoop().execute(new Runnable() {

            @Override
            public void run() {
                p.remove(context.handler());
            }
        });
    }
}
Also used : HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) HttpRequestEncoder(io.netty.handler.codec.http.HttpRequestEncoder) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor)

Example 17 with HttpClientCodec

use of io.netty.handler.codec.http.HttpClientCodec in project netty by netty.

the class Http2ClientInitializer method configureClearText.

/**
     * Configure the pipeline for a cleartext upgrade from HTTP to HTTP/2.
     */
private void configureClearText(SocketChannel ch) {
    HttpClientCodec sourceCodec = new HttpClientCodec();
    Http2ClientUpgradeCodec upgradeCodec = new Http2ClientUpgradeCodec(connectionHandler);
    HttpClientUpgradeHandler upgradeHandler = new HttpClientUpgradeHandler(sourceCodec, upgradeCodec, 65536);
    ch.pipeline().addLast(sourceCodec, upgradeHandler, new UpgradeRequestHandler(), new UserEventLogger());
}
Also used : Http2ClientUpgradeCodec(io.netty.handler.codec.http2.Http2ClientUpgradeCodec) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) HttpClientUpgradeHandler(io.netty.handler.codec.http.HttpClientUpgradeHandler)

Example 18 with HttpClientCodec

use of io.netty.handler.codec.http.HttpClientCodec in project camel by apache.

the class HttpClientInitializerFactory method initChannel.

@Override
protected void initChannel(Channel ch) throws Exception {
    // create a new pipeline
    ChannelPipeline pipeline = ch.pipeline();
    SslHandler sslHandler = configureClientSSLOnDemand();
    if (sslHandler != null) {
        //TODO must close on SSL exception
        //sslHandler.setCloseOnSSLException(true);
        LOG.debug("Client SSL handler configured and added as an interceptor against the ChannelPipeline: {}", sslHandler);
        pipeline.addLast("ssl", sslHandler);
    }
    pipeline.addLast("http", new HttpClientCodec());
    List<ChannelHandler> encoders = producer.getConfiguration().getEncoders();
    for (int x = 0; x < encoders.size(); x++) {
        ChannelHandler encoder = encoders.get(x);
        if (encoder instanceof ChannelHandlerFactory) {
            // use the factory to create a new instance of the channel as it may not be shareable
            encoder = ((ChannelHandlerFactory) encoder).newChannelHandler();
        }
        pipeline.addLast("encoder-" + x, encoder);
    }
    List<ChannelHandler> decoders = producer.getConfiguration().getDecoders();
    for (int x = 0; x < decoders.size(); x++) {
        ChannelHandler decoder = decoders.get(x);
        if (decoder instanceof ChannelHandlerFactory) {
            // use the factory to create a new instance of the channel as it may not be shareable
            decoder = ((ChannelHandlerFactory) decoder).newChannelHandler();
        }
        pipeline.addLast("decoder-" + x, decoder);
    }
    pipeline.addLast("aggregator", new HttpObjectAggregator(configuration.getChunkedMaxContentLength()));
    if (producer.getConfiguration().getRequestTimeout() > 0) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Using request timeout {} millis", producer.getConfiguration().getRequestTimeout());
        }
        ChannelHandler timeout = new ReadTimeoutHandler(producer.getConfiguration().getRequestTimeout(), TimeUnit.MILLISECONDS);
        pipeline.addLast("timeout", timeout);
    }
    // handler to route Camel messages
    pipeline.addLast("handler", new HttpClientChannelHandler(producer));
}
Also used : HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) HttpClientChannelHandler(org.apache.camel.component.netty4.http.handlers.HttpClientChannelHandler) ChannelHandlerFactory(org.apache.camel.component.netty4.ChannelHandlerFactory) ReadTimeoutHandler(io.netty.handler.timeout.ReadTimeoutHandler) HttpClientChannelHandler(org.apache.camel.component.netty4.http.handlers.HttpClientChannelHandler) ChannelHandler(io.netty.channel.ChannelHandler) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler)

Example 19 with HttpClientCodec

use of io.netty.handler.codec.http.HttpClientCodec in project okhttp by square.

the class NettyHttpClient method prepare.

@Override
public void prepare(final Benchmark benchmark) {
    this.concurrencyLevel = benchmark.concurrencyLevel;
    this.targetBacklog = benchmark.targetBacklog;
    ChannelInitializer<SocketChannel> channelInitializer = new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel channel) throws Exception {
            ChannelPipeline pipeline = channel.pipeline();
            if (benchmark.tls) {
                SslClient sslClient = SslClient.localhost();
                SSLEngine engine = sslClient.sslContext.createSSLEngine();
                engine.setUseClientMode(true);
                pipeline.addLast("ssl", new SslHandler(engine));
            }
            pipeline.addLast("codec", new HttpClientCodec());
            pipeline.addLast("inflater", new HttpContentDecompressor());
            pipeline.addLast("handler", new HttpChannel(channel));
        }
    };
    bootstrap = new Bootstrap();
    bootstrap.group(new NioEventLoopGroup(concurrencyLevel)).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).channel(NioSocketChannel.class).handler(channelInitializer);
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) SSLEngine(javax.net.ssl.SSLEngine) SslClient(okhttp3.internal.tls.SslClient) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler) HttpContentDecompressor(io.netty.handler.codec.http.HttpContentDecompressor) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelInitializer(io.netty.channel.ChannelInitializer) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 20 with HttpClientCodec

use of io.netty.handler.codec.http.HttpClientCodec in project riposte by Nike-Inc.

the class ComponentTestUtils method executeRequest.

public static Pair<Integer, String> executeRequest(HttpRequest request, int port, int incompleteCallTimeoutMillis) throws Exception {
    Bootstrap bootstrap = new Bootstrap();
    EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
    try {
        CompletableFuture<Pair<Integer, String>> responseFromServer = new CompletableFuture<>();
        bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();
                p.addLast(new HttpClientCodec());
                p.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
                p.addLast(new SimpleChannelInboundHandler<HttpObject>() {

                    @Override
                    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
                        if (msg instanceof FullHttpResponse) {
                            // Store the proxyServer response for asserting on later.
                            FullHttpResponse responseMsg = (FullHttpResponse) msg;
                            responseFromServer.complete(Pair.of(responseMsg.getStatus().code(), responseMsg.content().toString(UTF_8)));
                        } else {
                            // Should never happen.
                            throw new RuntimeException("Received unexpected message type: " + msg.getClass());
                        }
                    }
                });
            }
        });
        // Connect to the proxyServer.
        Channel ch = bootstrap.connect("localhost", port).sync().channel();
        // Send the request.
        ch.writeAndFlush(request);
        // Wait for the response to be received
        try {
            responseFromServer.get(incompleteCallTimeoutMillis, TimeUnit.MILLISECONDS);
        } catch (TimeoutException ex) {
            fail("The call took much longer than expected without receiving a response. " + "Cancelling this test - it's not working properly", ex);
        } finally {
            ch.close();
        }
        // If we reach here then the call should be complete.
        return responseFromServer.get();
    } finally {
        eventLoopGroup.shutdownGracefully();
    }
}
Also used : SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Channel(io.netty.channel.Channel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ChannelPipeline(io.netty.channel.ChannelPipeline) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) CompletableFuture(java.util.concurrent.CompletableFuture) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) HttpObject(io.netty.handler.codec.http.HttpObject) Bootstrap(io.netty.bootstrap.Bootstrap) FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Pair(com.nike.internal.util.Pair) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

HttpClientCodec (io.netty.handler.codec.http.HttpClientCodec)22 ChannelPipeline (io.netty.channel.ChannelPipeline)16 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)10 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)8 Bootstrap (io.netty.bootstrap.Bootstrap)7 ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)7 SocketChannel (io.netty.channel.socket.SocketChannel)7 Channel (io.netty.channel.Channel)6 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)6 HttpContentDecompressor (io.netty.handler.codec.http.HttpContentDecompressor)6 EventLoopGroup (io.netty.channel.EventLoopGroup)5 FullHttpResponse (io.netty.handler.codec.http.FullHttpResponse)5 HttpRequestEncoder (io.netty.handler.codec.http.HttpRequestEncoder)4 IOException (java.io.IOException)4 CompletableFuture (java.util.concurrent.CompletableFuture)4 ExecutionException (java.util.concurrent.ExecutionException)4 Pair (com.nike.internal.util.Pair)3 ChannelFuture (io.netty.channel.ChannelFuture)3 HttpRequest (io.netty.handler.codec.http.HttpRequest)3 SslHandler (io.netty.handler.ssl.SslHandler)3