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(int index, int length);

Source Link

Document

Returns a copy of this buffer's sub-region.

Usage

From source file:org.apache.drill.exec.rpc.ZeroCopyProtobufLengthDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

    if (!ctx.channel().isOpen()) {
        if (in.readableBytes() > 0)
            logger.info("Channel is closed, discarding remaining {} byte(s) in buffer.", in.readableBytes());
        in.skipBytes(in.readableBytes());
        return;//from  w ww  . j a  va  2s . co m
    }

    in.markReaderIndex();
    final byte[] buf = new byte[5];
    for (int i = 0; i < buf.length; i++) {
        if (!in.isReadable()) {
            in.resetReaderIndex();
            return;
        }

        buf[i] = in.readByte();
        if (buf[i] >= 0) {

            int length = CodedInputStream.newInstance(buf, 0, i + 1).readRawVarint32();

            if (length < 0) {
                throw new CorruptedFrameException("negative length: " + length);
            }
            if (length == 0) {
                throw new CorruptedFrameException("Received a message of length 0.");
            }

            if (in.readableBytes() < length) {
                in.resetReaderIndex();
                return;
            } else {
                // need to make buffer copy, otherwise netty will try to refill this buffer if we move the readerIndex forward...
                // TODO: Can we avoid this copy?
                ByteBuf outBuf = in.copy(in.readerIndex(), length);
                in.skipBytes(length);

                if (RpcConstants.EXTRA_DEBUGGING)
                    logger.debug(String.format(
                            "ReaderIndex is %d after length header of %d bytes and frame body of length %d bytes.",
                            in.readerIndex(), i + 1, length));
                out.add(outBuf);
                return;
            }
        }
    }

    // Couldn't find the byte whose MSB is off.
    throw new CorruptedFrameException("length wider than 32-bit");

}

From source file:org.apache.dubbo.rpc.protocol.dubbo.decode.DubboTelnetDecodeTest.java

License:Apache License

/**
 * dubbo and dubbo request//from  www  .  j  a v a 2s .  co m
 *
 * <p>
 * First ByteBuf (firstDubboByteBuf):
 * ++-------------------------------------------------+
 * ||               dubbo(incomplete)                 |
 * ++-------------------------------------------------+
 * ||
 * Magic Code
 * <p>
 *
 * <p>
 * Second ByteBuf (secondDubboByteBuf):
 * +-------------------------++-----------------------+
 * |  dubbo(the remaining)   ||    dubbo(complete)    |
 * +-------------------------++-----------------------+
 *                           ||
 *                       Magic Code
 *
 * @throws InterruptedException
 */
@Test
public void testDubboDubboDecoded() throws InterruptedException, IOException {
    ByteBuf dubboByteBuf = createDubboByteBuf();

    ByteBuf firstDubboByteBuf = dubboByteBuf.copy(0, 50);
    ByteBuf secondLeftDubboByteBuf = dubboByteBuf.copy(50, dubboByteBuf.readableBytes() - 50);
    ByteBuf secondDubboByteBuf = Unpooled.wrappedBuffer(secondLeftDubboByteBuf, dubboByteBuf);

    EmbeddedChannel ch = null;
    try {
        Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo");
        URL url = new URL("dubbo", "localhost", 22226);
        NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler());

        MockHandler mockHandler = new MockHandler(null, new MultiMessageHandler(
                new DecodeHandler(new HeaderExchangeHandler(new ExchangeHandlerAdapter() {
                    @Override
                    public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) {
                        if (checkDubboDecoded(msg)) {
                            dubboDubbo.incrementAndGet();
                        }
                        return null;
                    }
                }))));

        ch = new LocalEmbeddedChannel();
        ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler);

        ch.writeInbound(firstDubboByteBuf);
        ch.writeInbound(secondDubboByteBuf);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (ch != null) {
            ch.close().await(200, TimeUnit.MILLISECONDS);
        }
    }

    TimeUnit.MILLISECONDS.sleep(100);

    Assertions.assertEquals(2, dubboDubbo.get());
}

From source file:org.apache.dubbo.rpc.protocol.dubbo.decode.DubboTelnetDecodeTest.java

License:Apache License

/**
 * dubbo and telnet request//from w w w. j a  va2s. com
 *
 * <p>
 * First ByteBuf:
 * ++-------------------------------------------------+
 * ||               dubbo(incomplete)                 |
 * ++-------------------------------------------------+
 * ||
 * Magic Code
 *
 * <p>
 * Second ByteBuf:
 * +--------------------------------------------------+
 * |  dubbo(the remaining)  |     telnet(complete)    |
 * +--------------------------------------------------+
 *
 * @throws InterruptedException
 */
@Test
public void testDubboTelnetDecoded() throws InterruptedException, IOException {
    ByteBuf dubboByteBuf = createDubboByteBuf();
    ByteBuf firstDubboByteBuf = dubboByteBuf.copy(0, 50);
    ByteBuf secondLeftDubboByteBuf = dubboByteBuf.copy(50, dubboByteBuf.readableBytes());

    ByteBuf telnetByteBuf = Unpooled.wrappedBuffer("\r\n".getBytes());
    ByteBuf secondByteBuf = Unpooled.wrappedBuffer(secondLeftDubboByteBuf, telnetByteBuf);

    EmbeddedChannel ch = null;
    try {
        Codec2 codec = ExtensionLoader.getExtensionLoader(Codec2.class).getExtension("dubbo");
        URL url = new URL("dubbo", "localhost", 22226);
        NettyCodecAdapter adapter = new NettyCodecAdapter(codec, url, new MockChannelHandler());

        MockHandler mockHandler = new MockHandler((msg) -> {
            if (checkTelnetDecoded(msg)) {
                dubboTelnet.incrementAndGet();
            }
        }, new MultiMessageHandler(new DecodeHandler(new HeaderExchangeHandler(new ExchangeHandlerAdapter() {
            @Override
            public CompletableFuture<Object> reply(ExchangeChannel channel, Object msg) {
                if (checkDubboDecoded(msg)) {
                    dubboTelnet.incrementAndGet();
                }
                return null;
            }
        }))));

        ch = new LocalEmbeddedChannel();
        ch.pipeline().addLast("decoder", adapter.getDecoder()).addLast("handler", mockHandler);

        ch.writeInbound(firstDubboByteBuf);
        ch.writeInbound(secondByteBuf);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (ch != null) {
            ch.close().await(200, TimeUnit.MILLISECONDS);
        }
    }

    TimeUnit.MILLISECONDS.sleep(100);

    Assertions.assertEquals(2, dubboTelnet.get());
}

From source file:org.helios.octo.client.ResponseHandler.java

License:Open Source License

/**
 * {@inheritDoc}// w  ww . j a v a2s .com
 * @see io.netty.handler.codec.ByteToMessageDecoder#decode(io.netty.channel.ChannelHandlerContext, io.netty.buffer.ByteBuf, io.netty.channel.MessageList)
 */
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, MessageList<Object> out) {
    long bytesAvailable = super.actualReadableBytes();
    log.info("Replay Bytes Available:" + bytesAvailable);
    if (bytesAvailable < 1)
        return;
    switch (state()) {
    case REQUEST_ID:
        log.info("--------------------------------->Processing [" + state() + "]");
        long reqId = in.readLong();
        ctx.channel().attr(OctoShared.REQ_ID).set(reqId);
        checkpoint(RESPONSE_TYPE);
        log.info("REQUEST_ID:" + reqId);
    case RESPONSE_TYPE:
        log.info("--------------------------------->Processing [" + state() + "]");
        byte responseType = in.readByte();
        log.info("RESPONSE_TYPE:" + responseType);
        if (responseType == 0) {
            checkpoint(STREAM_TYPE);
        } else {
            //            if(!ctx.pipeline().get(name))
            ctx.pipeline().addAfter(OctoShared.RESPONSE_HANDLER, OctoShared.OBJECT_DECODER,
                    new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
            out.add(in.copy(0, super.actualReadableBytes()));
            checkpoint(FORWARD);
            return;
        }
    case STREAM_TYPE:
        log.info("--------------------------------->Processing [" + state() + "]");
        byte streamType = in.readByte();
        ctx.channel().attr(OctoShared.STREAM).set(streamType);
        log.info("STREAM_TYPE:" + streamType);
        checkpoint(FORWARD);
        return;
    //         out.add(in.readBytes(super.actualReadableBytes()));         
    //         return;
    case FORWARD:
        log.info("--------------------------------->Processing [" + state() + "]");
        log.info("Forwarding [" + super.actualReadableBytes() + "]....");
        out.add(in.readBytes(super.actualReadableBytes()));
        log.info("Forward Complete. Remaining: [" + super.actualReadableBytes() + "]");
        return;
    default:
        log.warn("Unexpected state [" + state() + "]");
        break;
    }
}

From source file:org.nd4j.linalg.api.buffer.DoubleDataBufferTest.java

License:Apache License

@Test
public void testNettyCopy() {
    DataBuffer db = Nd4j.createBuffer(new double[] { 1, 2, 3, 4 });
    ByteBuf buf = db.asNetty();
    if (db.allocationMode() == DataBuffer.AllocationMode.HEAP)
        return;//from   ww w . j  a va  2  s.  c o  m

    ByteBuf copy = buf.copy(0, buf.capacity());
    for (int i = 0; i < db.length(); i++) {
        assertEquals(db.getDouble(i), copy.getDouble(i * 8));
    }
}

From source file:org.opendaylight.openflowjava.protocol.impl.deserialization.factories.MultipartReplyMessageFactoryTest.java

License:Open Source License

/**
 * Testing {@link MultipartReplyMessageFactory} for correct translation into POJO
 *//* w  w  w. j a v a 2s  .  com*/
@Test
public void testMultipartReplyPortDescBody() {
    final byte MAX_PORT_NAME_LEN = 16;
    ByteBuf bb = BufferHelper.buildBuffer("00 0D 00 01 00 00 00 00 " + "00 01 02 03 " + //portNo
            "00 00 00 00 " + //padding01
            "08 00 27 00 B0 EB " + //mac address
            "00 00 "); //padding02
    //port name
    String portName = "SampleText";
    byte[] portNameBytes = new byte[MAX_PORT_NAME_LEN];
    portNameBytes = portName.getBytes();
    bb.writeBytes(portNameBytes);
    ByteBufUtils.padBuffer((MAX_PORT_NAME_LEN - portNameBytes.length), bb);

    ByteBuf bb2 = BufferHelper.buildBuffer("00 00 00 41 " + //port config
            "00 00 00 05 " + //port state
            "00 00 00 81 " + //current features
            "00 00 81 81 " + //advertised features
            "00 00 C1 89 " + //supported features
            "00 00 C5 8D " + //peer features
            "00 00 00 81 " + //curr speed
            "00 00 00 80" //max speed
    );
    bb.writeBytes(bb2.copy(4, bb2.readableBytes() - 4));//excluding version and xid

    MultipartReplyMessage builtByFactory = BufferHelper.decodeV13(MultipartReplyMessageFactory.getInstance(),
            bb);

    BufferHelper.checkHeaderV13(builtByFactory);
    Assert.assertEquals("Wrong type", 13, builtByFactory.getType().getIntValue());
    Assert.assertEquals("Wrong flag", true, builtByFactory.getFlags().isOFPMPFREQMORE());
    MultipartReplyPortDescCase messageCase = (MultipartReplyPortDescCase) builtByFactory
            .getMultipartReplyBody();
    MultipartReplyPortDesc message = messageCase.getMultipartReplyPortDesc();
    Assert.assertEquals("Wrong portNo", 66051L, message.getPorts().get(0).getPortNo().longValue());
    Assert.assertEquals("Wrong macAddress", new MacAddress("08:00:27:00:B0:EB"),
            message.getPorts().get(0).getHwAddr());
    Assert.assertEquals("Wrong portName", "SampleText", message.getPorts().get(0).getName());
    Assert.assertEquals("Wrong portConfig", new PortConfig(false, true, false, true),
            message.getPorts().get(0).getConfig());
    Assert.assertEquals("Wrong portState", new PortState(false, true, true),
            message.getPorts().get(0).getState());
    Assert.assertEquals(
            "Wrong currentFeatures", new PortFeatures(false, false, false, false, false, true, false, false,
                    false, true, false, false, false, false, false, false),
            message.getPorts().get(0).getCurrentFeatures());
    Assert.assertEquals(
            "Wrong advertisedFeatures", new PortFeatures(true, false, false, false, false, true, false, false,
                    false, true, false, false, false, false, false, true),
            message.getPorts().get(0).getAdvertisedFeatures());
    Assert.assertEquals(
            "Wrong supportedFeatures", new PortFeatures(true, true, false, false, false, true, false, false,
                    false, true, false, false, false, false, true, true),
            message.getPorts().get(0).getSupportedFeatures());
    Assert.assertEquals("Wrong peerFeatures", new PortFeatures(true, true, true, false, false, true, false,
            false, false, true, false, false, false, true, true, true),
            message.getPorts().get(0).getPeerFeatures());
    Assert.assertEquals("Wrong currSpeed", 129L, message.getPorts().get(0).getCurrSpeed().longValue());
    Assert.assertEquals("Wrong maxSpeed", 128L, message.getPorts().get(0).getMaxSpeed().longValue());
}

From source file:org.opendaylight.protocol.bgp.parser.impl.PathAttributeParserTest.java

License:Open Source License

@Test
public void testSerializingAigpAttribute() throws BGPDocumentedException, BGPParsingException {
    final byte[] value = new byte[] { 1, 0, 11, 0, 0, 0, 0, 0, 0, 0, 8 };
    final ByteBuf inputData = Unpooled.buffer();
    final ByteBuf testBuffer = Unpooled.buffer();

    AttributeUtil.formatAttribute(AttributeUtil.OPTIONAL, AigpAttributeParser.TYPE,
            Unpooled.copiedBuffer(value), inputData);

    final BGPExtensionProviderContext providerContext = ServiceLoaderBGPExtensionProviderContext
            .getSingletonInstance();//from   w w  w . j  a v a 2  s  .c  om
    final Attributes pathAttributes = providerContext.getAttributeRegistry().parseAttributes(inputData);
    final Aigp aigp = pathAttributes.getAigp();

    final AttributesBuilder pathAttributesBuilder = new AttributesBuilder();
    pathAttributesBuilder.setAigp(aigp);

    final AigpAttributeParser parser = new AigpAttributeParser();
    parser.serializeAttribute(pathAttributesBuilder.build(), testBuffer);

    final byte[] unparserData = inputData.copy(0, inputData.writerIndex()).array();
    final byte[] serializedData = testBuffer.copy(0, inputData.writerIndex()).array();

    assertTrue("Buffers should be the same.", Arrays.equals(unparserData, serializedData));
}

From source file:org.opendaylight.usc.plugin.UscMultiplexer.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf payload = (ByteBuf) msg;
    LOG.trace("UscMultiplexer.channelRead: " + payload);

    Channel ch = ctx.channel();// ww  w . j av a 2s  .c om
    Channel outboundChannel = ch.attr(UscPlugin.DIRECT_CHANNEL).get();
    if (outboundChannel != null) {
        if (plugin.getChannelType() == UscChannel.ChannelType.DTLS
                || plugin.getChannelType() == UscChannel.ChannelType.UDP) {
            DatagramPacket packet = new DatagramPacket(payload,
                    (InetSocketAddress) outboundChannel.remoteAddress());
            LOG.trace("UscMultiplexer.channelRead: convert payload to DatagramPacket " + packet);
            outboundChannel.write(packet);
        } else
            outboundChannel.write(msg);
    } else {
        UscSessionImpl session = ch.attr(UscPlugin.SESSION).get().get();
        outboundChannel = session.getChannel().getChannel();

        UscData reply = null;
        ByteBuf subPayload = null;
        int length = payload.readableBytes();
        int bytesOut = length;
        int index = 0;
        int realLength = 0;
        while (length > 0) {
            realLength = (length > MAX_PAYLOAD_SIZE) ? MAX_PAYLOAD_SIZE : length;
            subPayload = payload.copy(index, realLength);
            index += realLength;
            length -= realLength;

            reply = new UscData(session.getPort(), session.getSessionId(), subPayload);
            LOG.trace("Send data to Java Agent " + reply);
            outboundChannel.writeAndFlush(reply);
        }
        plugin.sendEvent(new UscSessionTransactionEvent(session, 0, bytesOut));
    }
}

From source file:org.traccar.protocol.Tk102ProtocolDecoder.java

License:Apache License

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    ByteBuf buf = (ByteBuf) msg;/*from   ww w  .j av  a 2  s  . c  o m*/

    buf.skipBytes(1); // header
    int type = buf.readUnsignedByte();
    ByteBuf dataSequence = buf.readSlice(10);
    int length = buf.readUnsignedByte();

    if (type == MSG_LOGIN_REQUEST || type == MSG_LOGIN_REQUEST_2) {

        ByteBuf data = buf.readSlice(length);

        String id;
        if (type == MSG_LOGIN_REQUEST) {
            id = data.toString(StandardCharsets.US_ASCII);
        } else {
            id = data.copy(1, 15).toString(StandardCharsets.US_ASCII);
        }

        if (getDeviceSession(channel, remoteAddress, id) != null) {
            ByteBuf response = Unpooled.buffer();
            response.writeByte(MODE_GPRS);
            response.writeBytes(data);
            sendResponse(channel, MSG_LOGIN_RESPONSE, dataSequence, response);
        }

    } else if (type == MSG_HEARTBEAT_REQUEST) {

        sendResponse(channel, MSG_HEARTBEAT_RESPONSE, dataSequence, buf.readRetainedSlice(length));

    } else {

        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress);
        if (deviceSession == null) {
            return null;
        }

        Parser parser = new Parser(PATTERN, buf.readSlice(length).toString(StandardCharsets.US_ASCII));
        if (!parser.matches()) {
            return null;
        }

        Position position = new Position(getProtocolName());
        position.setDeviceId(deviceSession.getDeviceId());

        DateBuilder dateBuilder = new DateBuilder().setTime(parser.nextInt(0), parser.nextInt(0),
                parser.nextInt(0));

        position.setValid(parser.next().equals("A"));
        position.setLatitude(parser.nextCoordinate());
        position.setLongitude(parser.nextCoordinate());
        position.setSpeed(parser.nextDouble(0));

        dateBuilder.setDateReverse(parser.nextInt(0), parser.nextInt(0), parser.nextInt(0));
        position.setTime(dateBuilder.getDate());

        return position;

    }

    return null;
}

From source file:ru.jts.authserver.network.handler.packet.Client2AuthPacketHandler.java

License:Apache License

@Override
public ClientPacket<Client> handlePacket(ByteBuf buf) {
    byte b1 = buf.readByte(); // 1
    short unk1 = buf.readShort(); // 0
    short size = buf.readShort(); // data size

    short sessionId = buf.readShort(); // sessionKey
    byte b2 = buf.readByte(); // 1

    int unk2 = buf.readInt(); // 0
    byte b3 = buf.readByte(); // 8

    byte[] packetData = new byte[buf.readableBytes() - 4];
    short unk3 = buf.readShort(); // 00 02
    buf.readBytes(packetData);//from   w  w w  .  j a va2s.c  o m
    short unk4 = buf.readShort(); // 02 00
    buf.clear();

    ByteBuf packetBuf = Unpooled.copiedBuffer(packetData).order(ByteOrder.LITTLE_ENDIAN);
    packetBuf = decryptBuffer(packetBuf);

    int opcode = packetBuf.readUnsignedByte();

    ClientPacket<Client> packet = null;
    switch (opcode) {
    case 0x01:
        packet = new CM_AUTH_BY_PASS(sessionId);
        break;
    //case 0x02:
    //    packet = new AuthorizeBySession();
    //    break;
    default:
        log.warn("Unknown opcode {}", Integer.toHexString(opcode));
        log.warn(ArrayUtils
                .bytesToHexString(packetBuf.copy(packetBuf.readerIndex(), packetBuf.readableBytes()).array()));
        log.warn(new String(packetBuf.copy(packetBuf.readerIndex(), packetBuf.readableBytes()).array()));
        break;
    }

    if (packet != null) {
        packet.setContent(packetBuf);
    }
    return packet;
}