use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBufOutputStream in project netty by netty.
the class PcapWriteHandlerTest method tcpV4.
@Test
public void tcpV4() throws InterruptedException, ExecutionException {
final ByteBuf byteBuf = Unpooled.buffer();
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup clientGroup = new NioEventLoopGroup();
// Configure the echo server
ServerBootstrap sb = new ServerBootstrap();
final Promise<Boolean> dataReadPromise = bossGroup.next().newPromise();
sb.group(bossGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new PcapWriteHandler(new ByteBufOutputStream(byteBuf)));
p.addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
ctx.write(msg);
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
dataReadPromise.setSuccess(true);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
}
});
}
});
// Start the server.
ChannelFuture serverChannelFuture = sb.bind(new InetSocketAddress("127.0.0.1", 0)).sync();
assertTrue(serverChannelFuture.isSuccess());
// configure the client
Bootstrap cb = new Bootstrap();
final Promise<Boolean> dataWrittenPromise = clientGroup.next().newPromise();
cb.group(clientGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true).handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(ChannelHandlerContext ctx) {
ctx.writeAndFlush(Unpooled.wrappedBuffer("Meow".getBytes()));
dataWrittenPromise.setSuccess(true);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
}
});
}
});
// Start the client.
ChannelFuture clientChannelFuture = cb.connect(serverChannelFuture.channel().localAddress()).sync();
assertTrue(clientChannelFuture.isSuccess());
assertTrue(dataWrittenPromise.await(5, TimeUnit.SECONDS));
assertTrue(dataReadPromise.await(5, TimeUnit.SECONDS));
clientChannelFuture.channel().close().sync();
serverChannelFuture.channel().close().sync();
// Shut down all event loops to terminate all threads.
assertTrue(clientGroup.shutdownGracefully().sync().isSuccess());
assertTrue(bossGroup.shutdownGracefully().sync().isSuccess());
verifyGlobalHeaders(byteBuf);
// Verify Pcap Packet Header
// Just read, we don't care about timestamps for now
byteBuf.readInt();
// Just read, we don't care about timestamps for now
byteBuf.readInt();
// Length of Packet Saved In Pcap
assertEquals(54, byteBuf.readInt());
// Actual Length of Packet
assertEquals(54, byteBuf.readInt());
// -------------------------------------------- Verify Packet --------------------------------------------
// Verify Ethernet Packet
ByteBuf ethernetPacket = byteBuf.readSlice(54);
ByteBuf dstMac = ethernetPacket.readSlice(6);
ByteBuf srcMac = ethernetPacket.readSlice(6);
assertArrayEquals(new byte[] { 0, 0, 94, 0, 83, -1 }, ByteBufUtil.getBytes(dstMac));
assertArrayEquals(new byte[] { 0, 0, 94, 0, 83, 0 }, ByteBufUtil.getBytes(srcMac));
assertEquals(0x0800, ethernetPacket.readShort());
// Verify IPv4 Packet
ByteBuf ipv4Packet = ethernetPacket.readSlice(32);
// Version + IHL
assertEquals(0x45, ipv4Packet.readByte());
// DSCP
assertEquals(0x00, ipv4Packet.readByte());
// Length
assertEquals(40, ipv4Packet.readShort());
// Identification
assertEquals(0x0000, ipv4Packet.readShort());
// Fragment
assertEquals(0x0000, ipv4Packet.readShort());
// TTL
assertEquals((byte) 0xff, ipv4Packet.readByte());
// Protocol
assertEquals((byte) 6, ipv4Packet.readByte());
// Checksum
assertEquals(0, ipv4Packet.readShort());
InetSocketAddress serverAddr = (InetSocketAddress) serverChannelFuture.channel().localAddress();
// Source IPv4 Address
assertEquals(NetUtil.ipv4AddressToInt((Inet4Address) serverAddr.getAddress()), ipv4Packet.readInt());
// Destination IPv4 Address
ipv4Packet.readInt();
InetSocketAddress clientAddr = (InetSocketAddress) clientChannelFuture.channel().localAddress();
// Verify ports
ByteBuf tcpPacket = ipv4Packet.readSlice(12);
// Source Port
assertEquals(clientAddr.getPort() & 0xffff, tcpPacket.readUnsignedShort());
// Destination Port
assertEquals(serverAddr.getPort() & 0xffff, tcpPacket.readUnsignedShort());
}
use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBufOutputStream in project netty by netty.
the class EmbeddedChannelIdTest method testSerialization.
@Test
public void testSerialization() throws IOException, ClassNotFoundException {
// test that a deserialized instance works the same as a normal instance (issue #2869)
ChannelId normalInstance = EmbeddedChannelId.INSTANCE;
ByteBuf buf = Unpooled.buffer();
ObjectOutputStream outStream = new ObjectOutputStream(new ByteBufOutputStream(buf));
try {
outStream.writeObject(normalInstance);
} finally {
outStream.close();
}
ObjectInputStream inStream = new ObjectInputStream(new ByteBufInputStream(buf, true));
final ChannelId deserializedInstance;
try {
deserializedInstance = (ChannelId) inStream.readObject();
} finally {
inStream.close();
}
assertEquals(normalInstance, deserializedInstance);
assertEquals(normalInstance.hashCode(), deserializedInstance.hashCode());
assertEquals(0, normalInstance.compareTo(deserializedInstance));
}
use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBufOutputStream in project crate by crate.
the class MainAndStaticFileHandler method clusterStateRespToHttpResponse.
private static FullHttpResponse clusterStateRespToHttpResponse(HttpMethod method, ClusterStateResponse response, ByteBufAllocator alloc, @Nullable String nodeName) {
var httpStatus = response.getState().blocks().hasGlobalBlockWithStatus(RestStatus.SERVICE_UNAVAILABLE) ? HttpResponseStatus.SERVICE_UNAVAILABLE : HttpResponseStatus.OK;
try {
DefaultFullHttpResponse resp;
if (method == HttpMethod.HEAD) {
resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpStatus);
HttpUtil.setContentLength(resp, 0);
} else {
var buffer = alloc.buffer();
try (var outputStream = new ByteBufOutputStream(buffer)) {
writeJSON(outputStream, response, httpStatus, nodeName);
}
resp = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, httpStatus, buffer);
resp.headers().set(HttpHeaderNames.CONTENT_TYPE, "application/json");
HttpUtil.setContentLength(resp, buffer.readableBytes());
}
return resp;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBufOutputStream in project pravega by pravega.
the class CommandEncoder method writeMessage.
@SneakyThrows(IOException.class)
@VisibleForTesting
static int writeMessage(WireCommand msg, ByteBuf out) {
int startIdx = out.writerIndex();
ByteBufOutputStream bout = new ByteBufOutputStream(out);
bout.writeInt(msg.getType().getCode());
bout.write(LENGTH_PLACEHOLDER);
msg.writeFields(bout);
bout.flush();
bout.close();
int endIdx = out.writerIndex();
int fieldsSize = endIdx - startIdx - TYPE_PLUS_LENGTH_SIZE;
out.setInt(startIdx + TYPE_SIZE, fieldsSize);
return endIdx - startIdx;
}
use of org.apache.flink.shaded.netty4.io.netty.buffer.ByteBufOutputStream in project ratpack by ratpack.
the class ErrorPageRenderer method render.
protected void render(Context context, String pageTitle, Consumer<? super BodyWriter> body) {
ByteBuf buffer = context.get(ByteBufAllocator.class).buffer();
OutputStream out = new ByteBufOutputStream(buffer);
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(out, CharsetUtil.encoder(CharsetUtil.UTF_8)));
BodyWriter writer = new BodyWriter(printWriter);
writer.println("<!DOCTYPE html>").println("<html>").println("<head>").print(" <title>").escape(pageTitle).println("</title>").println(" <style type=\"text/css\">").println(style).println(" </style>").println("</head>").println("<body>").println(" <header>").println(" <div class=\"logo\">").println(" <div class=\"martini\">").println(" <h1>Ratpack</h1>").println(" </div>").println(" <p>Development error page</p>").println(" </div>").println(" </header>");
body.accept(writer);
writer.println("<footer>").println(" <a href=\"http://www.ratpack.io\">Ratpack.io</a>").println("</footer>").println("</body>").println("</html>");
printWriter.close();
context.getResponse().send(HttpHeaderConstants.HTML_UTF_8, buffer);
}
Aggregations