Example usage for io.netty.buffer ByteBuf readerIndex

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

Introduction

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

Prototype

public abstract int readerIndex();

Source Link

Document

Returns the readerIndex of this buffer.

Usage

From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPMessage.java

License:Apache License

/**
 * Create a human readable string representation of binary data, keeping printable ascii and hex
 * encoding everything else./*w  w  w . j a  va 2s  .  c o m*/
 *
 * @param data The data
 * @return A human readable string representation of the data.
 */
private static String toString(final ByteBuf data) {
    if (data == null) {
        return null;
    }
    final StringBuilder sb = new StringBuilder();
    for (int i = data.readerIndex(); i < data.writerIndex(); i++) {
        final byte b = data.getByte(i);
        if (b > 31 && b < 127) {
            if (b == '%') {
                sb.append('%');
            }
            sb.append((char) b);
        } else {
            sb.append('%');
            sb.append(String.format("%02X", b));
        }
    }
    return sb.toString();
}

From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPMessage.java

License:Apache License

/**
 * Convenience method for reading a {@link ZMTPMessage} from a {@link ByteBuf}.
 *//*from  w  w  w .  j  a  v a  2s .c om*/
public static ZMTPMessage read(final ByteBuf in, final ZMTPVersion version) throws ZMTPParsingException {
    final int mark = in.readerIndex();
    final ZMTPWireFormat wireFormat = ZMTPWireFormats.wireFormat(version);
    final ZMTPWireFormat.Header header = wireFormat.header();
    final RecyclableArrayList frames = RecyclableArrayList.newInstance();
    while (true) {
        final boolean read = header.read(in);
        if (!read) {
            frames.recycle();
            in.readerIndex(mark);
            return null;
        }
        if (in.readableBytes() < header.length()) {
            frames.recycle();
            in.readerIndex(mark);
            return null;
        }
        if (header.length() > Integer.MAX_VALUE) {
            throw new ZMTPParsingException("frame is too large: " + header.length());
        }
        final ByteBuf frame = in.readSlice((int) header.length());
        frame.retain();
        frames.add(frame);
        if (!header.more()) {
            @SuppressWarnings("unchecked")
            final ZMTPMessage message = ZMTPMessage.from((List<ByteBuf>) (Object) frames);
            frames.recycle();
            return message;
        }
    }
}

From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPMessageEncoder.java

License:Apache License

@Override
public void encode(final Object msg, final ZMTPWriter writer) {
    final ZMTPMessage message = (ZMTPMessage) msg;
    for (int i = 0; i < message.size(); i++) {
        final ByteBuf frame = message.frame(i);
        final boolean more = i < message.size() - 1;
        final ByteBuf dst = writer.frame(frame.readableBytes(), more);
        dst.writeBytes(frame, frame.readerIndex(), frame.readableBytes());
    }//from w w w  .ja va 2  s . co  m
}

From source file:com.streamsets.pipeline.lib.parser.net.DelimitedLengthFieldBasedFrameDecoder.java

License:Apache License

public DelimitedLengthFieldBasedFrameDecoder(int maxFrameLength, int lengthAdjustment, boolean failFast,
        ByteBuf delimiter, Charset lengthFieldCharset, boolean trimLengthString) {
    if (delimiter == null) {
        throw new NullPointerException("delimiter");
    }//  ww w . j a  va 2 s.  c  o  m
    if (!delimiter.isReadable()) {
        throw new IllegalArgumentException("empty delimiter");
    }

    this.delimiter = delimiter.slice(delimiter.readerIndex(), delimiter.readableBytes());
    this.lengthFieldCharset = lengthFieldCharset;

    this.maxFrameLength = maxFrameLength;
    this.lengthAdjustment = lengthAdjustment;
    this.failFast = failFast;
    this.trimLengthString = trimLengthString;
}

From source file:com.streamsets.pipeline.lib.parser.net.DelimitedLengthFieldBasedFrameDecoder.java

License:Apache License

/**
 * Create a frame out of the {@link ByteBuf} and return it.
 *
 * @param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
 * @param in the {@link ByteBuf} from which to read data
 * @return frame           the {@link ByteBuf} which represent the frame or {@code null} if no frame could
 * be created.//from   w  w w  . ja  v  a2 s .  c  o  m
 */
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    if (discardingTooLongFrame) {
        long bytesToDiscard = this.bytesToDiscard;
        int localBytesToDiscard = (int) Math.min(bytesToDiscard, in.readableBytes());
        in.skipBytes(localBytesToDiscard);
        bytesToDiscard -= localBytesToDiscard;
        this.bytesToDiscard = bytesToDiscard;

        failIfNecessary(false);
        return null;
    }

    if (consumingLength) {
        int delimIndex = indexOf(in, delimiter);
        if (delimIndex < 0) {
            return null;
        }

        final String lengthStr = in.toString(in.readerIndex(), delimIndex, lengthFieldCharset);
        try {
            frameLength = Long.parseLong(trimLengthString ? lengthStr.trim() : lengthStr);
        } catch (NumberFormatException e) {
            throw new CorruptedFrameException(String.format("Invalid length field decoded (in %s charset): %s",
                    lengthFieldCharset.name(), lengthStr), e);
        }

        if (frameLength < 0) {
            throw new CorruptedFrameException("negative pre-adjustment length field: " + frameLength);
        }

        frameLength += lengthAdjustment;

        //consume length field and delimiter bytes
        in.skipBytes(delimIndex + delimiter.capacity());

        //consume delimiter bytes
        consumingLength = false;
    }

    if (frameLength > maxFrameLength) {
        long discard = frameLength - in.readableBytes();
        tooLongFrameLength = frameLength;

        if (discard < 0) {
            // buffer contains more bytes then the frameLength so we can discard all now
            in.skipBytes((int) frameLength);
        } else {
            // Enter the discard mode and discard everything received so far.
            discardingTooLongFrame = true;
            consumingLength = true;
            bytesToDiscard = discard;
            in.skipBytes(in.readableBytes());
        }
        failIfNecessary(true);
        return null;
    }

    // never overflows because it's less than maxFrameLength
    int frameLengthInt = (int) frameLength;
    if (in.readableBytes() < frameLengthInt) {
        // need more bytes available to read actual frame
        return null;
    }

    // the frame is now entirely present, reset state vars
    consumingLength = true;
    frameLength = 0;

    // extract frame
    int readerIndex = in.readerIndex();
    int actualFrameLength = frameLengthInt;// - initialBytesToStrip;
    ByteBuf frame = extractFrame(ctx, in, readerIndex, actualFrameLength);
    in.readerIndex(readerIndex + actualFrameLength);
    return frame;
}

From source file:com.streamsets.pipeline.lib.parser.net.DelimitedLengthFieldBasedFrameDecoder.java

License:Apache License

/**
 * Returns the number of bytes between the readerIndex of the haystack and
 * the first needle found in the haystack.  -1 is returned if no needle is
 * found in the haystack.//  w  w  w.j a  va2s.  c  om
 */
private static int indexOf(ByteBuf haystack, ByteBuf needle) {
    for (int i = haystack.readerIndex(); i < haystack.writerIndex(); i++) {
        int haystackIndex = i;
        int needleIndex;
        for (needleIndex = 0; needleIndex < needle.capacity(); needleIndex++) {
            if (haystack.getByte(haystackIndex) != needle.getByte(needleIndex)) {
                break;
            } else {
                haystackIndex++;
                if (haystackIndex == haystack.writerIndex() && needleIndex != needle.capacity() - 1) {
                    return -1;
                }
            }
        }

        if (needleIndex == needle.capacity()) {
            // Found the needle from the haystack!
            return i - haystack.readerIndex();
        }
    }
    return -1;
}

From source file:com.talent.balance.common.ParseUtils.java

License:Open Source License

public static int processReadIndex(ByteBuf buffer) {
    int newReaderIndex = buffer.readerIndex();
    if (newReaderIndex < (buffer.capacity())) {
        buffer.readerIndex(newReaderIndex + 1);
        return 1;
    }//  w  w w.ja  v a  2  s . co  m
    return 0;
}

From source file:com.talent.mysql.packet.MysqlResponsePacket.java

License:Open Source License

public PacketWithMeta<Packet> decode(ByteBuf byteBuf) throws DecodeException {
    int capacity = byteBuf.capacity();
    PacketWithMeta<Packet> packetWithMeta = null;
    while (true) {
        if ((capacity - byteBuf.readerIndex()) < MysqlHeader.HEADER_LEN) //?
        {/*from w ww .  ja v  a  2  s . co  m*/
            if (packetWithMeta != null) {
                packetWithMeta.setPacketLenght(byteBuf.readerIndex());
            }

            return packetWithMeta;
        }

        if (byteBuf.order() == ByteOrder.BIG_ENDIAN) {
            byteBuf = byteBuf.order(ByteOrder.LITTLE_ENDIAN);
        }

        MysqlHeader header = MysqlHeaderFactory.borrow();
        header.decode(byteBuf);

        ParseUtils.processReadIndex(byteBuf);

        //?
        if (capacity - byteBuf.readerIndex() < header.getBodyLength()) //?
        {
            if (packetWithMeta != null) {
                packetWithMeta.setPacketLenght(byteBuf.readerIndex());
            }
            return packetWithMeta;
        } else {
            T t = decodeBody(byteBuf, header);
            if (packetWithMeta == null) {
                packetWithMeta = new PacketWithMeta<Packet>();

                List<Packet> packets = new ArrayList<Packet>();
                packets.add(t);

                packetWithMeta.setPackets(packets);
                packetWithMeta.setPacketLenght(byteBuf.readerIndex());
                return packetWithMeta;

                //               com.talent.mysql.packet.factory.MysqlHeaderFactory.returnObj(t.getMysqlHeader());
            } else {
                packetWithMeta.getPackets().add(t);
            }
        }
    }

}

From source file:com.talent.mysql.packet.request.AuthPacket.java

License:Open Source License

@Override
public void encodeBody(ByteBuf byteBuf) {
    int index = byteBuf.readerIndex();
    String xx = Long.toBinaryString(clientFlags);
    byteBuf.setLong(index, clientFlags);
    index += 4;//from   w w w . ja  va  2s  . c o m

    byteBuf.setLong(index, maxPacketSize);
    index += 4;

    byteBuf.setByte(index, charsetIndex);
    index++;

    byteBuf.setBytes(index, extra);
    index += extra.length;

    byteBuf.setBytes(index, user);
    index += user.length;

    byteBuf.setByte(index, 0);
    index++;

    byteBuf.setByte(index, passwordLen);
    index++;

    byteBuf.setBytes(index, password);
    index += password.length;

    byteBuf.setBytes(index, database);
    index += database.length;

    byteBuf.setByte(index, 0);
    index++;
}

From source file:com.talent.mysql.packet.request.AuthPacket.java

License:Open Source License

public void decodeBody(ByteBuf _byteBuf) {
    byte[] bs = new byte[] { -117, -93, 2, 0, 0, 0, 0, 64, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 0, 0, 0, 0, 114, 111, 111, 116, 0, 20, -19, -111, -3, 39, -46, -116, -128, -44, -112, -26,
            -48, 42, 70, -85, 8, 83, 83, 100, 103, 68, 116, 97, 108, 101, 110, 116, 95, 98, 97, 115, 101, 119,
            101, 98, 50, 48, 49, 0 };/*  ww w . ja v a 2 s  .  c o m*/
    ByteBuf byteBuf = Unpooled.buffer(bs.length);
    byteBuf = byteBuf.order(ByteOrder.LITTLE_ENDIAN);
    byteBuf.setBytes(0, bs, 0, bs.length);

    int _index = byteBuf.readerIndex();
    int index = _index;

    clientFlags = byteBuf.getInt(index); //172939
    index += 4;

    maxPacketSize = byteBuf.getInt(index); //1073741824
    index += 4;

    charsetIndex = byteBuf.getByte(index); //33
    index += 1;

    index += extra.length;

    int len = 0;
    while (byteBuf.getByte(index + len) != 0) {
        len++;
    }
    user = new byte[len];
    byteBuf.getBytes(index, user, 0, len);
    index += len;
    index++;

    passwordLen = byteBuf.getByte(index);
    index += 1;

    password = new byte[passwordLen];
    byteBuf.getBytes(index, password, 0, passwordLen);

    len = 0;
    while (byteBuf.getByte(index + len) != 0) {
        len++;
    }
    database = new byte[len];
    byteBuf.getBytes(index, database, 0, len);
    index += len;
    index++;

}