Example usage for io.netty.handler.codec.http HttpResponseDecoder HttpResponseDecoder

List of usage examples for io.netty.handler.codec.http HttpResponseDecoder HttpResponseDecoder

Introduction

In this page you can find the example usage for io.netty.handler.codec.http HttpResponseDecoder HttpResponseDecoder.

Prototype

public HttpResponseDecoder() 

Source Link

Document

Creates a new instance with the default maxInitialLineLength (4096) , maxHeaderSize (8192) , and maxChunkSize (8192) .

Usage

From source file:books.netty.protocol.http.xml.client.HttpXmlClient.java

License:Apache License

public void connect(int port) throws Exception {
    // ?NIO/*from ww w.ja  va  2 s  . c  om*/
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast("http-decoder", new HttpResponseDecoder());
                        ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
                        // XML?
                        ch.pipeline().addLast("xml-decoder", new HttpXmlResponseDecoder(Order.class, true));
                        ch.pipeline().addLast("http-encoder", new HttpRequestEncoder());
                        ch.pipeline().addLast("xml-encoder", new HttpXmlRequestEncoder());
                        ch.pipeline().addLast("xmlClientHandler", new HttpXmlClientHandle());
                    }
                });

        // ??
        ChannelFuture f = b.connect(new InetSocketAddress(port)).sync();

        // 
        f.channel().closeFuture().sync();
    } finally {
        // NIO
        group.shutdownGracefully();
    }
}

From source file:cn.yesway.demo.book.protocol.http.xml.client.HttpXmlClient.java

License:Apache License

public void connect(int port) throws Exception {
    // ?NIO//from   w w w  . ja va2s  .c o  m
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("http-decoder", new HttpResponseDecoder());
                        ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
                        // XML?
                        ch.pipeline().addLast("xml-decoder", new HttpXmlResponseDecoder(Order.class, true));
                        ch.pipeline().addLast("http-encoder", new HttpRequestEncoder());
                        ch.pipeline().addLast("xml-encoder", new HttpXmlRequestEncoder());
                        ch.pipeline().addLast("xmlClientHandler", new HttpXmlClientHandle());
                    }
                });

        // ??
        ChannelFuture f = b.connect(new InetSocketAddress(port)).sync();

        // 
        f.channel().closeFuture().sync();
    } finally {
        // NIO
        group.shutdownGracefully();
    }
}

From source file:com.difference.historybook.proxy.littleproxy.LittleProxy.java

License:Apache License

private HttpFiltersSource getFiltersSource() {
    return new HttpFiltersSourceAdapter() {
        @Override/*w w w.  j  a  v  a 2  s.c  om*/
        public HttpFilters filterRequest(HttpRequest originalRequest) {

            return new HttpFiltersAdapter(originalRequest) {
                private final ProxyFilter filter = filterFactory != null ? filterFactory.getInstance() : null;
                private EmbeddedChannel bufferChannel = null;

                @Override
                public HttpResponse clientToProxyRequest(HttpObject httpObject) {
                    if (filter != null && httpObject instanceof DefaultHttpRequest) {
                        filter.processRequest(new LittleProxyRequest((DefaultHttpRequest) httpObject));
                    }
                    return null;
                }

                @Override
                public HttpObject proxyToClientResponse(HttpObject httpObject) {
                    if (httpObject instanceof DefaultHttpResponse) {
                        DefaultHttpResponse response = (DefaultHttpResponse) httpObject;
                        Map<String, String> headers = new HashMap<>();
                        response.headers().forEach(e -> {
                            headers.put(e.getKey(), e.getValue());
                        });

                        if (selector != null && selector.test(new ProxyTransactionInfo(originalRequest.getUri(),
                                response.getStatus().code(), headers))) {
                            bufferChannel = new EmbeddedChannel(new HttpResponseDecoder(),
                                    new HttpContentDecompressor(), new HttpObjectAggregator(maxBufferSize));

                            DefaultHttpResponse copiedResponse = new DefaultHttpResponse(
                                    response.getProtocolVersion(), response.getStatus());
                            copiedResponse.headers().add(response.headers());

                            bufferChannel.writeInbound(copiedResponse);
                        }
                    } else if (httpObject instanceof DefaultHttpContent && bufferChannel != null) {
                        DefaultHttpContent httpContent = (DefaultHttpContent) httpObject;
                        bufferChannel.writeInbound(httpContent.copy());

                        if (ProxyUtils.isLastChunk(httpObject))
                            processChunkedResponse();
                    } else if (httpObject instanceof LastHttpContent && bufferChannel != null) {
                        LastHttpContent httpContent = (LastHttpContent) httpObject;
                        bufferChannel.writeInbound(httpContent.copy());
                        processChunkedResponse();
                    } else if (filter != null && httpObject instanceof FullHttpResponse) {
                        filter.processResponse(new LittleProxyResponse((FullHttpResponse) httpObject));
                    }
                    return httpObject;
                };

                private void processChunkedResponse() {
                    bufferChannel.flush();
                    bufferChannel.finish();
                    FullHttpResponse fullResponse = (FullHttpResponse) bufferChannel.readInbound();
                    filter.processResponse(new LittleProxyResponse(fullResponse));
                    bufferChannel = null;
                }
            };
        };
    };
}

From source file:com.dwarf.netty.guide.http.snoop.HttpSnoopClientInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();//  w w w.  ja  va 2 s .co  m

    // Enable HTTPS if necessary.
    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(ch.alloc()));
    }

    //p.addLast(new HttpClientCodec());
    p.addLast(new HttpRequestEncoder());
    p.addLast(new HttpResponseDecoder());

    // Remove the following line if you don't want automatic content decompression.
    p.addLast(new HttpContentDecompressor());

    // Uncomment the following line if you don't want to handle HttpContents.
    //p.addLast(new HttpObjectAggregator(1048576));

    p.addLast(new HttpSnoopClientHandler());
}

From source file:com.ebay.jetstream.http.netty.client.HttpClient.java

License:MIT License

private void createChannelPipeline() {

    if (isPipelineCreated())
        return;/* w w  w. ja  va  2  s. c  o m*/

    m_workerGroup = new NioEventLoopGroup(getConfig().getNumWorkers(),
            new NameableThreadFactory("Jetstream-HttpClientWorker"));
    m_bootstrap = new Bootstrap();
    m_bootstrap.group(m_workerGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_KEEPALIVE, false)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getConfig().getConnectionTimeoutInSecs())
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast("timeout",
                            new IdleStateHandler(0, getConfig().getIdleTimeoutInSecs(), 0));
                    ch.pipeline().addLast("decoder", new HttpResponseDecoder());
                    ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
                    ch.pipeline().addLast("encoder", new HttpRequestEncoder());
                    ch.pipeline().addLast("aggregator",
                            new HttpObjectAggregator(m_config.getMaxContentLength()));
                    ch.pipeline().addLast(m_httpRequestHandler);
                }
            });

    if (getConfig().getRvcBufSz() > 0) {
        m_bootstrap.option(ChannelOption.SO_RCVBUF, (int) getConfig().getRvcBufSz());
    }

    if (getConfig().getSendBufSz() > 0) {
        m_bootstrap.option(ChannelOption.SO_SNDBUF, (int) getConfig().getSendBufSz());
    }
    createdPipeline();

}

From source file:com.eucalyptus.ws.IoHandlers.java

License:Open Source License

public static ChannelHandler httpResponseDecoder() {
    return new HttpResponseDecoder();
}

From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpBlobStore.java

License:Open Source License

public HttpBlobStore(URI uri, int timeoutMillis, @Nullable final Credentials creds) throws Exception {
    boolean useTls = uri.getScheme().equals("https");
    if (uri.getPort() == -1) {
        int port = useTls ? 443 : 80;
        uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), port, uri.getPath(), uri.getQuery(),
                uri.getFragment());/*from  www . j  a  va  2s .  c o  m*/
    }
    this.uri = uri;
    final SslContext sslCtx;
    if (useTls) {
        // OpenSsl gives us a > 2x speed improvement on fast networks, but requires netty tcnative
        // to be there which is not available on all platforms and environments.
        SslProvider sslProvider = OpenSsl.isAvailable() ? SslProvider.OPENSSL : SslProvider.JDK;
        sslCtx = SslContextBuilder.forClient().sslProvider(sslProvider).build();
    } else {
        sslCtx = null;
    }
    Bootstrap clientBootstrap = new Bootstrap().channel(NioSocketChannel.class)
            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeoutMillis).group(eventLoop)
            .remoteAddress(uri.getHost(), uri.getPort());
    downloadChannels = new SimpleChannelPool(clientBootstrap, new ChannelPoolHandler() {
        @Override
        public void channelReleased(Channel ch) {
            ch.pipeline().remove("read-timeout-handler");
        }

        @Override
        public void channelAcquired(Channel ch) {
            ch.pipeline().addFirst("read-timeout-handler", new ReadTimeoutHandler(timeoutMillis));
        }

        @Override
        public void channelCreated(Channel ch) {
            ChannelPipeline p = ch.pipeline();
            p.addFirst("read-timeout-handler", new ReadTimeoutHandler(timeoutMillis));
            if (sslCtx != null) {
                SSLEngine engine = sslCtx.newEngine(ch.alloc());
                engine.setUseClientMode(true);
                p.addFirst(new SslHandler(engine));
            }
            p.addLast(new HttpClientCodec());
            p.addLast(new HttpDownloadHandler(creds));
        }
    });
    uploadChannels = new SimpleChannelPool(clientBootstrap, new ChannelPoolHandler() {
        @Override
        public void channelReleased(Channel ch) {
        }

        @Override
        public void channelAcquired(Channel ch) {
        }

        @Override
        public void channelCreated(Channel ch) {
            ChannelPipeline p = ch.pipeline();
            if (sslCtx != null) {
                SSLEngine engine = sslCtx.newEngine(ch.alloc());
                engine.setUseClientMode(true);
                p.addFirst(new SslHandler(engine));
            }
            p.addLast(new HttpResponseDecoder());
            // The 10KiB limit was chosen at random. We only expect HTTP servers to respond with
            // an error message in the body and that should always be less than 10KiB.
            p.addLast(new HttpObjectAggregator(10 * 1024));
            p.addLast(new HttpRequestEncoder());
            p.addLast(new ChunkedWriteHandler());
            p.addLast(new HttpUploadHandler(creds));
        }
    });
    this.creds = creds;
}

From source file:com.jjzhk.Chapter10.xml.HttpXmlClient.java

License:Apache License

public void connect(int port) throws Exception {
    // ?NIO?/*  ww w  . ja va 2  s  .  c  o m*/
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast("http-decoder", new HttpResponseDecoder());
                        ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536));
                        // XML??
                        ch.pipeline().addLast("xml-decoder", new HttpXmlResponseDecoder(Order.class, true));
                        ch.pipeline().addLast("http-encoder", new HttpRequestEncoder());
                        ch.pipeline().addLast("xml-encoder", new HttpXmlRequestEncoder());
                        ch.pipeline().addLast("xmlClientHandler", new HttpXmlClientHandle());
                    }
                });

        // ??
        ChannelFuture f = b.connect(new InetSocketAddress(port)).sync();

        // ?
        f.channel().closeFuture().sync();
    } finally {
        // ?NIO?
        group.shutdownGracefully();
    }
}

From source file:com.linkedin.mitm.proxy.channel.ChannelMediator.java

License:Open Source License

private void initChannelPipeline(ChannelPipeline pipeline, ServerChannelHandler serverChannelHandler,
        int idleTimeoutMsec) {
    pipeline.addLast("decoder", new HttpResponseDecoder());
    pipeline.addLast("encoder", new HttpRequestEncoder());
    pipeline.addLast("idle", new IdleStateHandler(0, 0, idleTimeoutMsec / 1000));
    pipeline.addLast("handler", serverChannelHandler);
}

From source file:com.mpush.netty.http.NettyHttpClient.java

License:Apache License

@Override
protected void doStart(Listener listener) throws Throwable {
    workerGroup = new NioEventLoopGroup(http_work, new DefaultThreadFactory(ThreadNames.T_HTTP_CLIENT));
    b = new Bootstrap();
    b.group(workerGroup);/*from   w ww.  j  a  va2s  . c  om*/
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new HttpResponseDecoder());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(maxContentLength));
            ch.pipeline().addLast("encoder", new HttpRequestEncoder());
            ch.pipeline().addLast("handler", new HttpClientHandler(NettyHttpClient.this));
        }
    });
    timer = new HashedWheelTimer(new NamedThreadFactory(T_HTTP_TIMER), 1, TimeUnit.SECONDS, 64);
    listener.onSuccess();
}