use of org.apache.flink.shaded.netty4.io.netty.channel.SimpleChannelInboundHandler in project netty by netty.
the class SslHandlerTest method writingReadOnlyBufferDoesNotBreakAggregation.
@Test
public void writingReadOnlyBufferDoesNotBreakAggregation() throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate();
final SslContext sslServerCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
final SslContext sslClientCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
EventLoopGroup group = new NioEventLoopGroup();
Channel sc = null;
Channel cc = null;
final CountDownLatch serverReceiveLatch = new CountDownLatch(1);
try {
final int expectedBytes = 11;
sc = new ServerBootstrap().group(group).channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(sslServerCtx.newHandler(ch.alloc()));
ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {
private int readBytes;
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
readBytes += msg.readableBytes();
if (readBytes >= expectedBytes) {
serverReceiveLatch.countDown();
}
}
});
}
}).bind(new InetSocketAddress(0)).syncUninterruptibly().channel();
cc = new Bootstrap().group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(sslClientCtx.newHandler(ch.alloc()));
}
}).connect(sc.localAddress()).syncUninterruptibly().channel();
// We first write a ReadOnlyBuffer because SslHandler will attempt to take the first buffer and append to it
// until there is no room, or the aggregation size threshold is exceeded. We want to verify that we don't
// throw when a ReadOnlyBuffer is used and just verify that we don't aggregate in this case.
ByteBuf firstBuffer = Unpooled.buffer(10);
firstBuffer.writeByte(0);
firstBuffer = firstBuffer.asReadOnly();
ByteBuf secondBuffer = Unpooled.buffer(10);
secondBuffer.writeZero(secondBuffer.capacity());
cc.write(firstBuffer);
cc.writeAndFlush(secondBuffer).syncUninterruptibly();
serverReceiveLatch.countDown();
} finally {
if (cc != null) {
cc.close().syncUninterruptibly();
}
if (sc != null) {
sc.close().syncUninterruptibly();
}
group.shutdownGracefully();
ReferenceCountUtil.release(sslServerCtx);
ReferenceCountUtil.release(sslClientCtx);
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.SimpleChannelInboundHandler in project netty by netty.
the class HttpClientCodecTest method testServerCloseSocketInputProvidesData.
@Test
public void testServerCloseSocketInputProvidesData() throws InterruptedException {
ServerBootstrap sb = new ServerBootstrap();
Bootstrap cb = new Bootstrap();
final CountDownLatch serverChannelLatch = new CountDownLatch(1);
final CountDownLatch responseReceivedLatch = new CountDownLatch(1);
try {
sb.group(new NioEventLoopGroup(2));
sb.channel(NioServerSocketChannel.class);
sb.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
// Don't use the HttpServerCodec, because we don't want to have content-length or anything added.
ch.pipeline().addLast(new HttpRequestDecoder(4096, 8192, 8192, true));
ch.pipeline().addLast(new HttpObjectAggregator(4096));
ch.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpRequest>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) {
// This is just a simple demo...don't block in IO
assertTrue(ctx.channel() instanceof SocketChannel);
final SocketChannel sChannel = (SocketChannel) ctx.channel();
/**
* The point of this test is to not add any content-length or content-encoding headers
* and the client should still handle this.
* See <a href="https://tools.ietf.org/html/rfc7230#section-3.3.3">RFC 7230, 3.3.3</a>.
*/
sChannel.writeAndFlush(Unpooled.wrappedBuffer(("HTTP/1.0 200 OK\r\n" + "Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n" + "Content-Type: text/html\r\n\r\n").getBytes(CharsetUtil.ISO_8859_1))).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
assertTrue(future.isSuccess());
sChannel.writeAndFlush(Unpooled.wrappedBuffer("<html><body>hello half closed!</body></html>\r\n".getBytes(CharsetUtil.ISO_8859_1))).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
assertTrue(future.isSuccess());
sChannel.shutdownOutput();
}
});
}
});
}
});
serverChannelLatch.countDown();
}
});
cb.group(new NioEventLoopGroup(1));
cb.channel(NioSocketChannel.class);
cb.option(ChannelOption.ALLOW_HALF_CLOSURE, true);
cb.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
ch.pipeline().addLast(new HttpClientCodec(4096, 8192, 8192, true, true));
ch.pipeline().addLast(new HttpObjectAggregator(4096));
ch.pipeline().addLast(new SimpleChannelInboundHandler<FullHttpResponse>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) {
responseReceivedLatch.countDown();
}
});
}
});
Channel serverChannel = sb.bind(new InetSocketAddress(0)).sync().channel();
int port = ((InetSocketAddress) serverChannel.localAddress()).getPort();
ChannelFuture ccf = cb.connect(new InetSocketAddress(NetUtil.LOCALHOST, port));
assertTrue(ccf.awaitUninterruptibly().isSuccess());
Channel clientChannel = ccf.channel();
assertTrue(serverChannelLatch.await(5, SECONDS));
clientChannel.writeAndFlush(new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/"));
assertTrue(responseReceivedLatch.await(5, SECONDS));
} finally {
sb.config().group().shutdownGracefully();
sb.config().childGroup().shutdownGracefully();
cb.config().group().shutdownGracefully();
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.SimpleChannelInboundHandler in project netty by netty.
the class SocketDataReadInitialStateTest method testAutoReadOffNoDataReadUntilReadCalled.
public void testAutoReadOffNoDataReadUntilReadCalled(ServerBootstrap sb, Bootstrap cb) throws Throwable {
Channel serverChannel = null;
Channel clientChannel = null;
final int sleepMs = 100;
try {
sb.option(AUTO_READ, false);
sb.childOption(AUTO_READ, false);
cb.option(AUTO_READ, false);
final CountDownLatch serverReadyLatch = new CountDownLatch(1);
final CountDownLatch acceptorReadLatch = new CountDownLatch(1);
final CountDownLatch serverReadLatch = new CountDownLatch(1);
final CountDownLatch clientReadLatch = new CountDownLatch(1);
final AtomicReference<Channel> serverConnectedChannelRef = new AtomicReference<Channel>();
sb.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
acceptorReadLatch.countDown();
ctx.fireChannelRead(msg);
}
});
}
});
sb.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
serverConnectedChannelRef.set(ch);
ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
ctx.writeAndFlush(msg.retainedDuplicate());
serverReadLatch.countDown();
}
});
serverReadyLatch.countDown();
}
});
cb.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
ch.pipeline().addLast(new SimpleChannelInboundHandler<Object>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
clientReadLatch.countDown();
}
});
}
});
serverChannel = sb.bind().sync().channel();
clientChannel = cb.connect(serverChannel.localAddress()).sync().channel();
clientChannel.writeAndFlush(clientChannel.alloc().buffer().writeZero(1)).syncUninterruptibly();
// The acceptor shouldn't read any data until we call read() below, but give it some time to see if it will.
Thread.sleep(sleepMs);
assertEquals(1, acceptorReadLatch.getCount());
serverChannel.read();
serverReadyLatch.await();
Channel serverConnectedChannel = serverConnectedChannelRef.get();
assertNotNull(serverConnectedChannel);
// Allow some amount of time for the server peer to receive the message (which isn't expected to happen
// until we call read() below).
Thread.sleep(sleepMs);
assertEquals(1, serverReadLatch.getCount());
serverConnectedChannel.read();
serverReadLatch.await();
// Allow some amount of time for the client to read the echo.
Thread.sleep(sleepMs);
assertEquals(1, clientReadLatch.getCount());
clientChannel.read();
clientReadLatch.await();
} finally {
if (serverChannel != null) {
serverChannel.close().sync();
}
if (clientChannel != null) {
clientChannel.close().sync();
}
}
}
use of org.apache.flink.shaded.netty4.io.netty.channel.SimpleChannelInboundHandler in project netty by netty.
the class SocketFileRegionTest method testFileRegion0.
private static void testFileRegion0(ServerBootstrap sb, Bootstrap cb, boolean voidPromise, final boolean autoRead, boolean defaultFileRegion) throws Throwable {
sb.childOption(ChannelOption.AUTO_READ, autoRead);
cb.option(ChannelOption.AUTO_READ, autoRead);
final int bufferSize = 1024;
final File file = PlatformDependent.createTempFile("netty-", ".tmp", null);
file.deleteOnExit();
final FileOutputStream out = new FileOutputStream(file);
final Random random = PlatformDependent.threadLocalRandom();
// Prepend random data which will not be transferred, so that we can test non-zero start offset
final int startOffset = random.nextInt(8192);
for (int i = 0; i < startOffset; i++) {
out.write(random.nextInt());
}
// .. and here comes the real data to transfer.
out.write(data, bufferSize, data.length - bufferSize);
// .. and then some extra data which is not supposed to be transferred.
for (int i = random.nextInt(8192); i > 0; i--) {
out.write(random.nextInt());
}
out.close();
ChannelInboundHandler ch = new SimpleChannelInboundHandler<Object>() {
@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
if (!autoRead) {
ctx.read();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
ctx.close();
}
};
TestHandler sh = new TestHandler(autoRead);
sb.childHandler(sh);
cb.handler(ch);
Channel sc = sb.bind().sync().channel();
Channel cc = cb.connect(sc.localAddress()).sync().channel();
FileRegion region = new DefaultFileRegion(new RandomAccessFile(file, "r").getChannel(), startOffset, data.length - bufferSize);
FileRegion emptyRegion = new DefaultFileRegion(new RandomAccessFile(file, "r").getChannel(), 0, 0);
if (!defaultFileRegion) {
region = new FileRegionWrapper(region);
emptyRegion = new FileRegionWrapper(emptyRegion);
}
// https://github.com/netty/netty/issues/2964
if (voidPromise) {
assertEquals(cc.voidPromise(), cc.write(Unpooled.wrappedBuffer(data, 0, bufferSize), cc.voidPromise()));
assertEquals(cc.voidPromise(), cc.write(emptyRegion, cc.voidPromise()));
assertEquals(cc.voidPromise(), cc.writeAndFlush(region, cc.voidPromise()));
} else {
assertNotEquals(cc.voidPromise(), cc.write(Unpooled.wrappedBuffer(data, 0, bufferSize)));
assertNotEquals(cc.voidPromise(), cc.write(emptyRegion));
assertNotEquals(cc.voidPromise(), cc.writeAndFlush(region));
}
while (sh.counter < data.length) {
if (sh.exception.get() != null) {
break;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// Ignore.
}
}
sh.channel.close().sync();
cc.close().sync();
sc.close().sync();
if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) {
throw sh.exception.get();
}
if (sh.exception.get() != null) {
throw sh.exception.get();
}
// Make sure we did not receive more than we expected.
assertThat(sh.counter, is(data.length));
}
use of org.apache.flink.shaded.netty4.io.netty.channel.SimpleChannelInboundHandler in project netty by netty.
the class DatagramUnicastInetTest method setupServerChannel.
@Override
protected Channel setupServerChannel(Bootstrap sb, final byte[] bytes, final SocketAddress sender, final CountDownLatch latch, final AtomicReference<Throwable> errorRef, final boolean echo) throws Throwable {
sb.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
ch.pipeline().addLast(new SimpleChannelInboundHandler<DatagramPacket>() {
@Override
public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) {
try {
if (sender == null) {
assertNotNull(msg.sender());
} else {
InetSocketAddress senderAddress = (InetSocketAddress) sender;
if (senderAddress.getAddress().isAnyLocalAddress()) {
assertEquals(senderAddress.getPort(), msg.sender().getPort());
} else {
assertEquals(sender, msg.sender());
}
}
ByteBuf buf = msg.content();
assertEquals(bytes.length, buf.readableBytes());
for (int i = 0; i < bytes.length; i++) {
assertEquals(bytes[i], buf.getByte(buf.readerIndex() + i));
}
// Test that the channel's localAddress is equal to the message's recipient
assertEquals(ctx.channel().localAddress(), msg.recipient());
if (echo) {
ctx.writeAndFlush(new DatagramPacket(buf.retainedDuplicate(), msg.sender()));
}
} finally {
latch.countDown();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
errorRef.compareAndSet(null, cause);
}
});
}
});
return sb.bind(newSocketAddress()).sync().channel();
}
Aggregations