Example usage for io.netty.buffer ByteBuf copy

List of usage examples for io.netty.buffer ByteBuf copy

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf copy.

Prototype

public abstract ByteBuf copy();

Source Link

Document

Returns a copy of this buffer's readable bytes.

Usage

From source file:divconq.http.multipart.MemoryAttribute.java

License:Apache License

@Override
public Attribute copy() {
    MemoryAttribute attr = new MemoryAttribute(getName());
    attr.setCharset(getCharset());//ww w  .  j av  a 2s .c  om
    ByteBuf content = content();
    if (content != null) {
        try {
            attr.setContent(content.copy());
        } catch (IOException e) {
            throw new ChannelException(e);
        }
    }
    return attr;
}

From source file:divconq.http.multipart.MemoryFileUpload.java

License:Apache License

@Override
public FileUpload copy() {
    MemoryFileUpload upload = new MemoryFileUpload(getName(), getFilename(), getContentType(),
            getContentTransferEncoding(), getCharset(), size);
    ByteBuf buf = content();
    if (buf != null) {
        try {/*from   w  w  w.j av a2  s  . c  o  m*/
            upload.setContent(buf.copy());
            return upload;
        } catch (IOException e) {
            throw new ChannelException(e);
        }
    }
    return upload;
}

From source file:io.datty.unit.UnitValue.java

License:Apache License

public UnitValue(ByteBuf input) {
    super(input.copy());
}

From source file:io.grpc.netty.NettyHandlerTestBase.java

License:Apache License

@Test
public void dataSizeSincePingAccumulates() throws Exception {
    manualSetUp();/*from   w  w  w.  ja  v  a2 s .  com*/
    makeStream();
    AbstractNettyHandler handler = (AbstractNettyHandler) handler();
    handler.setAutoTuneFlowControl(true);
    long frameData = 123456;
    ByteBuf buff = ctx().alloc().buffer(16);
    buff.writeLong(frameData);
    int length = buff.readableBytes();

    channelRead(dataFrame(3, false, buff.copy()));
    channelRead(dataFrame(3, false, buff.copy()));
    channelRead(dataFrame(3, false, buff.copy()));

    assertEquals(length * 3, handler.flowControlPing().getDataSincePing());
}

From source file:io.grpc.netty.NettyHandlerTestBase.java

License:Apache License

@Test
public void windowUpdateMatchesTarget() throws Exception {
    manualSetUp();/*w  w w.  ja v  a2 s.c  om*/
    Http2Stream connectionStream = connection().connectionStream();
    Http2LocalFlowController localFlowController = connection().local().flowController();
    makeStream();
    AbstractNettyHandler handler = (AbstractNettyHandler) handler();
    handler.setAutoTuneFlowControl(true);

    ByteBuf data = ctx().alloc().buffer(1024);
    while (data.isWritable()) {
        data.writeLong(1111);
    }
    int length = data.readableBytes();
    ByteBuf frame = dataFrame(3, false, data.copy());
    channelRead(frame);
    int accumulator = length;
    // 40 is arbitrary, any number large enough to trigger a window update would work
    for (int i = 0; i < 40; i++) {
        channelRead(dataFrame(3, false, data.copy()));
        accumulator += length;
    }
    long pingData = handler.flowControlPing().payload();
    channelRead(pingFrame(true, pingData));

    assertEquals(accumulator, handler.flowControlPing().getDataSincePing());
    assertEquals(2 * accumulator, localFlowController.initialWindowSize(connectionStream));
}

From source file:io.hekate.cluster.seed.multicast.MulticastSeedNodeProvider.java

License:Apache License

@Override
public void startDiscovery(String cluster, InetSocketAddress address) throws HekateException {
    log.info("Starting seed nodes discovery [cluster={}, {}]", cluster, ToString.formatProperties(this));

    SeedNode thisNode = new SeedNode(address, cluster);

    try {/*w  ww . j  a v a  2  s  . co m*/
        NetworkInterface nif = selectMulticastInterface(address);

        try {
            synchronized (mux) {
                if (isRegistered()) {
                    throw new IllegalStateException(
                            "Multicast seed node provider is already registered with another address "
                                    + "[existing=" + localNode + ']');
                }

                ByteBuf discoveryMsg = prepareDiscovery(thisNode);

                ByteBuf seedNodeInfoBytes = prepareSeedNodeInfo(thisNode);

                localNode = thisNode;

                seedNodes = new HashSet<>();

                eventLoop = new NioEventLoopGroup(1, new HekateThreadFactory("SeedNodeMulticast"));

                // Prepare common bootstrap options.
                Bootstrap bootstrap = new Bootstrap();

                bootstrap.option(ChannelOption.SO_REUSEADDR, true);
                bootstrap.option(ChannelOption.IP_MULTICAST_TTL, ttl);
                bootstrap.option(ChannelOption.IP_MULTICAST_IF, nif);

                if (loopBackDisabled) {
                    bootstrap.option(ChannelOption.IP_MULTICAST_LOOP_DISABLED, true);

                    if (DEBUG) {
                        log.debug("Setting {} option to true", ChannelOption.IP_MULTICAST_LOOP_DISABLED);
                    }
                }

                bootstrap.group(eventLoop);
                bootstrap.channelFactory(() -> new NioDatagramChannel(ipVer));

                // Create a sender channel (not joined to a multicast group).
                bootstrap.localAddress(0);
                bootstrap.handler(createSenderHandler(thisNode));

                ChannelFuture senderBind = bootstrap.bind();

                DatagramChannel localSender = (DatagramChannel) senderBind.channel();

                sender = localSender;

                senderBind.get();

                // Create a listener channel and join to a multicast group.
                bootstrap.localAddress(group.getPort());

                bootstrap.handler(createListenerHandler(thisNode, seedNodeInfoBytes));

                ChannelFuture listenerBind = bootstrap.bind();

                listener = (DatagramChannel) listenerBind.channel();

                listenerBind.get();

                log.info("Joining to a multicast group " + "[address={}, port={}, interface={}, ttl={}]",
                        AddressUtils.host(group), group.getPort(), nif.getName(), ttl);

                listener.joinGroup(group, nif).get();

                // Create a periodic task for discovery messages sending.
                discoveryFuture = eventLoop.scheduleWithFixedDelay(() -> {
                    if (DEBUG) {
                        log.debug("Sending discovery message [from={}]", thisNode);
                    }

                    DatagramPacket discovery = new DatagramPacket(discoveryMsg.copy(), group);

                    localSender.writeAndFlush(discovery);
                }, 0, interval, TimeUnit.MILLISECONDS);
            }
        } catch (ExecutionException e) {
            cleanup();

            throw new HekateException(
                    "Failed to start a multicast seed nodes discovery [node=" + thisNode + ']', e.getCause());
        }

        log.info("Will wait for seed nodes [timeout={}(ms)]", waitTime);

        Thread.sleep(waitTime);
    } catch (InterruptedException e) {
        cleanup();

        Thread.currentThread().interrupt();

        throw new HekateException(
                "Thread was interrupted while awaiting for multicast discovery [node=" + thisNode + ']', e);
    }

    log.info("Done waiting for seed nodes.");
}

From source file:io.hekate.cluster.seed.multicast.MulticastSeedNodeProvider.java

License:Apache License

private SimpleChannelInboundHandler<DatagramPacket> createListenerHandler(SeedNode thisNode,
        ByteBuf seedNodeInfo) {
    return new SimpleChannelInboundHandler<DatagramPacket>() {
        @Override//from w ww  .  j ava2  s  .c  om
        public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
            ByteBuf buf = msg.content();

            if (buf.readableBytes() > 4 && buf.readInt() == Utils.MAGIC_BYTES) {
                MessageTYpe msgType = MessageTYpe.values()[buf.readByte()];

                if (msgType == MessageTYpe.DISCOVERY) {
                    String cluster = decodeUtf(buf);
                    InetSocketAddress address = decodeAddress(buf);

                    if (thisNode.cluster().equals(cluster) && !address.equals(thisNode.address())) {
                        onDiscoveryMessage(address);

                        DatagramPacket response = new DatagramPacket(seedNodeInfo.copy(), msg.sender());

                        ctx.writeAndFlush(response);
                    }
                }
            }
        }
    };
}

From source file:io.moquette.spi.impl.DebugUtils.java

License:Open Source License

static String payload2Str(ByteBuf content) {
    return new String(content.copy().array());
}

From source file:io.vertx.core.http.Http2ServerTest.java

License:Open Source License

private void testNetSocketSendFile(Buffer expected, String path, long offset, long length) throws Exception {
    server.requestHandler(req -> {/*  w  ww .j  a  va  2 s.  c om*/
        NetSocket socket = req.netSocket();
        socket.sendFile(path, offset, length, ar -> {
            assertTrue(ar.succeeded());
            socket.end();
        });
    });
    startServer();
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        request.decoder.frameListener(new Http2EventAdapter() {
            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                    int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                    throws Http2Exception {
                vertx.runOnContext(v -> {
                    assertEquals("200", headers.status().toString());
                    assertFalse(endStream);
                });
            }

            Buffer received = Buffer.buffer();

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
                    boolean endOfStream) throws Http2Exception {
                received.appendBuffer(Buffer.buffer(data.copy()));
                if (endOfStream) {
                    vertx.runOnContext(v -> {
                        assertEquals(received, expected);
                        testComplete();
                    });
                }
                return data.readableBytes() + padding;
            }
        });
        request.encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}

From source file:io.vertx.core.http.Http2ServerTest.java

License:Open Source License

@Test
public void testUnknownFrame() throws Exception {
    Buffer expectedSend = TestUtils.randomBuffer(500);
    Buffer expectedRecv = TestUtils.randomBuffer(500);
    Context ctx = vertx.getOrCreateContext();
    server.requestHandler(req -> {//from   w w w .  j a  v a2 s  .c  o m
        req.customFrameHandler(frame -> {
            assertOnIOContext(ctx);
            assertEquals(10, frame.type());
            assertEquals(253, frame.flags());
            assertEquals(expectedSend, frame.payload());
            req.response().writeCustomFrame(12, 134, expectedRecv).end();
        });
    });
    startServer(ctx);
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        request.decoder.frameListener(new Http2EventAdapter() {
            int status = 0;

            @Override
            public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers,
                    int streamDependency, short weight, boolean exclusive, int padding, boolean endStream)
                    throws Http2Exception {
                int s = status++;
                vertx.runOnContext(v -> {
                    assertEquals(0, s);
                });
            }

            @Override
            public void onUnknownFrame(ChannelHandlerContext ctx, byte frameType, int streamId,
                    Http2Flags flags, ByteBuf payload) {
                int s = status++;
                Buffer recv = Buffer.buffer(payload.copy());
                vertx.runOnContext(v -> {
                    assertEquals(1, s);
                    assertEquals(12, frameType);
                    assertEquals(134, flags.value());
                    assertEquals(expectedRecv, recv);
                });
            }

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding,
                    boolean endOfStream) throws Http2Exception {
                int len = data.readableBytes();
                int s = status++;
                vertx.runOnContext(v -> {
                    assertEquals(2, s);
                    assertEquals(0, len);
                    assertTrue(endOfStream);
                    testComplete();
                });
                return data.readableBytes() + padding;
            }
        });
        request.encoder.writeHeaders(request.context, id, GET("/"), 0, false, request.context.newPromise());
        request.encoder.writeFrame(request.context, (byte) 10, id, new Http2Flags((short) 253),
                expectedSend.getByteBuf(), request.context.newPromise());
        request.context.flush();
    });
    fut.sync();
    await();
}