Search in sources :

Example 16 with HttpRequestDecoder

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

the class HttpSnoopServerInitializer method initChannel.

@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();
    if (sslCtx != null) {
        p.addLast(sslCtx.newHandler(ch.alloc()));
    }
    p.addLast(new HttpRequestDecoder());
    // Uncomment the following line if you don't want to handle HttpChunks.
    //p.addLast(new HttpObjectAggregator(1048576));
    p.addLast(new HttpResponseEncoder());
    // Remove the following line if you don't want automatic content compression.
    //p.addLast(new HttpContentCompressor());
    p.addLast(new HttpSnoopServerHandler());
}
Also used : HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 17 with HttpRequestDecoder

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

the class HttpServerInitializerFactory method initChannel.

@Override
protected void initChannel(Channel ch) throws Exception {
    // create a new pipeline
    ChannelPipeline pipeline = ch.pipeline();
    SslHandler sslHandler = configureServerSSLOnDemand();
    if (sslHandler != null) {
        //TODO must close on SSL exception
        // sslHandler.setCloseOnSSLException(true);
        LOG.debug("Server SSL handler configured and added as an interceptor against the ChannelPipeline: {}", sslHandler);
        pipeline.addLast("ssl", sslHandler);
    }
    pipeline.addLast("decoder", new HttpRequestDecoder(4096, configuration.getMaxHeaderSize(), 8192));
    List<ChannelHandler> decoders = consumer.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("encoder", new HttpResponseEncoder());
    List<ChannelHandler> encoders = consumer.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);
    }
    pipeline.addLast("aggregator", new HttpObjectAggregator(configuration.getChunkedMaxContentLength()));
    if (supportCompressed()) {
        pipeline.addLast("deflater", new HttpContentCompressor());
    }
    int port = consumer.getConfiguration().getPort();
    ChannelHandler handler = consumer.getEndpoint().getComponent().getMultiplexChannelHandler(port).getChannelHandler();
    if (consumer.getConfiguration().isUsingExecutorService()) {
        EventExecutorGroup applicationExecutor = consumer.getEndpoint().getComponent().getExecutorService();
        pipeline.addLast(applicationExecutor, "handler", handler);
    } else {
        pipeline.addLast("handler", handler);
    }
}
Also used : HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) EventExecutorGroup(io.netty.util.concurrent.EventExecutorGroup) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) ChannelHandlerFactory(org.apache.camel.component.netty4.ChannelHandlerFactory) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) HttpContentCompressor(io.netty.handler.codec.http.HttpContentCompressor) ChannelHandler(io.netty.channel.ChannelHandler) ChannelPipeline(io.netty.channel.ChannelPipeline) SslHandler(io.netty.handler.ssl.SslHandler)

Example 18 with HttpRequestDecoder

use of io.netty.handler.codec.http.HttpRequestDecoder in project netty-socketio by mrniko.

the class SocketIOChannelInitializer method addSocketioHandlers.

/**
     * Adds the socketio channel handlers
     *
     * @param pipeline
     */
protected void addSocketioHandlers(ChannelPipeline pipeline) {
    pipeline.addLast(HTTP_REQUEST_DECODER, new HttpRequestDecoder());
    pipeline.addLast(HTTP_AGGREGATOR, new HttpObjectAggregator(configuration.getMaxHttpContentLength()) {

        @Override
        protected Object newContinueResponse(HttpMessage start, int maxContentLength, ChannelPipeline pipeline) {
            return null;
        }
    });
    pipeline.addLast(HTTP_ENCODER, new HttpResponseEncoder());
    if (configuration.isHttpCompression()) {
        pipeline.addLast(HTTP_COMPRESSION, new HttpContentCompressor());
    }
    pipeline.addLast(PACKET_HANDLER, packetHandler);
    pipeline.addLast(AUTHORIZE_HANDLER, authorizeHandler);
    pipeline.addLast(XHR_POLLING_TRANSPORT, xhrPollingTransport);
    // TODO use single instance when https://github.com/netty/netty/issues/4755 will be resolved
    if (configuration.isWebsocketCompression()) {
        pipeline.addLast(WEB_SOCKET_TRANSPORT_COMPRESSION, new WebSocketServerCompressionHandler());
    }
    pipeline.addLast(WEB_SOCKET_TRANSPORT, webSocketTransport);
    pipeline.addLast(SOCKETIO_ENCODER, encoderHandler);
    pipeline.addLast(WRONG_URL_HANDLER, wrongUrlHandler);
}
Also used : HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) HttpContentCompressor(io.netty.handler.codec.http.HttpContentCompressor) WebSocketServerCompressionHandler(io.netty.handler.codec.http.websocketx.extensions.compression.WebSocketServerCompressionHandler) HttpMessage(io.netty.handler.codec.http.HttpMessage) ChannelPipeline(io.netty.channel.ChannelPipeline)

Example 19 with HttpRequestDecoder

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

the class HttpChannelInitializer method initChannel.

@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();
    //                  request/response payloads, etc.
    if (debugChannelLifecycleLoggingEnabled) {
        p.addLast(SERVER_WORKER_CHANNEL_DEBUG_LOGGING_HANDLER_NAME, new LoggingHandler(SERVER_WORKER_CHANNEL_DEBUG_SLF4J_LOGGER_NAME, LogLevel.DEBUG));
    }
    //          order).
    if (sslCtx != null)
        p.addLast(SSL_HANDLER_NAME, sslCtx.newHandler(ch.alloc()));
    // OUTBOUND - Add HttpResponseEncoder to encode our responses appropriately.
    //            This MUST be the earliest "outbound" handler after the SSL handler since outbound handlers are
    //            processed in reverse order.
    p.addLast(HTTP_RESPONSE_ENCODER_HANDLER_NAME, new HttpResponseEncoder());
    // OUTBOUND - Add ProcessFinalResponseOutputHandler to get the final response headers, calculate the final
    //            content length (after compression/gzip and/or any other modifications), etc, and set those values
    //            on the channel's HttpProcessingState.
    p.addLast(PROCESS_FINAL_RESPONSE_OUTPUT_HANDLER_NAME, new ProcessFinalResponseOutputHandler());
    // INBOUND - Add HttpRequestDecoder so that incoming messages are translated into the appropriate HttpMessage
    //           objects.
    p.addLast(HTTP_REQUEST_DECODER_HANDLER_NAME, new HttpRequestDecoder());
    // INBOUND - Now that the message is translated into HttpMessages we can add RequestStateCleanerHandler to
    //           setup/clean state for the rest of the pipeline.
    p.addLast(REQUEST_STATE_CLEANER_HANDLER_NAME, new RequestStateCleanerHandler(metricsListener, incompleteHttpCallTimeoutMillis));
    // INBOUND - Add DTraceStartHandler to start the distributed tracing for this request
    p.addLast(DTRACE_START_HANDLER_NAME, new DTraceStartHandler(userIdHeaderKeys));
    // INBOUND - Access log start
    p.addLast(ACCESS_LOG_START_HANDLER_NAME, new AccessLogStartHandler());
    // IN/OUT - Add SmartHttpContentCompressor for automatic content compression (if appropriate for the
    //          request/response/size threshold). This must be after HttpRequestDecoder on the incoming pipeline and
    //          before HttpResponseEncoder on the outbound pipeline (keep in mind that "before" on outbound means
    //          later in the list since outbound is processed in reverse order).
    // TODO: Make the threshold configurable
    p.addLast(SMART_HTTP_CONTENT_COMPRESSOR_HANDLER_NAME, new SmartHttpContentCompressor(500));
    // INBOUND - Add RequestInfoSetterHandler to populate our request state with a RequestInfo object
    p.addLast(REQUEST_INFO_SETTER_HANDLER_NAME, new RequestInfoSetterHandler(maxRequestSizeInBytes));
    //           maxOpenChannelsThreshold is not -1.
    if (maxOpenChannelsThreshold != -1) {
        p.addLast(OPEN_CHANNEL_LIMIT_HANDLER_NAME, new OpenChannelLimitHandler(openChannelsGroup, maxOpenChannelsThreshold));
    }
    // INBOUND - Add the RequestFilterHandler for before security (if we have any filters to apply).
    if (beforeSecurityRequestFilterHandler != null)
        p.addLast(REQUEST_FILTER_BEFORE_SECURITY_HANDLER_NAME, beforeSecurityRequestFilterHandler);
    // INBOUND - Add RoutingHandler to figure out which endpoint should handle the request and set it on our request
    //           state for later execution
    p.addLast(ROUTING_HANDLER_NAME, new RoutingHandler(endpoints, maxRequestSizeInBytes));
    // INBOUND - Add SecurityValidationHandler to validate the RequestInfo object for the matching endpoint
    p.addLast(SECURITY_VALIDATION_HANDLER_NAME, new SecurityValidationHandler(requestSecurityValidator));
    // INBOUND - Add the RequestFilterHandler for after security (if we have any filters to apply).
    if (afterSecurityRequestFilterHandler != null)
        p.addLast(REQUEST_FILTER_AFTER_SECURITY_HANDLER_NAME, afterSecurityRequestFilterHandler);
    // INBOUND - Now that the request state knows which endpoint will be called we can try to deserialize the
    //           request content (if desired by the endpoint)
    p.addLast(REQUEST_CONTENT_DESERIALIZER_HANDLER_NAME, new RequestContentDeserializerHandler(requestContentDeserializer));
    //           deserialized content (if desired by the endpoint and if we have a non-null validator)
    if (validationService != null)
        p.addLast(REQUEST_CONTENT_VALIDATION_HANDLER_NAME, new RequestContentValidationHandler(validationService));
    // INBOUND - Add NonblockingEndpointExecutionHandler to perform execution of async/nonblocking endpoints
    p.addLast(NONBLOCKING_ENDPOINT_EXECUTION_HANDLER_NAME, new NonblockingEndpointExecutionHandler(longRunningTaskExecutor, defaultCompletableFutureTimeoutMillis));
    // INBOUND - Add ProxyRouterEndpointExecutionHandler to perform execution of proxy routing endpoints
    p.addLast(PROXY_ROUTER_ENDPOINT_EXECUTION_HANDLER_NAME, new ProxyRouterEndpointExecutionHandler(longRunningTaskExecutor, streamingAsyncHttpClientForProxyRouterEndpoints, defaultCompletableFutureTimeoutMillis));
    // INBOUND - Add RequestHasBeenHandledVerificationHandler to verify that one of the endpoint handlers took care
    //           of the request. This makes sure that the messages coming into channelRead are correctly typed for
    //           the rest of the pipeline.
    p.addLast(REQUEST_HAS_BEEN_HANDLED_VERIFICATION_HANDLER_NAME, new RequestHasBeenHandledVerificationHandler());
    // INBOUND - Add ExceptionHandlingHandler to catch and deal with any exceptions or requests that fell through
    //           the cracks.
    ExceptionHandlingHandler exceptionHandlingHandler = new ExceptionHandlingHandler(riposteErrorHandler, riposteUnhandledErrorHandler);
    p.addLast(EXCEPTION_HANDLING_HANDLER_NAME, exceptionHandlingHandler);
    // INBOUND - Add the ResponseFilterHandler (if we have any filters to apply).
    if (cachedResponseFilterHandler != null)
        p.addLast(RESPONSE_FILTER_HANDLER_NAME, cachedResponseFilterHandler);
    // INBOUND - Add ResponseSenderHandler to send the response that got put into the request state
    p.addLast(RESPONSE_SENDER_HANDLER_NAME, new ResponseSenderHandler(responseSender));
    // INBOUND - Access log end
    p.addLast(ACCESS_LOG_END_HANDLER_NAME, new AccessLogEndHandler(accessLogger));
    // INBOUND - Add DTraceEndHandler to finish up our distributed trace for this request.
    p.addLast(DTRACE_END_HANDLER_NAME, new DTraceEndHandler());
    // INBOUND - Add ChannelPipelineFinalizerHandler to stop the request processing.
    p.addLast(CHANNEL_PIPELINE_FINALIZER_HANDLER_NAME, new ChannelPipelineFinalizerHandler(exceptionHandlingHandler, responseSender, metricsListener, workerChannelIdleTimeoutMillis));
    // pipeline create hooks
    if (pipelineCreateHooks != null) {
        for (PipelineCreateHook hook : pipelineCreateHooks) {
            hook.executePipelineCreateHook(p);
        }
    }
}
Also used : ExceptionHandlingHandler(com.nike.riposte.server.handler.ExceptionHandlingHandler) LoggingHandler(io.netty.handler.logging.LoggingHandler) AccessLogStartHandler(com.nike.riposte.server.handler.AccessLogStartHandler) RequestContentValidationHandler(com.nike.riposte.server.handler.RequestContentValidationHandler) ProxyRouterEndpointExecutionHandler(com.nike.riposte.server.handler.ProxyRouterEndpointExecutionHandler) RequestContentDeserializerHandler(com.nike.riposte.server.handler.RequestContentDeserializerHandler) RequestStateCleanerHandler(com.nike.riposte.server.handler.RequestStateCleanerHandler) PipelineCreateHook(com.nike.riposte.server.hooks.PipelineCreateHook) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpResponseEncoder(io.netty.handler.codec.http.HttpResponseEncoder) SmartHttpContentCompressor(com.nike.riposte.server.handler.SmartHttpContentCompressor) DTraceEndHandler(com.nike.riposte.server.handler.DTraceEndHandler) RoutingHandler(com.nike.riposte.server.handler.RoutingHandler) AccessLogEndHandler(com.nike.riposte.server.handler.AccessLogEndHandler) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) SecurityValidationHandler(com.nike.riposte.server.handler.SecurityValidationHandler) DTraceStartHandler(com.nike.riposte.server.handler.DTraceStartHandler) RequestHasBeenHandledVerificationHandler(com.nike.riposte.server.handler.RequestHasBeenHandledVerificationHandler) RequestInfoSetterHandler(com.nike.riposte.server.handler.RequestInfoSetterHandler) ChannelPipelineFinalizerHandler(com.nike.riposte.server.handler.ChannelPipelineFinalizerHandler) NonblockingEndpointExecutionHandler(com.nike.riposte.server.handler.NonblockingEndpointExecutionHandler) OpenChannelLimitHandler(com.nike.riposte.server.handler.OpenChannelLimitHandler) ProcessFinalResponseOutputHandler(com.nike.riposte.server.handler.ProcessFinalResponseOutputHandler) ResponseSenderHandler(com.nike.riposte.server.handler.ResponseSenderHandler)

Example 20 with HttpRequestDecoder

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

the class HttpChannelInitializerTest method initChannel_adds_RequestStateCleanerHandler_immediately_after_HttpRequestDecoder.

@Test
public void initChannel_adds_RequestStateCleanerHandler_immediately_after_HttpRequestDecoder() {
    // given
    HttpChannelInitializer hci = basicHttpChannelInitializerNoUtilityHandlers();
    MetricsListener expectedMetricsListener = mock(MetricsListener.class);
    long expectedIncompleteCallTimeoutMillis = 424242;
    Whitebox.setInternalState(hci, "metricsListener", expectedMetricsListener);
    Whitebox.setInternalState(hci, "incompleteHttpCallTimeoutMillis", expectedIncompleteCallTimeoutMillis);
    // when
    hci.initChannel(socketChannelMock);
    // then
    ArgumentCaptor<ChannelHandler> channelHandlerArgumentCaptor = ArgumentCaptor.forClass(ChannelHandler.class);
    verify(channelPipelineMock, atLeastOnce()).addLast(anyString(), channelHandlerArgumentCaptor.capture());
    List<ChannelHandler> handlers = channelHandlerArgumentCaptor.getAllValues();
    Pair<Integer, HttpRequestDecoder> httpRequestDecoderHandler = findChannelHandler(handlers, HttpRequestDecoder.class);
    Pair<Integer, RequestStateCleanerHandler> requestStateCleanerHandler = findChannelHandler(handlers, RequestStateCleanerHandler.class);
    assertThat(httpRequestDecoderHandler, notNullValue());
    assertThat(requestStateCleanerHandler, notNullValue());
    assertThat(requestStateCleanerHandler.getLeft(), is(httpRequestDecoderHandler.getLeft() + 1));
    RequestStateCleanerHandler handler = requestStateCleanerHandler.getRight();
    assertThat(Whitebox.getInternalState(hci, "metricsListener"), is(expectedMetricsListener));
    assertThat(Whitebox.getInternalState(hci, "incompleteHttpCallTimeoutMillis"), is(expectedIncompleteCallTimeoutMillis));
}
Also used : MetricsListener(com.nike.riposte.metrics.MetricsListener) HttpRequestDecoder(io.netty.handler.codec.http.HttpRequestDecoder) ChannelHandler(io.netty.channel.ChannelHandler) RequestStateCleanerHandler(com.nike.riposte.server.handler.RequestStateCleanerHandler) Test(org.junit.Test)

Aggregations

HttpRequestDecoder (io.netty.handler.codec.http.HttpRequestDecoder)23 HttpResponseEncoder (io.netty.handler.codec.http.HttpResponseEncoder)19 HttpObjectAggregator (io.netty.handler.codec.http.HttpObjectAggregator)12 ChannelPipeline (io.netty.channel.ChannelPipeline)11 HttpContentCompressor (io.netty.handler.codec.http.HttpContentCompressor)6 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)5 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)5 ChunkedWriteHandler (io.netty.handler.stream.ChunkedWriteHandler)5 SocketChannel (io.netty.channel.socket.SocketChannel)4 NioServerSocketChannel (io.netty.channel.socket.nio.NioServerSocketChannel)4 LoggingHandler (io.netty.handler.logging.LoggingHandler)4 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)3 DefaultFullHttpRequest (io.netty.handler.codec.http.DefaultFullHttpRequest)3 FullHttpRequest (io.netty.handler.codec.http.FullHttpRequest)3 HttpResponse (io.netty.handler.codec.http.HttpResponse)3 HttpResponseDecoder (io.netty.handler.codec.http.HttpResponseDecoder)3 RequestStateCleanerHandler (com.nike.riposte.server.handler.RequestStateCleanerHandler)2 ByteBuf (io.netty.buffer.ByteBuf)2 Channel (io.netty.channel.Channel)2 ChannelHandler (io.netty.channel.ChannelHandler)2