use of io.netty.handler.codec.http.HttpResponseEncoder in project netty by netty.
the class HttpServer method start.
public ChannelFuture start() throws Exception {
ServerBootstrap b = new ServerBootstrap();
b.option(ChannelOption.SO_BACKLOG, 1024);
b.group(group).channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new HttpRequestDecoder(), new HttpResponseEncoder(), new HttpObjectAggregator(MAX_CONTENT_LENGTH), new Http1RequestHandler());
}
});
Channel ch = b.bind(PORT).sync().channel();
return ch.closeFuture();
}
use of io.netty.handler.codec.http.HttpResponseEncoder 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);
}
use of io.netty.handler.codec.http.HttpResponseEncoder in project intellij-community by JetBrains.
the class NettyUtil method addHttpServerCodec.
public static void addHttpServerCodec(@NotNull ChannelPipeline pipeline) {
pipeline.addLast("httpRequestEncoder", new HttpResponseEncoder());
// https://jetbrains.zendesk.com/agent/tickets/68315
pipeline.addLast("httpRequestDecoder", new HttpRequestDecoder(16 * 1024, 16 * 1024, 8192));
pipeline.addLast("httpObjectAggregator", new HttpObjectAggregator(MAX_CONTENT_LENGTH));
// could be added earlier if HTTPS
if (pipeline.get(ChunkedWriteHandler.class) == null) {
pipeline.addLast("chunkedWriteHandler", new ChunkedWriteHandler());
}
pipeline.addLast("corsHandler", new CorsHandlerDoNotUseOwnLogger(CorsConfigBuilder.forAnyOrigin().shortCircuit().allowCredentials().allowNullOrigin().allowedRequestMethods(HttpMethod.GET, HttpMethod.POST, HttpMethod.PUT, HttpMethod.DELETE, HttpMethod.HEAD, HttpMethod.PATCH).allowedRequestHeaders("origin", "accept", "authorization", "content-type", "x-ijt").build()));
}
use of io.netty.handler.codec.http.HttpResponseEncoder in project motan by weibocom.
the class Netty4HttpServer method open.
@Override
public boolean open() {
if (isAvailable()) {
return true;
}
if (channel != null) {
channel.close();
}
if (bossGroup == null) {
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup();
}
boolean shareChannel = url.getBooleanParameter(URLParamType.shareChannel.getName(), URLParamType.shareChannel.getBooleanValue());
// TODO max connection protect
int maxServerConnection = url.getIntParameter(URLParamType.maxServerConnection.getName(), URLParamType.maxServerConnection.getIntValue());
int workerQueueSize = url.getIntParameter(URLParamType.workerQueueSize.getName(), 500);
int minWorkerThread = 0, maxWorkerThread = 0;
if (shareChannel) {
minWorkerThread = url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MIN_WORKDER);
maxWorkerThread = url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_SHARECHANNEL_MAX_WORKDER);
} else {
minWorkerThread = url.getIntParameter(URLParamType.minWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MIN_WORKDER);
maxWorkerThread = url.getIntParameter(URLParamType.maxWorkerThread.getName(), MotanConstants.NETTY_NOT_SHARECHANNEL_MAX_WORKDER);
}
final int maxContentLength = url.getIntParameter(URLParamType.maxContentLength.getName(), URLParamType.maxContentLength.getIntValue());
final NettyHttpRequestHandler handler = new NettyHttpRequestHandler(this, messageHandler, new ThreadPoolExecutor(minWorkerThread, maxWorkerThread, 15, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(workerQueueSize)));
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("http-decoder", new HttpRequestDecoder());
ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(maxContentLength));
ch.pipeline().addLast("http-encoder", new HttpResponseEncoder());
ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
ch.pipeline().addLast("serverHandler", handler);
}
}).option(ChannelOption.SO_BACKLOG, 1024).childOption(ChannelOption.SO_KEEPALIVE, false);
ChannelFuture f;
try {
f = b.bind(url.getPort()).sync();
channel = f.channel();
} catch (InterruptedException e) {
LoggerUtil.error("init http server fail.", e);
return false;
}
state = ChannelState.ALIVE;
StatsUtil.registryStatisticCallback(this);
LoggerUtil.info("Netty4HttpServer ServerChannel finish Open: url=" + url);
return true;
}
use of io.netty.handler.codec.http.HttpResponseEncoder 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);
}
}
}
Aggregations