io.netty.handler.codec.LineBasedFrameDecoder Java Examples

The following examples show how to use io.netty.handler.codec.LineBasedFrameDecoder. 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: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addByteEncoderWhenFullReactorPipeline() {

	channel.pipeline()
	       .addLast(NettyPipeline.HttpCodec, new HttpServerCodec())
	       .addLast(NettyPipeline.HttpTrafficHandler, new ChannelDuplexHandler())
	       .addLast(NettyPipeline.ReactiveBridge, new ChannelHandlerAdapter() {
	       });
	ChannelHandler encoder = new LineBasedFrameDecoder(12);

	testContext.addHandlerFirst("encoder", encoder);

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList(NettyPipeline.HttpCodec,
					NettyPipeline.HttpTrafficHandler,
					"encoder",
					NettyPipeline.ReactiveBridge,
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #2
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addByteEncoderWhenNoRight() {

	channel.pipeline()
	       .addLast(NettyPipeline.HttpCodec, new ChannelHandlerAdapter() {
	       });
	ChannelHandler encoder = new LineBasedFrameDecoder(12);

	testContext.addHandlerFirst("encoder", encoder);

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList(NettyPipeline.HttpCodec,
					"encoder",
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #3
Source File: RxtxClient.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new OioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(RxtxChannel.class)
         .handler(new ChannelInitializer<RxtxChannel>() {
             @Override
             public void initChannel(RxtxChannel ch) throws Exception {
                 ch.pipeline().addLast(
                     new LineBasedFrameDecoder(32768),
                     new StringEncoder(),
                     new StringDecoder(),
                     new RxtxClientHandler()
                 );
             }
         });

        ChannelFuture f = b.connect(new RxtxDeviceAddress(PORT)).sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #4
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addByteEncoderWhenNoLeft() {

	channel.pipeline()
	       .addLast(NettyPipeline.ReactiveBridge, new ChannelHandlerAdapter() {
	       });
	ChannelHandler encoder = new LineBasedFrameDecoder(12);

	testContext.addHandlerFirst("encoder", encoder);

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList("encoder",
					NettyPipeline.ReactiveBridge,
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #5
Source File: RxtxClient.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new OioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(RxtxChannel.class)
         .handler(new ChannelInitializer<RxtxChannel>() {
             @Override
             public void initChannel(RxtxChannel ch) throws Exception {
                 ch.pipeline().addLast(
                     new LineBasedFrameDecoder(32768),
                     new StringEncoder(),
                     new StringDecoder(),
                     new RxtxClientHandler()
                 );
             }
         });

        ChannelFuture f = b.connect(new RxtxDeviceAddress(PORT)).sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example #6
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addSeveralByteEncodersWhenCodec() {
	ChannelHandler encoder1 = new LineBasedFrameDecoder(12);
	ChannelHandler encoder2 = new LineBasedFrameDecoder(13);

	channel.pipeline()
	       .addLast(NettyPipeline.HttpCodec, new HttpServerCodec())
	       .addLast(NettyPipeline.HttpTrafficHandler, new ChannelDuplexHandler())
	       .addLast(NettyPipeline.ReactiveBridge, new ChannelHandlerAdapter() {
	       });

	testContext.addHandlerFirst("encoder1", encoder1)
	           .addHandlerFirst("encoder2", encoder2);

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList(NettyPipeline.HttpCodec,
					NettyPipeline.HttpTrafficHandler,
					"encoder2",
					"encoder1",
					NettyPipeline.ReactiveBridge,
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #7
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addByteDecoderWhenFullReactorPipeline() {

	channel.pipeline()
	       .addLast(NettyPipeline.HttpCodec, new HttpServerCodec())
	       .addLast(NettyPipeline.HttpTrafficHandler, new ChannelDuplexHandler())
	       .addLast(NettyPipeline.ReactiveBridge, new ChannelHandlerAdapter() {
	       });
	ChannelHandler decoder = new LineBasedFrameDecoder(12);

	testContext.addHandlerLast("decoder", decoder)
	           .addHandlerFirst("decoder$extract",
			           NettyPipeline.inboundHandler(ADD_EXTRACTOR));

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList(NettyPipeline.HttpCodec,
					NettyPipeline.HttpTrafficHandler,
					"decoder$extract",
					"decoder",
					NettyPipeline.ReactiveBridge,
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #8
Source File: WhoisProtocolModule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Provides
@WhoisProtocol
static ImmutableList<Provider<? extends ChannelHandler>> provideHandlerProviders(
    Provider<ProxyProtocolHandler> proxyProtocolHandlerProvider,
    @WhoisProtocol Provider<ReadTimeoutHandler> readTimeoutHandlerProvider,
    Provider<LineBasedFrameDecoder> lineBasedFrameDecoderProvider,
    Provider<WhoisServiceHandler> whoisServiceHandlerProvider,
    Provider<FrontendMetricsHandler> frontendMetricsHandlerProvider,
    Provider<WhoisQuotaHandler> whoisQuotaHandlerProvider,
    Provider<FullHttpRequestRelayHandler> relayHandlerProvider) {
  return ImmutableList.of(
      proxyProtocolHandlerProvider,
      readTimeoutHandlerProvider,
      lineBasedFrameDecoderProvider,
      whoisServiceHandlerProvider,
      frontendMetricsHandlerProvider,
      whoisQuotaHandlerProvider,
      relayHandlerProvider);
}
 
Example #9
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
public void addByteDecoderWhenNoRight() {

	channel.pipeline()
	       .addLast(NettyPipeline.HttpCodec, new ChannelHandlerAdapter() {
	       });
	ChannelHandler decoder = new LineBasedFrameDecoder(12);

	testContext.addHandlerLast("decoder", decoder)
	           .addHandlerFirst("decoder$extract",
			           NettyPipeline.inboundHandler(ADD_EXTRACTOR));

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList(NettyPipeline.HttpCodec,
					"decoder$extract",
					"decoder",
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #10
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 6 votes vote down vote up
@Test
	public void tcpClientHandlesLineFeedDataFixedPool() throws InterruptedException {
		Consumer<? super Connection> channelInit = c -> c
				.addHandler("codec",
				            new LineBasedFrameDecoder(8 * 1024));

//		ConnectionProvider p = ConnectionProvider.fixed
//				("tcpClientHandlesLineFeedDataFixedPool", 1);

		ConnectionProvider p = ConnectionProvider.newConnection();

		tcpClientHandlesLineFeedData(
				TcpClient.create(p)
				         .host("localhost")
				         .port(echoServerPort)
				         .doOnConnected(channelInit)
		);

	}
 
Example #11
Source File: HttpServerTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void flushOnComplete() {

	Flux<String> flux = Flux.range(0, 100)
	                        .map(n -> String.format("%010d", n));
	List<String> test =
			flux.collectList()
			    .block();
	assertThat(test).isNotNull();

	disposableServer = HttpServer.create()
	                             .port(0)
	                             .handle((req, resp) -> resp.sendString(flux.map(s -> s + "\n")))
	                             .wiretap(true)
	                             .bindNow();

	Flux<String> client = HttpClient.create()
	                                .port(disposableServer.port())
	                                .wiretap(true)
	                                .doOnConnected(res ->
	                                        res.addHandler(new LineBasedFrameDecoder(10)))
	                                .get()
	                                .uri("/")
	                                .responseContent()
	                                .asString();

	StepVerifier.create(client)
	            .expectNextSequence(test)
	            .expectComplete()
	            .verify(Duration.ofSeconds(30));
}
 
Example #12
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void addDecoderSkipsIfExist() {
	channel.pipeline()
	       .addFirst("foo", new Utf8FrameValidator());

	testContext.addHandlerFirst("foo", new LineBasedFrameDecoder(10));

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList("foo", "DefaultChannelPipeline$TailContext#0"));
	MatcherAssert.assertThat(channel.pipeline()
	                  .get("foo"), is(instanceOf(Utf8FrameValidator.class)));
}
 
Example #13
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void addEncoderSkipsIfExist() {
	channel.pipeline()
	       .addFirst("foo", new Utf8FrameValidator());

	testContext.addHandlerFirst("foo", new LineBasedFrameDecoder(10));

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList("foo", "DefaultChannelPipeline$TailContext#0"));
	MatcherAssert.assertThat(channel.pipeline()
	                  .get("foo"), is(instanceOf(Utf8FrameValidator.class)));
}
 
Example #14
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void tcpClientHandlesLineFeedData() throws InterruptedException {
	final int messages = 100;
	final CountDownLatch latch = new CountDownLatch(messages);
	final List<String> strings = new ArrayList<>();

	Connection client =
			TcpClient.create()
			         .host("localhost")
			         .port(echoServerPort)
			         .doOnConnected(c -> c.addHandlerLast("codec",
					                                 new LineBasedFrameDecoder(8 * 1024)))
			         .handle((in, out) ->
				        out.sendString(Flux.range(1, messages)
				                            .map(i -> "Hello World!" + i + "\n")
				                            .subscribeOn(Schedulers.parallel()))
				            .then( in.receive()
				                     .asString()
				                     .take(100)
				                     .flatMapIterable(s -> Arrays.asList(s.split("\\n")))
				                     .doOnNext(s -> {
					                     strings.add(s);
					                     latch.countDown();
				                     }).then())
			         )
			         .wiretap(true)
			         .connectNow(Duration.ofSeconds(15));

	assertTrue("Expected messages not received. Received " + strings.size() + " messages: " + strings,
			latch.await(15, TimeUnit.SECONDS));

	assertEquals(messages, strings.size());
	client.disposeNow();
}
 
Example #15
Source File: TcpClientTests.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void tcpClientHandlesLineFeedDataElasticPool() throws InterruptedException {
	Consumer<? super Connection> channelInit = c -> c
			.addHandler("codec",
			            new LineBasedFrameDecoder(8 * 1024));

	tcpClientHandlesLineFeedData(
			TcpClient.create(ConnectionProvider.create("tcpClientHandlesLineFeedDataElasticPool", Integer.MAX_VALUE))
			         .host("localhost")
			         .port(echoServerPort)
			         .doOnConnected(channelInit)
	);
}
 
Example #16
Source File: SimpleServer.java    From ext-opensource-netty with Mozilla Public License 2.0 5 votes vote down vote up
@Override
  protected void initSocketChannel(SocketChannel ch) {
super.initSocketChannel(ch);
ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
ch.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")));
ch.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8")));
ch.pipeline().addLast(new LogDispatchHandler());
ch.pipeline().addLast(new SimpleServerHandler());
  }
 
Example #17
Source File: LineBasedServer.java    From netty-learning with Apache License 2.0 5 votes vote down vote up
public void bind(int port) throws Exception {

		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap b = new ServerBootstrap();
			b.group(bossGroup, workerGroup)
			.channel(NioServerSocketChannel.class)
			.option(ChannelOption.SO_BACKLOG, 1024)
			.childHandler(new ChannelInitializer<SocketChannel>() {
				@Override
				public void initChannel(SocketChannel ch) throws Exception {

					ChannelPipeline p = ch.pipeline();
					p.addLast(new LineBasedFrameDecoder(1024));
					p.addLast(new StringDecoder());
					p.addLast(new StringEncoder());

					p.addLast(new LineServerHandler());
				}
			});

			// Bind and start to accept incoming connections.
			ChannelFuture f = b.bind(port).sync(); // (7)

			logger.info("server bind port:{}", port);

			// Wait until the server socket is closed.
			f.channel().closeFuture().sync();

		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
 
Example #18
Source File: LineBasedClient.java    From netty-learning with Apache License 2.0 5 votes vote down vote up
public void connect(String host, int port) throws InterruptedException {

		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap b = new Bootstrap();
			b.group(group)
			.channel(NioSocketChannel.class)
			.option(ChannelOption.TCP_NODELAY, true)
			.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel ch) throws Exception {

					ChannelPipeline p = ch.pipeline();
					p.addLast(new LineBasedFrameDecoder(1024));
					p.addLast(new StringDecoder());
					p.addLast(new StringEncoder());

					p.addLast(new LineClientHandler());
				}
			});

			ChannelFuture future = b.connect(Constants.HOST, Constants.PORT).sync();

			future.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully();
		}
	}
 
Example #19
Source File: CarbonLineServer.java    From ffwd with Apache License 2.0 5 votes vote down vote up
@Override
public ChannelInitializer<Channel> initializer() {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(final Channel ch) throws Exception {
            ch.pipeline().addLast(new LineBasedFrameDecoder(MAX_LINE));
            ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
            ch.pipeline().addLast(decoder, handler);
        }
    };
}
 
Example #20
Source File: JsonLineProtocolServer.java    From ffwd with Apache License 2.0 5 votes vote down vote up
@Override
public final ChannelInitializer<Channel> initializer() {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(new LineBasedFrameDecoder(MAX_LINE));
            ch.pipeline().addLast(decoder, handler);
        }
    };
}
 
Example #21
Source File: CodecSample.java    From reactive-ipc-jvm with Apache License 2.0 5 votes vote down vote up
private static void runLineBasedFrameDecoder() {

        TcpServer<String, String> transport = Netty4TcpServer.<String, String>create(
                0,
                new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        int bufferSize = 1;
                        ChannelConfig config = channel.config();
                        config.setOption(ChannelOption.SO_RCVBUF, bufferSize);
                        config.setOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(bufferSize));
                        channel.pipeline().addFirst(
                                new LineBasedFrameDecoder(256),
                                new StringDecoder(CharsetUtil.UTF_8),
                                new StringEncoder(CharsetUtil.UTF_8));
                    }
                });

        ReactorTcpServer.create(transport).start(connection -> {
            connection.log("input")
                    .observeComplete(v -> LOG.info("Connection input complete"))
                    .capacity(1)
                    .consume(line -> {
                        String response = "Hello " + line + "\n";
                        Streams.wrap(connection.writeWith(Streams.just(response))).consume();
                    });
            return Streams.never();
        });
    }
 
Example #22
Source File: InitializerPipeline.java    From High-concurrent-server with Apache License 2.0 5 votes vote down vote up
@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		//使用Netty实现的线程池
//        DefaultEventExecutorGroup e1=new DefaultEventExecutorGroup(16);
		ChannelPipeline pipeline = ch.pipeline();
//		pipeline.addLast("decoder", new MessageDecoder());
		pipeline.addLast("decoder", new LineBasedFrameDecoder(2048));
		pipeline.addLast(new StringDecoder());
        pipeline.addLast("encoder", new MessageEncoder());
		pipeline.addLast("handler", new CommonHandler());
	}
 
Example #23
Source File: ServerWithNettyHandlers.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void run() throws Exception {
    EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    try {
        ServerBootstrap b = new ServerBootstrap(); // (2)
        b.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class) // (3)
                .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LineBasedFrameDecoder(1000));
                        ch.pipeline().addLast(new LineEncoder(Charset.defaultCharset()));
                        ch.pipeline().addLast(new StringDecoder(Charset.defaultCharset()));
                        ch.pipeline().addLast(serverHandler);

                    }
                })
                .option(ChannelOption.SO_BACKLOG, 128)          // (5)
                .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

        // Bind and start to accept incoming connections.
        ChannelFuture f = b.bind(port).sync(); // (7)

        // Wait until the server socket is closed.
        // In this example, this does not happen, but you can do that to gracefully
        // shut down your server.
        f.channel().closeFuture().sync();
    } finally {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }
}
 
Example #24
Source File: ConnectionTest.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Test
public void addSeveralByteDecodersWhenCodec() {
	ChannelHandler decoder1 = new LineBasedFrameDecoder(12);
	ChannelHandler decoder2 = new LineBasedFrameDecoder(13);

	channel.pipeline()
	       .addLast(NettyPipeline.HttpCodec, new HttpServerCodec())
	       .addLast(NettyPipeline.HttpTrafficHandler, new ChannelDuplexHandler())
	       .addLast(NettyPipeline.ReactiveBridge, new ChannelHandlerAdapter() {
	       });

	testContext.addHandlerLast("decoder1$extract",
			NettyPipeline.inboundHandler(ADD_EXTRACTOR))
	           .addHandlerLast("decoder1", decoder1)

	           .addHandlerLast("decoder2$extract",
			           NettyPipeline.inboundHandler(ADD_EXTRACTOR))
	           .addHandlerLast("decoder2", decoder2);

	assertEquals(channel.pipeline()
	                    .names(),
			Arrays.asList(NettyPipeline.HttpCodec,
					NettyPipeline.HttpTrafficHandler,
					"decoder1$extract",
					"decoder1",
					"decoder2$extract",
					"decoder2",
					NettyPipeline.ReactiveBridge,
					"DefaultChannelPipeline$TailContext#0"));
}
 
Example #25
Source File: QosProcessHandler.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() < 1) {
        return;
    }

    // read one byte to guess protocol
    final int magic = in.getByte(in.readerIndex());

    ChannelPipeline p = ctx.pipeline();
    p.addLast(new LocalHostPermitHandler(acceptForeignIp));
    if (isHttp(magic)) {
        // no welcome output for http protocol
        if (welcomeFuture != null && welcomeFuture.isCancellable()) {
            welcomeFuture.cancel(false);
        }
        p.addLast(new HttpServerCodec());
        p.addLast(new HttpObjectAggregator(1048576));
        p.addLast(new HttpProcessHandler());
        p.remove(this);
    } else {
        p.addLast(new LineBasedFrameDecoder(2048));
        p.addLast(new StringDecoder(CharsetUtil.UTF_8));
        p.addLast(new StringEncoder(CharsetUtil.UTF_8));
        p.addLast(new IdleStateHandler(0, 0, 5 * 60));
        p.addLast(new TelnetProcessHandler());
        p.remove(this);
    }
}
 
Example #26
Source File: SimpleClient.java    From ext-opensource-netty with Mozilla Public License 2.0 5 votes vote down vote up
@Override
protected void initSocketChannel(SocketChannel ch) {
	super.initSocketChannel(ch);
	ch.pipeline().addLast(new LineBasedFrameDecoder(1024)); 
	ch.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")));
	ch.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8")));
	///ch.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, Delimiters.lineDelimiter()));

	ch.pipeline().addLast(new LogDispatchHandler());
	ch.pipeline().addLast(new ClientSimpleHandler());
	///ch.pipeline().addLast(new ClientSimpleHandlerX());
}
 
Example #27
Source File: ProxyHandlerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void test() throws Exception {
    final SuccessTestHandler testHandler = new SuccessTestHandler();
    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.AUTO_READ, ThreadLocalRandom.current().nextBoolean());
    b.resolver(NoopAddressResolverGroup.INSTANCE);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(clientHandlers);
            p.addLast(new LineBasedFrameDecoder(64));
            p.addLast(testHandler);
        }
    });

    boolean finished = b.connect(destination).channel().closeFuture().await(10, TimeUnit.SECONDS);

    logger.debug("Received messages: {}", testHandler.received);

    if (testHandler.exceptions.isEmpty()) {
        logger.debug("No recorded exceptions on the client side.");
    } else {
        for (Throwable t : testHandler.exceptions) {
            logger.debug("Recorded exception on the client side: {}", t);
        }
    }

    assertProxyHandlers(true);

    assertThat(testHandler.received.toArray(), is(new Object[] { "0", "1", "2", "3" }));
    assertThat(testHandler.exceptions.toArray(), is(EmptyArrays.EMPTY_OBJECTS));
    assertThat(testHandler.eventCount, is(expectedEventCount));
    assertThat(finished, is(true));
}
 
Example #28
Source File: ProxyHandlerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void test() throws Exception {
    final FailureTestHandler testHandler = new FailureTestHandler();
    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(NioSocketChannel.class);
    b.resolver(NoopAddressResolverGroup.INSTANCE);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(clientHandlers);
            p.addLast(new LineBasedFrameDecoder(64));
            p.addLast(testHandler);
        }
    });

    boolean finished = b.connect(destination).channel().closeFuture().await(10, TimeUnit.SECONDS);
    finished &= testHandler.latch.await(10, TimeUnit.SECONDS);

    logger.debug("Recorded exceptions: {}", testHandler.exceptions);

    assertProxyHandlers(false);

    assertThat(testHandler.exceptions.size(), is(1));
    Throwable e = testHandler.exceptions.poll();
    assertThat(e, is(instanceOf(ProxyConnectException.class)));
    assertThat(String.valueOf(e), containsString(expectedMessage));
    assertThat(finished, is(true));
}
 
Example #29
Source File: ProxyHandlerTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void test() throws Exception {
    final long TIMEOUT = 2000;
    for (ChannelHandler h: clientHandlers) {
        if (h instanceof ProxyHandler) {
            ((ProxyHandler) h).setConnectTimeoutMillis(TIMEOUT);
        }
    }

    final FailureTestHandler testHandler = new FailureTestHandler();
    Bootstrap b = new Bootstrap();
    b.group(group);
    b.channel(NioSocketChannel.class);
    b.resolver(NoopAddressResolverGroup.INSTANCE);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            p.addLast(clientHandlers);
            p.addLast(new LineBasedFrameDecoder(64));
            p.addLast(testHandler);
        }
    });

    ChannelFuture cf = b.connect(DESTINATION).channel().closeFuture();
    boolean finished = cf.await(TIMEOUT * 2, TimeUnit.MILLISECONDS);
    finished &= testHandler.latch.await(TIMEOUT * 2, TimeUnit.MILLISECONDS);

    logger.debug("Recorded exceptions: {}", testHandler.exceptions);

    assertProxyHandlers(false);

    assertThat(testHandler.exceptions.size(), is(1));
    Throwable e = testHandler.exceptions.poll();
    assertThat(e, is(instanceOf(ProxyConnectException.class)));
    assertThat(String.valueOf(e), containsString("timeout"));
    assertThat(finished, is(true));
}
 
Example #30
Source File: HttpProxyServer.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private boolean authenticate(ChannelHandlerContext ctx, FullHttpRequest req) {
    assertThat(req.method(), is(HttpMethod.CONNECT));

    if (testMode != TestMode.INTERMEDIARY) {
        ctx.pipeline().addBefore(ctx.name(), "lineDecoder", new LineBasedFrameDecoder(64, false, true));
    }

    ctx.pipeline().remove(HttpObjectAggregator.class);
    ctx.pipeline().get(HttpServerCodec.class).removeInboundHandler();

    boolean authzSuccess = false;
    if (username != null) {
        CharSequence authz = req.headers().get(HttpHeaderNames.PROXY_AUTHORIZATION);
        if (authz != null) {
            String[] authzParts = authz.toString().split(" ", 2);
            ByteBuf authzBuf64 = Unpooled.copiedBuffer(authzParts[1], CharsetUtil.US_ASCII);
            ByteBuf authzBuf = Base64.decode(authzBuf64);

            String expectedAuthz = username + ':' + password;
            authzSuccess = "Basic".equals(authzParts[0]) &&
                           expectedAuthz.equals(authzBuf.toString(CharsetUtil.US_ASCII));

            authzBuf64.release();
            authzBuf.release();
        }
    } else {
        authzSuccess = true;
    }

    return authzSuccess;
}