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

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

Introduction

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

Prototype

public HttpRequestDecoder(int maxInitialLineLength, int maxHeaderSize, int maxChunkSize) 

Source Link

Document

Creates a new instance with the specified parameters.

Usage

From source file:com.addthis.hydra.query.web.QueryServerInitializer.java

License:Apache License

@Override
protected void initChannel(final SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    if (log.isTraceEnabled()) {
        log.trace("New socket connection {}", ch);
        ch.closeFuture().addListener(new ChannelFutureListener() {
            @Override/*from w w w . ja  va 2s. c o  m*/
            public void operationComplete(ChannelFuture future) throws Exception {
                log.trace("channel closed {}", ch);
            }
        });
    }
    pipeline.addLast("decoder", new HttpRequestDecoder(maxInitialLineLength, maxHeaderSize, maxChunkSize));
    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("aggregator", new HttpObjectAggregator(maxContentLength));
    // compression is neat, but a little buggy
    //        pipeline.addLast(ImmediateEventExecutor.INSTANCE, "compressor", new HttpContentCompressor());
    pipeline.addLast("query", httpQueryHandler);

}

From source file:com.buildria.mocking.stub.StubHttpServer.java

License:Open Source License

@Override
public StubHttpServer start() {
    Stopwatch sw = createStarted();/*from  w ww .  j  a  va2s . co  m*/
    bossGroup = new NioEventLoopGroup();
    workerGroup = new NioEventLoopGroup();

    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                // CHECKSTYLE:OFF
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    // CHECKSTYLE:ON
                    // int maxInitialLineLength, int maxHeaderSize, int maxChunkSize
                    ch.pipeline().addLast("decoder",
                            new HttpRequestDecoder(MAX_INITIALLINE_LENGH, MAX_HEADERS_SIZE, MAX_CHUNK_SIZE));
                    ch.pipeline().addLast("aggregator", new HttpObjectAggregator(MAX_CONTENT_LENGTH));
                    ch.pipeline().addLast("encoder", new HttpResponseEncoder());
                    ch.pipeline().addLast("deflater", new HttpContentCompressor());
                    if (config.isLogging()) {
                        ch.pipeline().addLast("logging", new LoggingHandler(StubHttpServer.class));
                    }
                    ch.pipeline().addLast("handler", new Handler());
                }
            }).option(ChannelOption.SO_BACKLOG, SO_BACKLOG).childOption(ChannelOption.SO_KEEPALIVE, true);

    // Bind and start to accept incoming connections.
    int port = config.getPort();
    ChannelFuture f;
    try {
        f = b.bind(port).sync();
    } catch (InterruptedException ex) {
        throw new MockingException(ex);
    }
    f.awaitUninterruptibly();
    sw.stop();
    LOG.debug("### StubHttpServer(port:{}) started. It took {}", port, sw);
    return this;
}

From source file:com.seagate.kinetic.simulator.io.provider.nio.http.HttpChannelInitializer.java

License:Open Source License

@Override
protected void initChannel(SocketChannel ch) throws Exception {

    ChannelPipeline p = ch.pipeline();/*w w w .j  a v  a 2  s  .  c  om*/

    boolean isSsl = Boolean.getBoolean("kinetic.io.https");

    if (isSsl) {
        SSLEngine engine = SslContextFactory.getServerContext().createSSLEngine();

        engine.setUseClientMode(false);

        p.addLast("ssl", new SslHandler(engine));

        logger.info("ssl handler added, https is enabled ...");
    }

    p.addLast("decoder", new HttpRequestDecoder(1024, 4 * 1024, 4 * 1024 * 1024));

    p.addLast("encoder", new HttpResponseEncoder());

    p.addLast("aggregator", new HttpObjectAggregator(4 * 1024 * 1024));

    p.addLast("handler", new HttpMessageServiceHandler(lcservice));

    logger.info("http channel initialized. ssl/tls enabled=" + isSsl);
}

From source file:com.vmware.dcp.common.http.netty.NettyHttpServerInitializer.java

License:Open Source License

@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();//from   w ww  . j  a v a2  s.com
    ch.config().setAllocator(NettyChannelContext.ALLOCATOR);
    ch.config().setSendBufferSize(NettyChannelContext.BUFFER_SIZE);
    ch.config().setReceiveBufferSize(NettyChannelContext.BUFFER_SIZE);
    if (this.sslContext != null) {
        SslHandler handler = this.sslContext.newHandler(ch.alloc());
        SslClientAuthMode mode = this.host.getState().sslClientAuthMode;
        if (mode != null) {
            switch (mode) {
            case NEED:
                handler.engine().setNeedClientAuth(true);
                break;
            case WANT:
                handler.engine().setWantClientAuth(true);
                break;
            default:
                break;
            }
        }
        p.addLast(SSL_HANDLER, handler);
    }

    p.addLast(DECODER_HANDLER,
            new HttpRequestDecoder(MAX_INITIAL_LINE_LENGTH, MAX_HEADER_SIZE, MAX_CHUNK_SIZE));
    p.addLast(ENCODER_HANDLER, new HttpResponseEncoder());
    p.addLast(AGGREGATOR_HANDLER, new HttpObjectAggregator(NettyChannelContext.MAX_REQUEST_SIZE));
    p.addLast(DCP_WEBSOCKET_HANDLER, new NettyWebSocketRequestHandler(this.host,
            ServiceUriPaths.CORE_WEB_SOCKET_ENDPOINT, ServiceUriPaths.WEB_SOCKET_SERVICE_PREFIX));
    p.addLast(DCP_HANDLER, new NettyHttpClientRequestHandler(this.host));
}

From source file:divconq.web.WebModule.java

License:Open Source License

public void goOnline() {
    this.listenlock.lock();

    try {// ww w  .  java 2  s .  c  o  m
        // don't try if already in online mode
        if (this.activelisteners.size() > 0)
            return;

        // typically we should have an extension, unless we are supporting RPC only
        // TODO if (WebSiteManager.instance.getDefaultExtension() == null) 
        //   log.warn(0, "No default extension for web server");

        for (final XElement httpconfig : this.config.selectAll("HttpListener")) {
            final boolean secure = "True".equals(httpconfig.getAttribute("Secure"));
            int httpport = (int) StringUtil.parseInt(httpconfig.getAttribute("Port"), secure ? 443 : 80);

            // -------------------------------------------------
            // message port
            // -------------------------------------------------
            ServerBootstrap b = new ServerBootstrap();

            // TODO consider using shared EventLoopGroup
            // http://normanmaurer.me/presentations/2014-facebook-eng-netty/slides.html#25.0

            b.group(Hub.instance.getEventLoopGroup()).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.ALLOCATOR, Hub.instance.getBufferAllocator())
                    //.option(ChannelOption.SO_BACKLOG, 125)         // this is probably not needed but serves as note to research
                    .option(ChannelOption.TCP_NODELAY, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();

                            if (secure) {
                                SniHandler ssl = new SniHandler(WebModule.this.siteman);

                                //SslHandler ssl = new SslHandler(WebModule.this.siteman.findSslContextFactory("root").getServerEngine()); 

                                pipeline.addLast("ssl", ssl);
                            }

                            //pipeline.addLast("codec-http", new HttpServerCodec());
                            //pipeline.addLast("aggregator", new HttpObjectAggregator(65536));

                            pipeline.addLast("decoder", new HttpRequestDecoder(4096, 8192, 262144));
                            pipeline.addLast("encoder", new HttpResponseEncoder());

                            pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());

                            // TODO maybe - but currently we selectively compress files which is more efficient
                            // this can also be a cached & compressed response that way
                            //pipeline.addLast("deflater", new HttpContentCompressor());

                            pipeline.addLast("handler", new ServerHandler(httpconfig, WebModule.this.siteman));
                        }
                    });

            try {
                // must wait here, both to keep the activelisteners listeners up to date
                // but also to make sure we don't release connectLock too soon
                ChannelFuture bfuture = b.bind(httpport).sync();

                if (bfuture.isSuccess()) {
                    Logger.info("Web Server listening - now listening for HTTP on TCP port " + httpport);
                    this.activelisteners.put(httpport, bfuture.channel());
                } else
                    Logger.error("Web Server unable to bind: " + bfuture.cause());
            } catch (InterruptedException x) {
                Logger.error("Web Server interrupted while binding: " + x);
            } catch (Exception x) {
                Logger.error("Web Server errored while binding: " + x);
            }
        }
    } finally {
        this.listenlock.unlock();
    }

    this.siteman.online();

    //for (IWebExtension ext : WebSiteManager.instance.extensions.values())
    //   ext.online();
}

From source file:org.apache.hyracks.http.server.HttpServerInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();//from www  .  j  a  v a2 s  .com
    p.addLast(new HttpRequestCapacityController(server));
    p.addLast(new HttpRequestDecoder(MAX_REQUEST_INITIAL_LINE_LENGTH, MAX_REQUEST_HEADER_SIZE,
            MAX_REQUEST_CHUNK_SIZE));
    p.addLast(new HttpResponseEncoder());
    p.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
    p.addLast(server.createHttpHandler(RESPONSE_CHUNK_SIZE));
}

From source file:org.apache.tinkerpop.gremlin.server.channel.WebSocketChannelizer.java

License:Apache License

@Override
public void configure(final ChannelPipeline pipeline) {
    if (logger.isDebugEnabled())
        pipeline.addLast(new LoggingHandler("log-io", LogLevel.DEBUG));

    logger.debug("HttpRequestDecoder settings - maxInitialLineLength={}, maxHeaderSize={}, maxChunkSize={}",
            settings.maxInitialLineLength, settings.maxHeaderSize, settings.maxChunkSize);
    pipeline.addLast("http-request-decoder", new HttpRequestDecoder(settings.maxInitialLineLength,
            settings.maxHeaderSize, settings.maxChunkSize));

    if (logger.isDebugEnabled())
        pipeline.addLast(new LoggingHandler("log-decoder-aggregator", LogLevel.DEBUG));

    logger.debug("HttpObjectAggregator settings - maxContentLength={}, maxAccumulationBufferComponents={}",
            settings.maxContentLength, settings.maxAccumulationBufferComponents);
    final HttpObjectAggregator aggregator = new HttpObjectAggregator(settings.maxContentLength);
    aggregator.setMaxCumulationBufferComponents(settings.maxAccumulationBufferComponents);
    pipeline.addLast("aggregator", aggregator);

    if (logger.isDebugEnabled())
        pipeline.addLast(new LoggingHandler("log-aggregator-encoder", LogLevel.DEBUG));

    pipeline.addLast("http-response-encoder", new HttpResponseEncoder());
    pipeline.addLast("request-handler",
            new WebSocketServerProtocolHandler("/gremlin", null, false, settings.maxContentLength));

    if (logger.isDebugEnabled())
        pipeline.addLast(new LoggingHandler("log-aggregator-encoder", LogLevel.DEBUG));

    pipeline.addLast("ws-frame-encoder", wsGremlinResponseFrameEncoder);
    pipeline.addLast("response-frame-encoder", gremlinResponseFrameEncoder);
    pipeline.addLast("request-text-decoder", wsGremlinTextRequestDecoder);
    pipeline.addLast("request-binary-decoder", wsGremlinBinaryRequestDecoder);
    pipeline.addLast("request-close-decoder", wsGremlinCloseRequestDecoder);

    if (logger.isDebugEnabled())
        pipeline.addLast(new LoggingHandler("log-aggregator-encoder", LogLevel.DEBUG));

    if (authenticationHandler != null)
        pipeline.addLast(PIPELINE_AUTHENTICATOR, authenticationHandler);
}

From source file:org.elasticsearch.http.nio.HttpReadWriteHandler.java

License:Apache License

public HttpReadWriteHandler(NioHttpChannel nioHttpChannel, NioHttpServerTransport transport,
        HttpHandlingSettings settings, NioCorsConfig corsConfig) {
    this.nioHttpChannel = nioHttpChannel;
    this.transport = transport;

    List<ChannelHandler> handlers = new ArrayList<>(5);
    HttpRequestDecoder decoder = new HttpRequestDecoder(settings.getMaxInitialLineLength(),
            settings.getMaxHeaderSize(), settings.getMaxChunkSize());
    decoder.setCumulator(ByteToMessageDecoder.COMPOSITE_CUMULATOR);
    handlers.add(decoder);//from www .jav  a 2s.  c  o  m
    handlers.add(new HttpContentDecompressor());
    handlers.add(new HttpResponseEncoder());
    handlers.add(new HttpObjectAggregator(settings.getMaxContentLength()));
    if (settings.isCompression()) {
        handlers.add(new HttpContentCompressor(settings.getCompressionLevel()));
    }
    if (settings.isCorsEnabled()) {
        handlers.add(new NioCorsHandler(corsConfig));
    }
    handlers.add(new NioHttpPipeliningHandler(transport.getLogger(), settings.getPipeliningMaxEvents()));

    adaptor = new NettyAdaptor(handlers.toArray(new ChannelHandler[0]));
    adaptor.addCloseListener((v, e) -> nioHttpChannel.close());
}

From source file:org.graylog2.inputs.transports.HttpTransport.java

License:Open Source License

@Override
protected LinkedHashMap<String, Callable<? extends ChannelHandler>> getCustomChildChannelHandlers(
        MessageInput input) {//w  w w . ja va2  s  . c om
    final LinkedHashMap<String, Callable<? extends ChannelHandler>> handlers = new LinkedHashMap<>();

    if (idleWriterTimeout > 0) {
        // Install read timeout handler to close idle connections after a timeout.
        // This avoids dangling HTTP connections when the HTTP client does not close the connection properly.
        // For details see: https://github.com/Graylog2/graylog2-server/issues/3223#issuecomment-270350500
        handlers.put("read-timeout-handler", () -> new ReadTimeoutHandler(idleWriterTimeout, TimeUnit.SECONDS));
    }

    handlers.put("decoder", () -> new HttpRequestDecoder(DEFAULT_MAX_INITIAL_LINE_LENGTH,
            DEFAULT_MAX_HEADER_SIZE, maxChunkSize));
    handlers.put("aggregator", () -> new HttpObjectAggregator(maxChunkSize));
    handlers.put("encoder", HttpResponseEncoder::new);
    handlers.put("decompressor", HttpContentDecompressor::new);
    handlers.put("http-handler", () -> new HttpHandler(enableCors));
    handlers.putAll(super.getCustomChildChannelHandlers(input));

    return handlers;
}