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

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

Introduction

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

Prototype

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

Source Link

Document

Creates a new instance with the specified decoder options.

Usage

From source file:NettyHttpTransportHandlerInitializer.java

License:Apache License

/**
 *
 * @param ch//from   w  w  w  .j a va 2 s  . c  o  m
 * @throws Exception
 */
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    //  System.out.println("Initlizing Source channel pool");
    ChannelPipeline p = ch.pipeline();

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

    p.addLast(new HttpServerCodec(102400, 102400, 102400));
    //   p.addLast(new HttpObjectAggregator(Constants.MAXIMUM_CHUNK_SIZE_AGGREGATOR));
    p.addLast(new NettyHttpTransportSourceHandler(connections));
}

From source file:com.bloom.zerofs.rest.NettyServerFactory.java

License:Open Source License

/**
 * Creates a new instance of NettyServerFactory.
 * @param verifiableProperties the in-memory {@link VerifiableProperties} to use.
 * @param metricRegistry the {@link MetricRegistry} to use.
 * @param requestHandler the {@link RestRequestHandler} to hand off the requests to.
 * @param publicAccessLogger the {@link PublicAccessLogger} that can be used for public access logging
 * @param restServerState the {@link RestServerState} that can be used to check the health of the system
 *                              to respond to health check requests
 * @throws IllegalArgumentException if any of the arguments are null.
 */// ww  w .  j a  va  2 s  . com
public NettyServerFactory(VerifiableProperties verifiableProperties, MetricRegistry metricRegistry,
        final RestRequestHandler requestHandler, final PublicAccessLogger publicAccessLogger,
        final RestServerState restServerState) {
    if (verifiableProperties == null || metricRegistry == null || requestHandler == null
            || publicAccessLogger == null || restServerState == null) {
        throw new IllegalArgumentException("Null arg(s) received during instantiation of NettyServerFactory");
    } else {
        nettyConfig = new NettyConfig(verifiableProperties);
        nettyMetrics = new NettyMetrics(metricRegistry);
        final ConnectionStatsHandler connectionStatsHandler = new ConnectionStatsHandler(nettyMetrics);
        channelInitializer = new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) {
                ch.pipeline()
                        // connection stats handler to track connection related metrics
                        .addLast("connectionStatsHandler", connectionStatsHandler)
                        // for http encoding/decoding. Note that we get content in 8KB chunks and a change to that number has
                        // to go here.
                        .addLast("codec", new HttpServerCodec(nettyConfig.nettyServerMaxInitialLineLength,
                                nettyConfig.nettyServerMaxHeaderSize, nettyConfig.nettyServerMaxChunkSize))
                        // for health check request handling
                        .addLast("healthCheckHandler", new HealthCheckHandler(restServerState, nettyMetrics))
                        // for public access logging
                        .addLast("publicAccessLogHandler",
                                new PublicAccessLogHandler(publicAccessLogger, nettyMetrics))
                        // for detecting connections that have been idle too long - probably because of an error.
                        .addLast("idleStateHandler",
                                new IdleStateHandler(0, 0, nettyConfig.nettyServerIdleTimeSeconds))
                        // for safe writing of chunks for responses
                        .addLast("chunker", new ChunkedWriteHandler())
                        // custom processing class that interfaces with a BlobStorageService.
                        .addLast("processor",
                                new NettyMessageProcessor(nettyMetrics, nettyConfig, requestHandler));
            }
        };
    }
}

From source file:com.github.ambry.rest.NettyServerChannelInitializer.java

License:Open Source License

@Override
protected void initChannel(SocketChannel ch) throws Exception {
    // If channel handler implementations are not annotated with @Sharable, Netty creates a new instance of every class
    // in the pipeline for every connection.
    // i.e. if there are a 1000 active connections there will be a 1000 NettyMessageProcessor instances.
    ChannelPipeline pipeline = ch.pipeline();
    // connection stats handler to track connection related metrics
    pipeline.addLast("connectionStatsHandler", connectionStatsHandler);
    // if SSL is enabled, add an SslHandler before the HTTP codec
    if (sslFactory != null) {
        InetSocketAddress peerAddress = ch.remoteAddress();
        String peerHost = peerAddress.getHostName();
        int peerPort = peerAddress.getPort();
        SslHandler sslHandler = new SslHandler(
                sslFactory.createSSLEngine(peerHost, peerPort, SSLFactory.Mode.SERVER));
        pipeline.addLast("sslHandler", sslHandler);
    }/*from  ww w.j  a  v a  2 s  .  co  m*/
    pipeline
            // for http encoding/decoding.
            .addLast("codec",
                    new HttpServerCodec(nettyConfig.nettyServerMaxInitialLineLength,
                            nettyConfig.nettyServerMaxHeaderSize, nettyConfig.nettyServerMaxChunkSize))
            // for health check request handling
            .addLast("healthCheckHandler", new HealthCheckHandler(restServerState, nettyMetrics))
            // for public access logging
            .addLast("publicAccessLogHandler", new PublicAccessLogHandler(publicAccessLogger, nettyMetrics))
            // for detecting connections that have been idle too long - probably because of an error.
            .addLast("idleStateHandler", new IdleStateHandler(0, 0, nettyConfig.nettyServerIdleTimeSeconds))
            // for safe writing of chunks for responses
            .addLast("chunker", new ChunkedWriteHandler())
            // custom processing class that interfaces with a BlobStorageService.
            .addLast("processor", new NettyMessageProcessor(nettyMetrics, nettyConfig, requestHandler));
}

From source file:org.glowroot.ui.HttpServer.java

License:Apache License

HttpServer(String bindAddress, int port, int numWorkerThreads, ConfigRepository configRepository,
        CommonHandler commonHandler, File certificateDir) throws Exception {

    InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE);

    ThreadFactory bossThreadFactory = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("Glowroot-Http-Boss").build();
    ThreadFactory workerThreadFactory = new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("Glowroot-Http-Worker-%d").build();
    bossGroup = new NioEventLoopGroup(1, bossThreadFactory);
    workerGroup = new NioEventLoopGroup(numWorkerThreads, workerThreadFactory);

    final HttpServerHandler handler = new HttpServerHandler(configRepository, commonHandler);

    if (configRepository.getWebConfig().https()) {
        sslContext = SslContextBuilder//from   ww w .ja  va2s  . c o m
                .forServer(new File(certificateDir, "certificate.pem"), new File(certificateDir, "private.pem"))
                .build();
    }
    this.certificateDir = certificateDir;

    bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    SslContext sslContextLocal = sslContext;
                    if (sslContextLocal != null) {
                        p.addLast(sslContextLocal.newHandler(ch.alloc()));
                    }
                    // bumping maxInitialLineLength (first arg below) from default 4096 to 32768
                    // in order to handle long urls on /jvm/gauges view
                    // bumping maxHeaderSize (second arg below) from default 8192 to 32768 for
                    // same reason due to "Referer" header once url becomes huge
                    // leaving maxChunkSize (third arg below) at default 8192
                    p.addLast(new HttpServerCodec(32768, 32768, 8192));
                    p.addLast(new HttpObjectAggregator(1048576));
                    p.addLast(new ConditionalHttpContentCompressor());
                    p.addLast(new ChunkedWriteHandler());
                    p.addLast(handler);
                }
            });
    this.handler = handler;
    logger.debug("<init>(): binding http server to port {}", port);
    this.bindAddress = bindAddress;
    Channel serverChannel;
    try {
        serverChannel = bootstrap.bind(new InetSocketAddress(bindAddress, port)).sync().channel();
    } catch (Exception e) {
        // FailedChannelFuture.sync() is using UNSAFE to re-throw checked exceptions
        bossGroup.shutdownGracefully(0, 0, SECONDS);
        workerGroup.shutdownGracefully(0, 0, SECONDS);
        throw new SocketBindException(e);
    }
    this.serverChannel = serverChannel;
    this.port = ((InetSocketAddress) serverChannel.localAddress()).getPort();
    logger.debug("<init>(): http server bound");
}