Search in sources :

Example 76 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project apiRecord by tobecoder2015.

the class ApirecordApplication method main.

public static void main(String[] args) {
    SpringApplication.run(ApirecordApplication.class, args);
    System.setProperty("proxySet", "true");
    System.setProperty("http.proxyHost", "127.0.0.1");
    System.setProperty("http.proxyPort", "9999");
    log.info("本地代理服务器ip:" + System.getProperty("http.proxyHost"));
    log.info("本地代理服务器port:" + System.getProperty("http.proxyPort"));
    // 配置文件
    RecordQueue.getInstance().start();
    FilterChain.addFilter(new ContentTypeFilter(FilterService.contentType));
    FilterChain.addFilter(new UrlFilter(FilterService.urls));
    FilterChain.addFilter(new MethodFilter(FilterService.methods));
    FileService.setSavePath(null);
    new NettyHttpProxyServer().initProxyInterceptFactory(() -> new HttpProxyIntercept() {

        @Override
        public boolean beforeRequest(Channel clientChannel, HttpRequest httpRequest) {
            log.debug("request " + clientChannel.id().asShortText() + "   " + httpRequest.toString());
            Request request = TransferUtil.toRequest(httpRequest);
            Message message = new Message(clientChannel.id().asShortText(), Message.REQUEST_HEAD, request);
            FilterChain filterChain = FilterChain.getFilterChain();
            if (filterChain.doFilter(message, filterChain)) {
            // 
            } else {
                RecordQueue.getInstance().add(message);
            }
            return true;
        }

        @Override
        public boolean beforeRequest(Channel clientChannel, HttpContent httpContent) {
            log.debug("request httpContent:" + clientChannel.id().asShortText() + "   " + clientChannel.id().asShortText() + "  " + httpContent.content().toString(Charset.defaultCharset()));
            if (!RecordMap.containKey(clientChannel.id().asShortText()))
                return true;
            Message message = new Message(clientChannel.id().asShortText(), Message.REQUEST_BODY, httpContent.content().toString(io.netty.util.CharsetUtil.UTF_8));
            FilterChain filterChain = FilterChain.getFilterChain();
            if (filterChain.doFilter(message, filterChain)) {
            // 
            } else {
                RecordQueue.getInstance().add(message);
            }
            return true;
        }

        @Override
        public boolean afterResponse(Channel clientChannel, Channel proxyChannel, HttpResponse httpResponse) {
            log.debug("httpResponse:" + clientChannel.id().asShortText() + "  " + httpResponse.toString());
            if (!RecordMap.containKey(clientChannel.id().asShortText()))
                return true;
            Response response = TransferUtil.toReponse(httpResponse);
            Message message = new Message(clientChannel.id().asShortText(), Message.RESPONSE_HEAD, response);
            FilterChain filterChain = FilterChain.getFilterChain();
            if (filterChain.doFilter(message, filterChain)) {
                message.setFilter(true);
                RecordQueue.getInstance().add(message);
            } else {
                RecordQueue.getInstance().add(message);
            }
            return true;
        }

        @Override
        public boolean afterResponse(Channel clientChannel, Channel proxyChannel, HttpContent httpContent) {
            log.debug("httpContent:" + clientChannel.id().asShortText() + "  " + httpContent.content().toString(Charset.defaultCharset()));
            if (!RecordMap.containKey(clientChannel.id().asShortText()))
                return true;
            ByteBuf buf = httpContent.content().copy();
            byte[] bytes = new byte[buf.readableBytes()];
            buf.readBytes(bytes);
            Message message = new Message(clientChannel.id().asShortText(), Message.RESPONSE_BODY, bytes);
            buf.writeBytes(bytes);
            if (httpContent instanceof LastHttpContent)
                message.setFinish(true);
            FilterChain filterChain = FilterChain.getFilterChain();
            if (filterChain.doFilter(message, filterChain)) {
            // 
            } else {
                RecordQueue.getInstance().add(message);
            }
            return true;
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            ctx.fireExceptionCaught(cause);
        // log.error("异常",cause);
        }
    }).start(9999);
}
Also used : Message(com.wing.apirecord.core.record.Message) MethodFilter(com.wing.apirecord.core.filter.MethodFilter) Channel(io.netty.channel.Channel) FilterChain(com.wing.apirecord.core.filter.FilterChain) Request(com.wing.apirecord.core.model.Request) UrlFilter(com.wing.apirecord.core.filter.UrlFilter) HttpProxyIntercept(com.wing.apirecord.core.intercept.HttpProxyIntercept) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) ContentTypeFilter(com.wing.apirecord.core.filter.ContentTypeFilter) NettyHttpProxyServer(com.wing.apirecord.core.NettyHttpProxyServer) Response(com.wing.apirecord.core.model.Response)

Example 77 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project jackrabbit-oak by apache.

the class ForwardHandler method channelActive.

@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    group = new NioEventLoopGroup(0, r -> {
        return new Thread(r, String.format("forward-handler-%d", threadNumber.getAndIncrement()));
    });
    Bootstrap b = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            if (flipPosition >= 0) {
                ch.pipeline().addLast(new FlipHandler(flipPosition));
            }
            if (skipBytes > 0) {
                ch.pipeline().addLast(new SkipHandler(skipPosition, skipBytes));
            }
            ch.pipeline().addLast(new BackwardHandler(ctx.channel()));
        }
    });
    remote = b.connect(targetHost, targetPort).sync().channel();
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) EventLoopGroup(io.netty.channel.EventLoopGroup) Logger(org.slf4j.Logger) ChannelInitializer(io.netty.channel.ChannelInitializer) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) LoggerFactory(org.slf4j.LoggerFactory) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) TimeUnit(java.util.concurrent.TimeUnit) Channel(io.netty.channel.Channel) Bootstrap(io.netty.bootstrap.Bootstrap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Example 78 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project jocean-http by isdom.

the class ChannelTestCase method testChannelInactiveForInactiveChannel.

@Test
public final void testChannelInactiveForInactiveChannel() throws InterruptedException {
    final EmbeddedChannel channel = new EmbeddedChannel();
    channel.disconnect().syncUninterruptibly();
    assertTrue(!channel.isActive());
    final AtomicBoolean isInactiveCalled = new AtomicBoolean(false);
    channel.pipeline().addLast(new ChannelInboundHandlerAdapter() {

        @Override
        public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
            isInactiveCalled.set(true);
        }
    });
    Thread.currentThread().sleep(1000);
    assertFalse(isInactiveCalled.get());
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) EmbeddedChannel(io.netty.channel.embedded.EmbeddedChannel) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Example 79 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project ratpack by ratpack.

the class ContentAggregatingRequestAction method addResponseHandlers.

@Override
protected void addResponseHandlers(ChannelPipeline p, Downstream<? super ReceivedResponse> downstream) {
    p.addLast(AGGREGATOR_HANDLER_NAME, new NoContentLengthOnNoBodyHttpObjectAggregator(requestConfig.maxContentLength));
    p.addLast(RESPONSE_HANDLER_NAME, new SimpleChannelInboundHandler<FullHttpResponse>(false) {

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse response) throws Exception {
            response.touch();
            dispose(ctx.pipeline(), response);
            ByteBuf content = new ByteBufRef(response.content());
            execution.onComplete(() -> {
                if (content.refCnt() > 0) {
                    content.release();
                }
            });
            success(downstream, toReceivedResponse(response, content));
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause = decorateException(cause);
            error(downstream, cause);
            forceDispose(ctx.pipeline());
        }
    });
}
Also used : FullHttpResponse(io.netty.handler.codec.http.FullHttpResponse) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) ByteBufRef(ratpack.bytebuf.ByteBufRef)

Example 80 with ChannelHandlerContext

use of org.apache.flink.shaded.netty4.io.netty.channel.ChannelHandlerContext in project cdap by caskdata.

the class NettyRouterPipelineTest method testHttpPipelining.

@Test
public void testHttpPipelining() throws Exception {
    final BlockingQueue<HttpResponseStatus> responseStatuses = new LinkedBlockingQueue<>();
    EventLoopGroup eventGroup = new NioEventLoopGroup();
    Bootstrap bootstrap = new Bootstrap().channel(NioSocketChannel.class).group(eventGroup).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast("codec", new HttpClientCodec());
            pipeline.addLast("aggregator", new HttpObjectAggregator(1048576));
            pipeline.addLast("handler", new ChannelInboundHandlerAdapter() {

                @Override
                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                    if (msg instanceof HttpResponse) {
                        responseStatuses.add(((HttpResponse) msg).status());
                    }
                    ReferenceCountUtil.release(msg);
                }
            });
        }
    });
    // Create a connection and make five consecutive HTTP call without waiting for the first to respond
    Channel channel = bootstrap.connect(HOSTNAME, ROUTER.getServiceMap().get(GATEWAY_NAME)).sync().channel();
    for (int i = 0; i < 5; i++) {
        HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/v1/sleep?sleepMillis=3000");
        request.headers().set(HttpHeaderNames.HOST, HOSTNAME);
        channel.writeAndFlush(request);
    }
    // Should get the first response as normal one
    HttpResponseStatus status = responseStatuses.poll(5, TimeUnit.SECONDS);
    Assert.assertEquals(HttpResponseStatus.OK, status);
    // The rest four should be failure responses
    for (int i = 0; i < 4; i++) {
        Assert.assertEquals(HttpResponseStatus.NOT_IMPLEMENTED, responseStatuses.poll(1, TimeUnit.SECONDS));
    }
    eventGroup.shutdownGracefully();
    channel.close();
    Assert.assertTrue(responseStatuses.isEmpty());
}
Also used : DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpRequest(io.netty.handler.codec.http.HttpRequest) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) DefaultFullHttpRequest(io.netty.handler.codec.http.DefaultFullHttpRequest) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) SocketChannel(io.netty.channel.socket.SocketChannel) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) Channel(io.netty.channel.Channel) HttpResponse(io.netty.handler.codec.http.HttpResponse) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) HttpClientCodec(io.netty.handler.codec.http.HttpClientCodec) IOException(java.io.IOException) ChannelPipeline(io.netty.channel.ChannelPipeline) HttpObjectAggregator(io.netty.handler.codec.http.HttpObjectAggregator) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) EventLoopGroup(io.netty.channel.EventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.Test)

Aggregations

ChannelHandlerContext (io.netty.channel.ChannelHandlerContext)661 Channel (io.netty.channel.Channel)274 ByteBuf (io.netty.buffer.ByteBuf)234 ChannelFuture (io.netty.channel.ChannelFuture)210 Test (org.junit.Test)208 ChannelInboundHandlerAdapter (io.netty.channel.ChannelInboundHandlerAdapter)201 Bootstrap (io.netty.bootstrap.Bootstrap)177 InetSocketAddress (java.net.InetSocketAddress)160 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)156 EmbeddedChannel (io.netty.channel.embedded.EmbeddedChannel)154 Test (org.junit.jupiter.api.Test)153 ChannelPipeline (io.netty.channel.ChannelPipeline)151 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)141 AtomicReference (java.util.concurrent.atomic.AtomicReference)140 IOException (java.io.IOException)137 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)120 ClosedChannelException (java.nio.channels.ClosedChannelException)119 CountDownLatch (java.util.concurrent.CountDownLatch)115 ArrayList (java.util.ArrayList)113 List (java.util.List)111