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,
            boolean validateHeaders) 

Source Link

Usage

From source file:io.advantageous.conekt.http.impl.HttpServerImpl.java

License:Open Source License

public synchronized HttpServer listen(int port, String host, Handler<AsyncResult<HttpServer>> listenHandler) {
    if (requestStream.handler() == null && wsStream.handler() == null) {
        throw new IllegalStateException("Set request or websocket handler first");
    }/*  w  w w  . ja  v  a 2  s. com*/
    if (listening) {
        throw new IllegalStateException("Already listening");
    }
    listenContext = vertx.getOrCreateContext();
    listening = true;
    serverOrigin = (options.isSsl() ? "https" : "http") + "://" + host + ":" + port;
    synchronized (vertx.sharedHttpServers()) {
        id = new ServerID(port, host);
        HttpServerImpl shared = vertx.sharedHttpServers().get(id);
        if (shared == null) {
            serverChannelGroup = new DefaultChannelGroup("conekt-acceptor-channels",
                    GlobalEventExecutor.INSTANCE);
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(vertx.getAcceptorEventLoopGroup(), availableWorkers);
            bootstrap.channelFactory(new VertxNioServerChannelFactory());
            applyConnectionOptions(bootstrap);
            sslHelper.validate(vertx);
            bootstrap.childHandler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    if (requestStream.isPaused() || wsStream.isPaused()) {
                        ch.close();
                        return;
                    }
                    ChannelPipeline pipeline = ch.pipeline();
                    if (sslHelper.isSSL()) {
                        pipeline.addLast("ssl", sslHelper.createSslHandler(vertx, false));
                    }
                    pipeline.addLast("httpDecoder", new HttpRequestDecoder(options.getMaxInitialLineLength(),
                            options.getMaxHeaderSize(), options.getMaxChunkSize(), false));
                    pipeline.addLast("httpEncoder", new VertxHttpResponseEncoder());
                    if (options.isCompressionSupported()) {
                        pipeline.addLast("deflater", new HttpChunkContentCompressor());
                    }
                    if (sslHelper.isSSL() || options.isCompressionSupported()) {
                        // only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used.
                        pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support
                    }
                    if (options.getIdleTimeout() > 0) {
                        pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout()));
                    }
                    pipeline.addLast("handler", new ServerHandler());
                }
            });

            addHandlers(this, listenContext);
            try {
                bindFuture = bootstrap.bind(new InetSocketAddress(InetAddress.getByName(host), port));
                Channel serverChannel = bindFuture.channel();
                serverChannelGroup.add(serverChannel);
                bindFuture.addListener(channelFuture -> {
                    if (!channelFuture.isSuccess()) {
                        vertx.sharedHttpServers().remove(id);
                    } else {
                        metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(port, host),
                                options);
                    }
                });
            } catch (final Throwable t) {
                // Make sure we send the exception back through the handler (if any)
                if (listenHandler != null) {
                    vertx.runOnContext(v -> listenHandler.handle(Future.failedFuture(t)));
                } else {
                    // No handler - log so user can see failure
                    log.error("", t);
                }
                listening = false;
                return this;
            }
            vertx.sharedHttpServers().put(id, this);
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            actualServer = shared;
            addHandlers(actualServer, listenContext);
            metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(port, host), options);
        }
        actualServer.bindFuture.addListener(future -> {
            if (listenHandler != null) {
                final AsyncResult<HttpServer> res;
                if (future.isSuccess()) {
                    res = Future.succeededFuture(HttpServerImpl.this);
                } else {
                    res = Future.failedFuture(future.cause());
                    listening = false;
                }
                listenContext.runOnContext((v) -> listenHandler.handle(res));
            } else if (!future.isSuccess()) {
                listening = false;
                // No handler - log so user can see failure
                log.error("", future.cause());
            }
        });
    }
    return this;
}

From source file:io.jsync.http.impl.DefaultHttpServer.java

License:Open Source License

public HttpServer listen(int port, String host, final Handler<AsyncResult<HttpServer>> listenHandler) {
    if (requestHandler == null && wsHandler == null) {
        throw new IllegalStateException("Set request or websocket handler first");
    }/* ww w .ja  v a  2 s . c  om*/
    if (listening) {
        throw new IllegalStateException("Listen already called");
    }
    listening = true;

    synchronized (async.sharedHttpServers()) {
        id = new ServerID(port, host);

        serverOrigin = (isSSL() ? "https" : "http") + "://" + host + ":" + port;

        DefaultHttpServer shared = async.sharedHttpServers().get(id);
        if (shared == null || port == 0) {
            serverChannelGroup = new DefaultChannelGroup("async-acceptor-channels",
                    GlobalEventExecutor.INSTANCE);
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(availableWorkers);
            bootstrap.channel(NioServerSocketChannel.class);
            tcpHelper.applyConnectionOptions(bootstrap);
            tcpHelper.checkSSL(async);
            bootstrap.childHandler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (tcpHelper.isSSL()) {
                        pipeline.addLast("ssl", tcpHelper.createSslHandler(async, false));
                    }
                    pipeline.addLast("flashpolicy", new FlashPolicyHandler());
                    pipeline.addLast("httpDecoder", new HttpRequestDecoder(4096, 8192, 8192, false));
                    pipeline.addLast("httpEncoder", new AsyncHttpResponseEncoder());
                    if (compressionSupported) {
                        pipeline.addLast("deflater", new HttpChunkContentCompressor());
                    }
                    if (tcpHelper.isSSL() || compressionSupported) {
                        // only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used.
                        pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support
                    }
                    pipeline.addLast("handler", new ServerHandler());
                }
            });

            addHandlers(this);
            try {
                bindFuture = bootstrap.bind(new InetSocketAddress(InetAddress.getByName(host), port));
                bindFuture.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) throws Exception {
                        if (!channelFuture.isSuccess()) {
                            async.sharedHttpServers().remove(id);
                        } else {
                            Channel channel = channelFuture.channel();
                            InetSocketAddress address = (InetSocketAddress) channel.localAddress();
                            DefaultHttpServer.this.actualPort = address.getPort();
                            serverChannelGroup.add(channel);
                        }
                    }
                });
            } catch (final Throwable t) {
                // Make sure we send the exception back through the handler (if any)
                if (listenHandler != null) {
                    async.runOnContext(new VoidHandler() {
                        @Override
                        protected void handle() {
                            listenHandler.handle(new DefaultFutureResult<HttpServer>(t));
                        }
                    });
                } else {
                    // No handler - log so user can see failure
                    actualCtx.reportException(t);
                }
                listening = false;
                return this;
            }
            async.sharedHttpServers().put(id, this);
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            actualServer = shared;
            this.actualPort = shared.actualPort;
            addHandlers(actualServer);
        }
        actualServer.bindFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(final ChannelFuture future) throws Exception {
                if (listenHandler != null) {
                    final AsyncResult<HttpServer> res;
                    if (future.isSuccess()) {
                        res = new DefaultFutureResult<HttpServer>(DefaultHttpServer.this);
                    } else {
                        res = new DefaultFutureResult<>(future.cause());
                        listening = false;
                    }
                    actualCtx.execute(future.channel().eventLoop(), new Runnable() {
                        @Override
                        public void run() {
                            listenHandler.handle(res);
                        }
                    });
                } else if (!future.isSuccess()) {
                    listening = false;
                    // No handler - log so user can see failure
                    actualCtx.reportException(future.cause());
                }
            }
        });
    }
    return this;
}

From source file:io.reactivex.netty.protocol.http.server.HttpServerPipelineConfigurator.java

License:Apache License

@Override
public void configureNewPipeline(ChannelPipeline pipeline) {
    pipeline.addLast(HTTP_REQUEST_DECODER_HANDLER_NAME,
            new HttpRequestDecoder(maxInitialLineLength, maxHeaderSize, maxChunkSize, validateHeaders));
    pipeline.addLast(HTTP_RESPONSE_ENCODER_HANDLER_NAME, new HttpResponseEncoder());
}

From source file:io.vertx.core.http.impl.HttpServerImpl.java

License:Open Source License

private void configureHttp1(ChannelPipeline pipeline) {
    if (logEnabled) {
        pipeline.addLast("logging", new LoggingHandler());
    }/*from  w w  w .jav a  2 s  . c  om*/
    if (USE_FLASH_POLICY_HANDLER) {
        pipeline.addLast("flashpolicy", new FlashPolicyHandler());
    }
    pipeline.addLast("httpDecoder", new HttpRequestDecoder(options.getMaxInitialLineLength(),
            options.getMaxHeaderSize(), options.getMaxChunkSize(), false));
    pipeline.addLast("httpEncoder", new VertxHttpResponseEncoder());
    if (options.isDecompressionSupported()) {
        pipeline.addLast("inflater", new HttpContentDecompressor(true));
    }
    if (options.isCompressionSupported()) {
        pipeline.addLast("deflater", new HttpChunkContentCompressor(options.getCompressionLevel()));
    }
    if (sslHelper.isSSL() || options.isCompressionSupported()) {
        // only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used.
        pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support
    }
    if (options.getIdleTimeout() > 0) {
        pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout()));
    }
    pipeline.addLast("handler", new ServerHandler(pipeline.channel()));
}

From source file:itlab.teleport.HttpServerInitializer.java

License:Apache License

@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();/*from  w w  w .ja v  a 2  s . c  om*/
    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(ch.alloc()));
    }
    p.addLast("inflater", new HttpContentDecompressor());
    p.addLast("decoder", new HttpRequestDecoder(4096, 8192, 8192, false));
    p.addLast("aggregator", new HttpObjectAggregator(1048576));
    p.addLast("encoder", new HttpResponseEncoder());
    p.addLast("deflater", new HttpContentCompressor());
    p.addLast(new HttpServerHandler());
}

From source file:net.holmes.core.service.http.HttpServer.java

License:Open Source License

/**
 * {@inheritDoc}/*from ww  w.jav  a  2 s.  c om*/
 */
@Override
public void start() {
    LOGGER.info("Starting HTTP server");

    // Start RestEasy deployment
    deployment.start();

    // Create a RestEasy request dispatcher
    final RequestDispatcher dispatcher = new RequestDispatcher(
            (SynchronousDispatcher) deployment.getDispatcher(), deployment.getProviderFactory(), null);

    // Configure the server.
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(final SocketChannel channel) {
                    ChannelPipeline pipeline = channel.pipeline();
                    // Add default handlers
                    pipeline.addLast("decoder",
                            new HttpRequestDecoder(MAX_INITIAL_LINE_LENGTH, MAX_HEADER_SIZE, MAX_CHUNK_SIZE,
                                    false))
                            .addLast("aggregator", new HttpObjectAggregator(MAX_CONTENT_LENGTH))
                            .addLast("encoder", new HttpResponseEncoder())
                            .addLast("chunkedWriter", new ChunkedWriteHandler());

                    // Add HTTP file request handlers
                    pipeline.addLast("httpFileRequestDecoder",
                            injector.getInstance(HttpFileRequestDecoder.class))
                            .addLast("httpFileRequestHandler",
                                    injector.getInstance(HttpFileRequestHandler.class));

                    // Add RestEasy handlers
                    pipeline.addLast("restEasyHttpRequestDecoder",
                            new RestEasyHttpRequestDecoder(dispatcher.getDispatcher(), RESTEASY_MAPPING_PREFIX,
                                    HTTP))
                            .addLast("restEasyHttpResponseEncoder", new RestEasyHttpResponseEncoder(dispatcher))
                            .addLast("restEasyRequestHandler", new RequestHandler(dispatcher));
                }
            }).option(SO_BACKLOG, BACKLOG).childOption(ALLOCATOR, DEFAULT).childOption(SO_KEEPALIVE, true);

    // Register backend JAX-RS handlers declared in Guice injector
    ModuleProcessor processor = new ModuleProcessor(deployment.getRegistry(), deployment.getProviderFactory());
    processor.processInjector(injector);

    // Bind and start server to accept incoming connections.
    InetSocketAddress bindAddress = new InetSocketAddress(configurationDao.getParameter(HTTP_SERVER_PORT));
    bootstrap.bind(bindAddress).syncUninterruptibly();

    LOGGER.info("HTTP server bound on {}", bindAddress);
}

From source file:net.holmes.core.service.http.HttpService.java

License:Open Source License

/**
 * {@inheritDoc}//from  ww w  .ja v a  2  s  .  com
 */
@Override
public void start() {
    LOGGER.info("Starting HTTP service");

    // Start RestEasy deployment
    resteasy.start();

    // Create a RestEasy request dispatcher
    final RequestDispatcher resteasyDispatcher = new RequestDispatcher(
            (SynchronousDispatcher) resteasy.getDispatcher(), resteasy.getProviderFactory(), null);

    // Configure the service.
    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(nettyBossGroup, nettyWorkerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(final SocketChannel channel) {
                    ChannelPipeline pipeline = channel.pipeline();
                    // Add default handlers
                    pipeline.addLast("decoder",
                            new HttpRequestDecoder(MAX_INITIAL_LINE_LENGTH, MAX_HEADER_SIZE, MAX_CHUNK_SIZE,
                                    false))
                            .addLast("aggregator", new HttpObjectAggregator(MAX_CONTENT_LENGTH))
                            .addLast("encoder", new HttpResponseEncoder())
                            .addLast("chunkedWriter", new ChunkedWriteHandler());

                    // Add HTTP file request handlers
                    pipeline.addLast("httpFileRequestDecoder",
                            injector.getInstance(HttpFileRequestDecoder.class))
                            .addLast("httpFileRequestHandler",
                                    injector.getInstance(HttpFileRequestHandler.class));

                    // Add RestEasy handlers
                    pipeline.addLast("restEasyHttpRequestDecoder",
                            new RestEasyHttpRequestDecoder(resteasyDispatcher.getDispatcher(),
                                    RESTEASY_MAPPING_PREFIX, HTTP))
                            .addLast("restEasyHttpResponseEncoder", new RestEasyHttpResponseEncoder())
                            .addLast("restEasyRequestHandler", new RequestHandler(resteasyDispatcher));
                }
            }).option(SO_BACKLOG, BACKLOG).childOption(ALLOCATOR, DEFAULT).childOption(SO_KEEPALIVE, true);

    // Register backend JAX-RS handlers (declared in Guice injector) to RestEasy
    ModuleProcessor guiceProcessor = new ModuleProcessor(resteasy.getRegistry(), resteasy.getProviderFactory());
    guiceProcessor.processInjector(injector);

    // Bind and start service to accept incoming connections
    SocketAddress boundAddress = new InetSocketAddress(configurationManager.getParameter(HTTP_SERVER_PORT));
    serverBootstrap.bind(boundAddress).syncUninterruptibly();

    LOGGER.info("HTTP service bound on {}", boundAddress);
}

From source file:org.dcache.http.HttpTransferService.java

License:Open Source License

protected void addChannelHandlers(ChannelPipeline pipeline) {
    // construct HttpRequestDecoder as netty defaults, except configurable chunk size
    pipeline.addLast("decoder", new HttpRequestDecoder(4096, 8192, getChunkSize(), true));
    pipeline.addLast("encoder", new HttpResponseEncoder());

    if (LOGGER.isDebugEnabled()) {
        pipeline.addLast("logger", new LoggingHandler());
    }//www.j  a  v a 2  s  .c  o  m
    pipeline.addLast("idle-state-handler",
            new IdleStateHandler(0, 0, clientIdleTimeout, clientIdleTimeoutUnit));
    pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
    pipeline.addLast("keepalive", new KeepAliveHandler());

    if (!customHeaders.isEmpty()) {
        pipeline.addLast("custom-headers", new CustomResponseHeadersHandler(customHeaders));
    }

    CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin()
            .allowedRequestMethods(GET, PUT, HEAD).allowedRequestHeaders(CONTENT_TYPE, AUTHORIZATION,
                    CONTENT_MD5, "Want-Digest", "suppress-www-authenticate")
            .build();
    pipeline.addLast("cors", new CorsHandler(corsConfig));

    pipeline.addLast("transfer", new HttpPoolRequestHandler(this, chunkSize));
}

From source file:org.jooby.internal.netty.NettyInitializer.java

License:Apache License

@Override
protected void initChannel(final SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    if (sslCtx != null) {
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    }//from   ww  w  .java  2 s .  co m

    pipeline.addLast("decoder",
            new HttpRequestDecoder(maxInitialLineLength, maxHeaderSize, maxChunkSize, false))
            .addLast("encoder", new HttpResponseEncoder());

    if (idleTimeOut > 0) {
        pipeline.addLast("timeout", new IdleStateHandler(0, 0, idleTimeOut, TimeUnit.MILLISECONDS));
    }

    pipeline.addLast("aggregator", new HttpObjectAggregator(maxContentLength)).addLast(executor, "handler",
            new NettyHandler(handler, config));
}

From source file:org.vertx.java.core.http.impl.DefaultHttpServer.java

License:Open Source License

public HttpServer listen(int port, String host, final Handler<AsyncResult<HttpServer>> listenHandler) {
    if (requestHandler == null && wsHandler == null) {
        throw new IllegalStateException("Set request or websocket handler first");
    }/*  w  w w .  ja  v  a 2 s  .  c o m*/
    if (listening) {
        throw new IllegalStateException("Listen already called");
    }
    listening = true;

    synchronized (vertx.sharedHttpServers()) {
        id = new ServerID(port, host);

        serverOrigin = (isSSL() ? "https" : "http") + "://" + host + ":" + port;

        DefaultHttpServer shared = vertx.sharedHttpServers().get(id);
        if (shared == null) {
            serverChannelGroup = new DefaultChannelGroup("vertx-acceptor-channels",
                    GlobalEventExecutor.INSTANCE);
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(availableWorkers);
            bootstrap.channel(NioServerSocketChannel.class);
            tcpHelper.applyConnectionOptions(bootstrap);
            tcpHelper.checkSSL(vertx);
            bootstrap.childHandler(new ChannelInitializer<Channel>() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    if (tcpHelper.isSSL()) {
                        SSLEngine engine = tcpHelper.getSSLContext().createSSLEngine();
                        engine.setUseClientMode(false);
                        switch (tcpHelper.getClientAuth()) {
                        case REQUEST: {
                            engine.setWantClientAuth(true);
                            break;
                        }
                        case REQUIRED: {
                            engine.setNeedClientAuth(true);
                            break;
                        }
                        case NONE: {
                            engine.setNeedClientAuth(false);
                            break;
                        }
                        }
                        pipeline.addLast("ssl", new SslHandler(engine));
                    }
                    pipeline.addLast("flashpolicy", new FlashPolicyHandler());
                    pipeline.addLast("httpDecoder", new HttpRequestDecoder(4096, 8192, 8192, false));
                    pipeline.addLast("httpEncoder", new VertxHttpResponseEncoder());
                    if (compressionSupported) {
                        pipeline.addLast("deflater", new HttpChunkContentCompressor());
                    }
                    if (tcpHelper.isSSL() || compressionSupported) {
                        // only add ChunkedWriteHandler when SSL is enabled otherwise it is not needed as FileRegion is used.
                        pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); // For large file / sendfile support
                    }
                    pipeline.addLast("handler", new ServerHandler());
                }
            });

            addHandlers(this);
            try {
                bindFuture = bootstrap.bind(new InetSocketAddress(InetAddress.getByName(host), port));
                Channel serverChannel = bindFuture.channel();
                serverChannelGroup.add(serverChannel);
                bindFuture.addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture channelFuture) throws Exception {
                        if (!channelFuture.isSuccess()) {
                            vertx.sharedHttpServers().remove(id);
                        }
                    }
                });
            } catch (final Throwable t) {
                // Make sure we send the exception back through the handler (if any)
                if (listenHandler != null) {
                    vertx.runOnContext(new VoidHandler() {
                        @Override
                        protected void handle() {
                            listenHandler.handle(new DefaultFutureResult<HttpServer>(t));
                        }
                    });
                } else {
                    // No handler - log so user can see failure
                    actualCtx.reportException(t);
                }
                listening = false;
                return this;
            }
            vertx.sharedHttpServers().put(id, this);
            actualServer = this;
        } else {
            // Server already exists with that host/port - we will use that
            actualServer = shared;
            addHandlers(actualServer);
        }
        actualServer.bindFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(final ChannelFuture future) throws Exception {
                if (listenHandler != null) {
                    final AsyncResult<HttpServer> res;
                    if (future.isSuccess()) {
                        res = new DefaultFutureResult<HttpServer>(DefaultHttpServer.this);
                    } else {
                        res = new DefaultFutureResult<>(future.cause());
                        listening = false;
                    }
                    actualCtx.execute(future.channel().eventLoop(), new Runnable() {
                        @Override
                        public void run() {
                            listenHandler.handle(res);
                        }
                    });
                } else if (!future.isSuccess()) {
                    listening = false;
                    // No handler - log so user can see failure
                    actualCtx.reportException(future.cause());
                }
            }
        });
    }
    return this;
}