io.netty.handler.codec.http.HttpResponseEncoder Java Examples

The following examples show how to use io.netty.handler.codec.http.HttpResponseEncoder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: NettyHttpServerInitializer.java    From piranha with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
/**
 * Initialize the channel.
 *
 * @param channel the channel.
 */
@Override
public void initChannel(SocketChannel channel) {
    ChannelPipeline pipeline = channel.pipeline();
    if (ssl) {
        try {
            SSLContext sslContext = SSLContext.getDefault();
            SSLEngine sslEngine = sslContext.createSSLEngine();
            sslEngine.setUseClientMode(false);
            pipeline.addLast(new SslHandler(sslEngine));
        } catch (NoSuchAlgorithmException e) {
            if (LOGGER.isLoggable(SEVERE)) {
                LOGGER.log(WARNING, "Unable to match SSL algorithm", e);
            }
        }
    }
    pipeline.addLast(new HttpRequestDecoder());
    pipeline.addLast(new HttpResponseEncoder());
    pipeline.addLast(new HttpObjectAggregator(10*1024*1024));
    pipeline.addLast(new NettyHttpServerHandler(httpServerProcessor));
}
 
Example #2
Source File: HttpUploadServerInitializer.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();

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

    pipeline.addLast(new HttpRequestDecoder());
    pipeline.addLast(new HttpResponseEncoder());

    // Remove the following line if you don't want automatic content compression.
    pipeline.addLast(new HttpContentCompressor());

    pipeline.addLast(new HttpUploadServerHandler());
}
 
Example #3
Source File: Ipcd10ChannelInitializer.java    From arcusipcd with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
	
	ChannelPipeline pipeline = ch.pipeline();
	
	if (serverTlsContext != null && serverTlsContext.useTls()) {
		SSLEngine engine = serverTlsContext.getContext().createSSLEngine();
		engine.setUseClientMode(false);
		pipeline.addLast("tls", new SslHandler(engine));
	}
	
	pipeline.addLast("encoder", new HttpResponseEncoder());
       pipeline.addLast("decoder", new HttpRequestDecoder());
       pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
       pipeline.addLast("handler", new Ipcd10WebSocketServerHandler(false));
}
 
Example #4
Source File: HttpUploadServerInitializer.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();

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

    pipeline.addLast(new HttpRequestDecoder());
    pipeline.addLast(new HttpResponseEncoder());

    // Remove the following line if you don't want automatic content compression.
    pipeline.addLast(new HttpContentCompressor());

    pipeline.addLast(new HttpUploadServerHandler());
}
 
Example #5
Source File: ProtocolHandler.java    From activemq-artemis with Apache License 2.0 6 votes vote down vote up
private void switchToHttp(ChannelHandlerContext ctx) {
   ChannelPipeline p = ctx.pipeline();
   p.addLast("http-decoder", new HttpRequestDecoder());
   p.addLast("http-aggregator", new HttpObjectAggregator(Integer.MAX_VALUE));
   p.addLast("http-encoder", new HttpResponseEncoder());
   //create it lazily if and when we need it
   if (httpKeepAliveRunnable == null) {
      long httpServerScanPeriod = ConfigurationHelper.getLongProperty(TransportConstants.HTTP_SERVER_SCAN_PERIOD_PROP_NAME, TransportConstants.DEFAULT_HTTP_SERVER_SCAN_PERIOD, nettyAcceptor.getConfiguration());
      httpKeepAliveRunnable = new HttpKeepAliveRunnable();
      Future<?> future = scheduledThreadPool.scheduleAtFixedRate(httpKeepAliveRunnable, httpServerScanPeriod, httpServerScanPeriod, TimeUnit.MILLISECONDS);
      httpKeepAliveRunnable.setFuture(future);
   }
   long httpResponseTime = ConfigurationHelper.getLongProperty(TransportConstants.HTTP_RESPONSE_TIME_PROP_NAME, TransportConstants.DEFAULT_HTTP_RESPONSE_TIME, nettyAcceptor.getConfiguration());
   HttpAcceptorHandler httpHandler = new HttpAcceptorHandler(httpKeepAliveRunnable, httpResponseTime, ctx.channel());
   ctx.pipeline().addLast("http-handler", httpHandler);
   p.addLast(new ProtocolDecoder(false, true));
   p.remove(this);
}
 
Example #6
Source File: ProxyInitializer.java    From flashback with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void initChannel(SocketChannel socketChannel) {
  ChannelPipeline channelPipeline = socketChannel.pipeline();
  channelPipeline.addLast("decoder", new HttpRequestDecoder());
  channelPipeline.addLast("encoder", new HttpResponseEncoder());
  channelPipeline.addLast("idle", new IdleStateHandler(0, 0, _proxyServer.getClientConnectionIdleTimeout()));
  ChannelMediator channelMediator = new ChannelMediator(socketChannel,
      _proxyServer.getProxyModeControllerFactory(),
      _proxyServer.getDownstreamWorkerGroup(),
      _proxyServer.getServerConnectionIdleTimeout(),
      _proxyServer.getAllChannels());
  ClientChannelHandler clientChannelHandler =
      new ClientChannelHandler(channelMediator, _proxyServer.getConnectionFlowRegistry());

  channelPipeline.addLast("handler", clientChannelHandler);
}
 
Example #7
Source File: HttpServerInitializer.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
	ChannelPipeline pipeline = ch.pipeline();
	if (sslCtx != null) {
		pipeline.addLast(sslCtx.newHandler(ch.alloc()));
	}
	pipeline.addLast(new HttpResponseEncoder());
	pipeline.addLast(new HttpRequestDecoder());
	// Uncomment the following line if you don't want to handle HttpChunks.
	//pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
	//p.addLast(new HttpObjectAggregator(1048576));
	// Remove the following line if you don't want automatic content compression.
	//pipeline.addLast(new HttpContentCompressor());
	
	// Uncomment the following line if you don't want to handle HttpContents.
	pipeline.addLast(new HttpObjectAggregator(65536));
	pipeline.addLast("readTimeoutHandler", new ReadTimeoutHandler(READ_TIMEOUT));
	pipeline.addLast("myHandler", new MyHandler());
	
	pipeline.addLast("handler", new HttpServerHandler(listener));
}
 
Example #8
Source File: HttpClientTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void prematureCancel() {
	FluxIdentityProcessor<Void> signal = Processors.more().multicastNoBackpressure();
	disposableServer =
			TcpServer.create()
			         .host("localhost")
			         .port(0)
			         .handle((in, out) -> {
			             signal.onComplete();
			             return out.withConnection(c -> c.addHandlerFirst(new HttpResponseEncoder()))
			                       .sendObject(Mono.delay(Duration.ofSeconds(2))
			                                       .map(t -> new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
			                                                                             HttpResponseStatus.PROCESSING)))
			                       .neverComplete();
			         })
			         .wiretap(true)
			         .bindNow(Duration.ofSeconds(30));

	StepVerifier.create(
			createHttpClientForContextWithAddress()
			        .get()
			        .uri("/")
			        .responseContent()
			        .timeout(signal))
			    .verifyError(TimeoutException.class);
}
 
Example #9
Source File: ApiServerInitializer.java    From netty.book.kor with MIT License 6 votes vote down vote up
@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(65536));
    p.addLast(new HttpResponseEncoder());
    // Remove the following line if you don't want automatic content
    // compression.
    p.addLast(new HttpContentCompressor());
    p.addLast(new ApiRequestParser());
}
 
Example #10
Source File: HttpCodecDispatcher.java    From nettythrift with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	if (msg instanceof ByteBuf && ctx.channel().isActive()) {
		boolean isHttpRequest = false;
		ByteBuf buffer = (ByteBuf) msg;
		final int len = 11;
		if (buffer.readableBytes() > len) {
			byte[] dst = new byte[len];
			buffer.getBytes(buffer.readerIndex(), dst, 0, len);
			int n = HttpMethodUtil.method(dst);
			isHttpRequest = n > 2;
		}
		if (isHttpRequest) {
			ChannelPipeline cp = ctx.pipeline();
			String currentName = ctx.name();
			cp.addAfter(currentName, "HttpRequestDecoder", new HttpRequestDecoder());
			cp.addAfter("HttpRequestDecoder", "HttpResponseEncoder", new HttpResponseEncoder());
			cp.addAfter("HttpResponseEncoder", "HttpObjectAggregator", new HttpObjectAggregator(512 * 1024));
			ChannelHandler handler = serverDef.httpHandlerFactory.create(serverDef);
			cp.addAfter("HttpObjectAggregator", "HttpThriftBufDecoder", handler);

			cp.remove(currentName);
		}
	}
	ctx.fireChannelRead(msg);
}
 
Example #11
Source File: HandlerInitializer.java    From netty-rest-server with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    /*
     * ChannelInboundHandler按照注册的先后顺序执行,ChannelOutboundHandler按照注册的先后顺序逆序执行。
     * HttpRequestDecoder、HttpObjectAggregator、HttpHandler为InboundHandler
     * HttpContentCompressor、HttpResponseEncoder为OutboundHandler
     * 在使用Handler的过程中,需要注意:
     * 1、ChannelInboundHandler之间的传递,通过调用 ctx.fireChannelRead(msg) 实现;调用ctx.write(msg) 将传递到ChannelOutboundHandler。
     * 2、ctx.write()方法执行后,需要调用flush()方法才能令它立即执行。
     * 3、ChannelOutboundHandler 在注册的时候需要放在最后一个ChannelInboundHandler之前,否则将无法传递到ChannelOutboundHandler。
     * 4、Handler的消费处理放在最后一个处理。
     */
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast("decoder", new HttpRequestDecoder());
    pipeline.addLast("aggregator", new HttpObjectAggregator(maxContentLength));
    pipeline.addLast("encoder", new HttpResponseEncoder());
    // 启用gzip(由于使用本地存储文件,不能启用gzip)
    //pipeline.addLast(new HttpContentCompressor(1));
    pipeline.addLast(new ChunkedWriteHandler());
    // 将HttpRequestHandler放在业务线程池中执行,避免阻塞worker线程。
    pipeline.addLast(eventExecutorGroup, "httpRequestHandler", new HttpRequestHandler());
}
 
Example #12
Source File: NonSslRedirectHandler.java    From qonduit with Apache License 2.0 6 votes vote down vote up
@Override
protected ChannelHandler newNonSslHandler(ChannelHandlerContext context) {
    return new ChannelInboundHandlerAdapter() {

        private HttpResponseEncoder encoder = new HttpResponseEncoder();

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            LOG.trace("Received non-SSL request, returning redirect");
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.MOVED_PERMANENTLY, Unpooled.EMPTY_BUFFER);
            response.headers().set(HttpHeaderNames.LOCATION, redirectAddress);
            LOG.trace(Constants.LOG_RETURNING_RESPONSE, response);
            encoder.write(ctx, response, ctx.voidPromise());
            ctx.flush();
        }
    };
}
 
Example #13
Source File: TestServer.java    From pampas with Apache License 2.0 6 votes vote down vote up
private ServerBootstrap serverBootstrap() {
        boot.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                                  @Override
                                  protected void initChannel(SocketChannel ch) throws Exception {
                                      ch.pipeline()
                                              .addLast("decoder", new HttpRequestDecoder())
                                              .addLast("http-aggregator", new HttpObjectAggregator(65536))
//                                              .addLast("encoder", new HttpResponseDecoder())
                                              .addLast("base-encoder", new HttpResponseEncoder())
                                              .addLast("chunk", new ChunkedWriteHandler())
                                              .addLast("handler", new TestHttpServerHandler());

                                  }
                              }
                );


        return boot;
    }
 
Example #14
Source File: HttpServer.java    From DistributedID with Apache License 2.0 6 votes vote down vote up
@Override
public void init() {
    super.init();
    b.group(bossGroup, workGroup)
            .channel(NioServerSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, false)
            .option(ChannelOption.TCP_NODELAY, true)
            .option(ChannelOption.SO_BACKLOG, 1024)
            .localAddress(new InetSocketAddress(port))
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(defLoopGroup,
                            new HttpRequestDecoder(),       //请求解码器
                            new HttpObjectAggregator(65536),//将多个消息转换成单一的消息对象
                            new HttpResponseEncoder(),      // 响应编码器
                            new HttpServerHandler(snowFlake)//自定义处理器
                    );
                }
            });

}
 
Example #15
Source File: HttpServerInitHandler.java    From util4j with Apache License 2.0 6 votes vote down vote up
@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline p = ch.pipeline();
		if(sslCtx!=null)
		{
			p.addLast(new SslHandler(sslCtx.newEngine(ch.alloc())));
		}
		p.addLast(new HttpResponseEncoder());//必须放在最前面,如果decoder途中需要回复消息,则decoder前面需要encoder
		p.addLast(new HttpRequestDecoder());
		p.addLast(new HttpObjectAggregator(65536));//限制contentLength
		//大文件传输处理
//		p.addLast(new ChunkedWriteHandler());
//		p.addLast(new HttpContentCompressor());
		//跨域配置
		CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin().allowCredentials().build();
		p.addLast(new CorsHandler(corsConfig));
		if(unPoolMsg)
		{
			p.addLast(new DefaultListenerHandler<HttpRequest>(new HttpListenerProxy(listener)));
		}else
		{
			p.addLast(new DefaultListenerHandler<HttpRequest>(listener));
		}
	}
 
Example #16
Source File: FrontFilter.java    From api-gateway-core with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    config.getChannelInboundHandlerList().forEach(pipeline::addLast);
    config.getChannelOutboundHandlerList().forEach(pipeline::addLast);
    pipeline.addLast(new HttpResponseEncoder());
    config.getHttpResponseHandlerList().forEach(pipeline::addLast);
    pipeline.addLast(new HttpRequestDecoder());
    pipeline.addLast(new ChunkedWriteHandler());
    pipeline.addLast(new HttpObjectAggregator(10 * 1024 * 1024));
    pipeline.addLast(new FrontHandler());
    pipeline.addLast(new ExceptionHandler());


    ch.closeFuture().addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            logger.debug("channel close");
        }
    });
}
 
Example #17
Source File: HttpUploadServerInitializer.java    From tools-journey with Apache License 2.0 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline pipeline = ch.pipeline();

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

    pipeline.addLast(new HttpRequestDecoder());
    pipeline.addLast(new HttpResponseEncoder());

    // Remove the following line if you don't want automatic content compression.
    pipeline.addLast(new HttpContentCompressor());

    pipeline.addLast(new HttpUploadServerHandler());
}
 
Example #18
Source File: HttpStaticFileServerInitializer.java    From codes-scratch-zookeeper-netty with Apache License 2.0 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch)
        throws Exception {
    // Create a default pipeline implementation.
    CorsConfig corsConfig = CorsConfig.withAnyOrigin().build();
    ChannelPipeline pipeline = ch.pipeline();
    // Uncomment the following line if you want HTTPS
    //SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine();
    //engine.setUseClientMode(false);
    //pipeline.addLast("ssl", new SslHandler(engine));

    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("decoder", new HttpRequestDecoder());
    pipeline.addLast("aggregator", new HttpObjectAggregator(8388608)); // 8MB
    //pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
    pipeline.addLast("cors", new CorsHandler(corsConfig));
    pipeline.addLast("handler", new HttpStaticFileServerHandler());
}
 
Example #19
Source File: HttpProtocolHandler.java    From hasor with Apache License 2.0 5 votes vote down vote up
@Override
public ChannelHandler[] channelHandler(Connector connector, AppContext appContext) {
    RsfContext rsfContext = appContext.getInstance(RsfContext.class);
    RsfDuplexHandler inHandler = new RsfDuplexHandler(  //
            new HttpRequestDecoder(),   //
            new HttpResponseEncoder()   //
    );
    return new ChannelHandler[] {       //
            inHandler,                  //
            new HttpCoder(rsfContext, connector, this.httpHandler)//
    };
}
 
Example #20
Source File: ProcessorHttpServer.java    From netty-reactive-streams with Apache License 2.0 5 votes vote down vote up
public ChannelFuture bind(SocketAddress address, final Callable<Processor<HttpRequest, HttpResponse>> handler) {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(eventLoop)
            .channel(NioServerSocketChannel.class)
            .childOption(ChannelOption.AUTO_READ, false)
            .localAddress(address)
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();

                    pipeline.addLast(
                            new HttpRequestDecoder(),
                            new HttpResponseEncoder()
                    ).addLast("serverStreamsHandler", new HttpStreamsServerHandler());

                    HandlerSubscriber<HttpResponse> subscriber = new HandlerSubscriber<>(ch.eventLoop(), 2, 4);
                    HandlerPublisher<HttpRequest> publisher = new HandlerPublisher<>(ch.eventLoop(), HttpRequest.class);

                    pipeline.addLast("serverSubscriber", subscriber);
                    pipeline.addLast("serverPublisher", publisher);

                    Processor<HttpRequest, HttpResponse> processor = handler.call();
                    processor.subscribe(subscriber);
                    publisher.subscribe(processor);
                }
            });

    return bootstrap.bind();
}
 
Example #21
Source File: PortUnificationServerHandler.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
private void switchToHttp(ChannelHandlerContext ctx) {
    ChannelPipeline p = ctx.pipeline();
    p.addLast("decoder", new HttpRequestDecoder());
    p.addLast("encoder", new HttpResponseEncoder());
    p.addLast("deflater", new HttpContentCompressor());
    p.addLast("handler", new HttpSnoopServerHandler());
    p.remove(this);
}
 
Example #22
Source File: Server.java    From qonduit with Apache License 2.0 5 votes vote down vote up
protected ChannelHandler setupHttpChannel(Configuration config, SslContext sslCtx) {

        return new ChannelInitializer<SocketChannel>() {

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

                ch.pipeline().addLast("ssl", new NonSslRedirectHandler(config, sslCtx));
                ch.pipeline().addLast("encoder", new HttpResponseEncoder());
                ch.pipeline().addLast("decoder", new HttpRequestDecoder());
                ch.pipeline().addLast("compressor", new HttpContentCompressor());
                ch.pipeline().addLast("decompressor", new HttpContentDecompressor());
                ch.pipeline().addLast("aggregator", new HttpObjectAggregator(8192));
                ch.pipeline().addLast("chunker", new ChunkedWriteHandler());
                final Configuration.Cors corsCfg = config.getHttp().getCors();
                final CorsConfigBuilder ccb;
                if (corsCfg.isAllowAnyOrigin()) {
                    ccb = CorsConfigBuilder.forAnyOrigin();
                } else {
                    ccb = CorsConfigBuilder.forOrigins(corsCfg.getAllowedOrigins().stream().toArray(String[]::new));
                }
                if (corsCfg.isAllowNullOrigin()) {
                    ccb.allowNullOrigin();
                }
                if (corsCfg.isAllowCredentials()) {
                    ccb.allowCredentials();
                }
                corsCfg.getAllowedMethods().stream().map(HttpMethod::valueOf).forEach(ccb::allowedRequestMethods);
                corsCfg.getAllowedHeaders().forEach(ccb::allowedRequestHeaders);
                CorsConfig cors = ccb.build();
                LOG.trace("Cors configuration: {}", cors);
                ch.pipeline().addLast("cors", new CorsHandler(cors));
                ch.pipeline().addLast("queryDecoder", new qonduit.netty.http.HttpRequestDecoder(config));
                ch.pipeline().addLast("strict", new StrictTransportHandler(config));
                ch.pipeline().addLast("login", new X509LoginRequestHandler(config));
                ch.pipeline().addLast("doLogin", new BasicAuthLoginRequestHandler(config));
                ch.pipeline().addLast("error", new HttpExceptionHandler());
            }
        };
    }
 
Example #23
Source File: SimpleHttpProxyHandler.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead0
  (final ChannelHandlerContext ctx, final HttpRequest req) {
  uri = req.getUri();
  final Channel client = ctx.channel();
  Bootstrap proxiedServer = new Bootstrap()
    .group(client.eventLoop())
    .channel(NioSocketChannel.class)
    .handler(new ChannelInitializer<SocketChannel>() {
      @Override
      protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();
        p.addLast(new HttpRequestEncoder(), new Forwarder(uri, client));
      }
    });
  ChannelFuture f = proxiedServer.connect(host);
  proxiedChannel = f.channel();
  f.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
      if (future.isSuccess()) {
        ctx.channel().pipeline().remove(HttpResponseEncoder.class);
        HttpRequest newReq = new DefaultFullHttpRequest(HTTP_1_1,
          req.getMethod(), req.getUri());
        newReq.headers().add(req.headers());
        newReq.headers().set(CONNECTION, Values.CLOSE);
        future.channel().writeAndFlush(newReq);
      } else {
        DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1,
          INTERNAL_SERVER_ERROR);
        resp.headers().set(CONNECTION, Values.CLOSE);
        LOG.info("Proxy " + uri + " failed. Cause: ", future.cause());
        ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
        client.close();
      }
    }
  });
}
 
Example #24
Source File: HttpSnoopServerInitializer.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #25
Source File: HttpCorsServerInitializer.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    CorsConfig corsConfig = CorsConfigBuilder.forAnyOrigin().allowNullOrigin().allowCredentials().build();
    ChannelPipeline pipeline = ch.pipeline();
    if (sslCtx != null) {
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    }
    pipeline.addLast(new HttpResponseEncoder());
    pipeline.addLast(new HttpRequestDecoder());
    pipeline.addLast(new HttpObjectAggregator(65536));
    pipeline.addLast(new ChunkedWriteHandler());
    pipeline.addLast(new CorsHandler(corsConfig));
    pipeline.addLast(new OkResponseHandler());
}
 
Example #26
Source File: HttpSnoopServerInitializer.java    From tools-journey with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #27
Source File: HttpCorsServerInitializer.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) {
    CorsConfig corsConfig = CorsConfig.withAnyOrigin().build();
    ChannelPipeline pipeline = ch.pipeline();
    if (sslCtx != null) {
        pipeline.addLast(sslCtx.newHandler(ch.alloc()));
    }
    pipeline.addLast(new HttpResponseEncoder());
    pipeline.addLast(new HttpRequestDecoder());
    pipeline.addLast(new HttpObjectAggregator(65536));
    pipeline.addLast(new ChunkedWriteHandler());
    pipeline.addLast(new CorsHandler(corsConfig));
    pipeline.addLast(new OkResponseHandler());
}
 
Example #28
Source File: SpdyOrHttpChooser.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
/**
 * Add all {@link ChannelHandler}'s that are needed for HTTP.
 */
protected void addHttpHandlers(ChannelHandlerContext ctx) {
    ChannelPipeline pipeline = ctx.pipeline();
    pipeline.addLast("httpRequestDecoder", new HttpRequestDecoder());
    pipeline.addLast("httpResponseEncoder", new HttpResponseEncoder());
    pipeline.addLast("httpChunkAggregator", new HttpObjectAggregator(maxHttpContentLength));
    pipeline.addLast("httpRequestHandler", createHttpRequestHandlerForHttp());
}
 
Example #29
Source File: AutobahnServerInitializer.java    From netty4.0.27Learn with Apache License 2.0 5 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();
    pipeline.addLast("encoder", new HttpResponseEncoder());
    pipeline.addLast("decoder", new HttpRequestDecoder());
    pipeline.addLast("handler", new AutobahnServerHandler());
}
 
Example #30
Source File: SimpleHttpProxyHandler.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead0
  (final ChannelHandlerContext ctx, final HttpRequest req) {
  uri = req.getUri();
  final Channel client = ctx.channel();
  Bootstrap proxiedServer = new Bootstrap()
    .group(client.eventLoop())
    .channel(NioSocketChannel.class)
    .handler(new ChannelInitializer<SocketChannel>() {
      @Override
      protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();
        p.addLast(new HttpRequestEncoder(), new Forwarder(uri, client));
      }
    });
  ChannelFuture f = proxiedServer.connect(host);
  proxiedChannel = f.channel();
  f.addListener(new ChannelFutureListener() {
    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
      if (future.isSuccess()) {
        ctx.channel().pipeline().remove(HttpResponseEncoder.class);
        HttpRequest newReq = new DefaultFullHttpRequest(HTTP_1_1,
          req.getMethod(), req.getUri());
        newReq.headers().add(req.headers());
        newReq.headers().set(CONNECTION, Values.CLOSE);
        future.channel().writeAndFlush(newReq);
      } else {
        DefaultHttpResponse resp = new DefaultHttpResponse(HTTP_1_1,
          INTERNAL_SERVER_ERROR);
        resp.headers().set(CONNECTION, Values.CLOSE);
        LOG.info("Proxy " + uri + " failed. Cause: ", future.cause());
        ctx.writeAndFlush(resp).addListener(ChannelFutureListener.CLOSE);
        client.close();
      }
    }
  });
}