Search in sources :

Example 26 with ByteBufOutputStream

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());
}
Also used : ChannelFuture(io.netty.channel.ChannelFuture) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) NioServerSocketChannel(io.netty.channel.socket.nio.NioServerSocketChannel) Inet4Address(java.net.Inet4Address) ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) InetSocketAddress(java.net.InetSocketAddress) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) ExecutionException(java.util.concurrent.ExecutionException) ChannelPipeline(io.netty.channel.ChannelPipeline) EventLoopGroup(io.netty.channel.EventLoopGroup) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) ServerBootstrap(io.netty.bootstrap.ServerBootstrap) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) ChannelInboundHandlerAdapter(io.netty.channel.ChannelInboundHandlerAdapter) Test(org.junit.jupiter.api.Test)

Example 27 with ByteBufOutputStream

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));
}
Also used : ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) ByteBufInputStream(io.netty.buffer.ByteBufInputStream) ChannelId(io.netty.channel.ChannelId) ByteBuf(io.netty.buffer.ByteBuf) ObjectOutputStream(java.io.ObjectOutputStream) ObjectInputStream(java.io.ObjectInputStream) Test(org.junit.jupiter.api.Test)

Example 28 with ByteBufOutputStream

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);
    }
}
Also used : DefaultFullHttpResponse(io.netty.handler.codec.http.DefaultFullHttpResponse) ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) IOException(java.io.IOException)

Example 29 with ByteBufOutputStream

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;
}
Also used : ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) VisibleForTesting(com.google.common.annotations.VisibleForTesting) SneakyThrows(lombok.SneakyThrows)

Example 30 with ByteBufOutputStream

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);
}
Also used : ByteBufAllocator(io.netty.buffer.ByteBufAllocator) ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) ByteBufOutputStream(io.netty.buffer.ByteBufOutputStream) ByteBuf(io.netty.buffer.ByteBuf)

Aggregations

ByteBufOutputStream (io.netty.buffer.ByteBufOutputStream)52 ByteBuf (io.netty.buffer.ByteBuf)37 IOException (java.io.IOException)18 ObjectOutputStream (java.io.ObjectOutputStream)11 OutputStreamWriter (java.io.OutputStreamWriter)6 ByteBufInputStream (io.netty.buffer.ByteBufInputStream)5 OutputStream (java.io.OutputStream)5 Test (org.junit.jupiter.api.Test)5 ObjectInputStream (java.io.ObjectInputStream)4 SneakyThrows (lombok.SneakyThrows)4 NBTTagCompound (net.minecraft.nbt.NBTTagCompound)4 ByteBufAllocator (io.netty.buffer.ByteBufAllocator)3 Writer (java.io.Writer)3 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 CodedOutputStream (com.google.protobuf.CodedOutputStream)2 Bootstrap (io.netty.bootstrap.Bootstrap)2 ServerBootstrap (io.netty.bootstrap.ServerBootstrap)2