Example usage for io.netty.buffer ByteBuf getByte

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

Introduction

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

Prototype

public abstract byte getByte(int index);

Source Link

Document

Gets a byte at the specified absolute index in this buffer.

Usage

From source file:com.neoba.MessageInterpreter.java

MessageInterpreter(ChannelHandlerContext ctx, ByteBuf buff) {

    VERSION = buff.getByte(0);
    type = buff.getByte(1);//from  w ww .j a  va2s.c om
    size = buff.getInt(2);
    if (type != Constants.PINGPONG && type != Constants.USER_CREATE && type != Constants.USER_LOGIN
            && type != Constants.FACEBOOK_USER_CREATE && type != Constants.FACEBOOK_USER_LOGIN) {
        sessid = new UUID(buff.getLong(14), buff.getLong(6));
        if (isloggedin()) {
            logger.info("Authenticated message from user " + Dsyncserver.usersessions.get(sessid)
                    + " with session " + sessid);
        }
    } else {
        sessid = null;
    }
    this.buff = buff;
    this.ctx = ctx;
}

From source file:com.netflix.iep.http.NetflixJsonObjectDecoder.java

License:Apache License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (state == ST_CORRUPTED) {
        in.skipBytes(in.readableBytes());
        return;//w  w  w. ja va  2 s  . c  o  m
    }

    if (LOGGER.isTraceEnabled()) {
        byte[] bytes = new byte[in.readableBytes()];
        in.getBytes(in.readerIndex(), bytes, 0, in.readableBytes());
        LOGGER.trace("starting [" + in.readerIndex() + ":" + in.readableBytes() + "]:" + new String(bytes));
    }

    // index of next byte to process.
    int len = this.len;
    int wrtIdx = in.writerIndex();

    for (; in.readerIndex() + len < wrtIdx; len++) {
        if (len > maxObjectLength) {
            // buffer size exceeded maxObjectLength; discarding the complete buffer.
            in.skipBytes(in.readableBytes());
            reset();
            throw new TooLongFrameException(
                    "object length exceeds " + maxObjectLength + ": " + len + " bytes discarded");
        }
        byte c = in.getByte(in.readerIndex() + len);
        if (state == ST_DECODING_NORMAL) {
            decodeByte(c, in, in.readerIndex() + len);

            // All opening braces/brackets have been closed. That's enough to conclude
            // that the JSON object/array is complete.
            if (openBraces == 0) {
                ByteBuf json = extractObject(ctx, in, in.readerIndex(), len + 1);
                if (json != null) {
                    out.add(json);
                }

                // The JSON object/array was extracted => discard the bytes from
                // the input buffer.
                in.readerIndex(in.readerIndex() + len + 1);
                len = 0;
                // Reset the object state to get ready for the next JSON object/text
                // coming along the byte stream.
                reset();
                break;
            }
        } else if (state == ST_DECODING_ARRAY_STREAM) {
            if (len == 0 && Character.isWhitespace(c)) {
                in.skipBytes(1);
                len--;
            }
            decodeByte(c, in, in.readerIndex() + len);
            if (!insideString && (openBraces == 1 && c == ',' || openBraces == 0 && c == ']')) {
                ByteBuf json = extractObject(ctx, in, in.readerIndex(), len);
                if (json != null) {
                    out.add(json);
                }

                in.readerIndex(in.readerIndex() + len + 1);
                len = 0;

                if (c == ']') {
                    reset();
                }
                break;
            }
            // JSON object/array detected. Accumulate bytes until all braces/brackets are closed.
        } else if (c == '{' || c == '[') {
            initDecoding(c);

            if (state == ST_DECODING_ARRAY_STREAM) {
                // Discard the array bracket
                in.skipBytes(1);
                len--;
            }
            // Discard leading spaces in front of a JSON object/array.
        } else if (Character.isWhitespace(c)) {
            in.skipBytes(1);
            len--;
        } else {
            state = ST_CORRUPTED;
            throw new CorruptedFrameException("invalid JSON received at byte position "
                    + (in.readerIndex() + len) + ": " + ByteBufUtil.hexDump(in));
        }
    }

    this.len = len;

    if (LOGGER.isTraceEnabled()) {
        byte[] bytes = new byte[in.readableBytes()];
        in.getBytes(in.readerIndex(), bytes, 0, in.readableBytes());
        LOGGER.trace("remainder [" + in.readerIndex() + ":" + in.readableBytes() + "]:" + new String(bytes));
    }
}

From source file:com.quavo.osrs.network.protocol.codec.update.encrypt.XOREncryptionEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, XOREncryptionResponse msg, ByteBuf out) throws Exception {
    if (msg.getKey() != 0) {
        for (int i = 0; i < out.writerIndex(); i++) {
            out.setByte(i, out.getByte(i) ^ msg.getKey());
        }/*  www .j  av a  2 s .  c  o m*/
    }

    ctx.pipeline().remove(this);
}

From source file:com.shouxun.server.netty.tcp.EchoServerHandler.java

License:Apache License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {

    ByteBuf buffer = (ByteBuf) msg;

    for (int i = 0; i < buffer.capacity(); i++) {
        byte b = buffer.getByte(i);
        sb.append((char) b);
    }//w w w  .j a v  a2 s  .  c  o  m
    buffer.release();
}

From source file:com.spotify.netty.handler.codec.zmtp.ZMTPUtils.java

License:Apache License

/**
 * Create a string from binary data, keeping printable ascii and hex encoding everything else.
 *
 * @param data The data/*  w w  w  .j  a va2 s  . c o  m*/
 * @return A string representation of the data
 */
public 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.benchmarks.CustomReqRepBenchmark.java

License:Apache License

private static boolean asciiEquals(final AsciiString s, final ByteBuf data, final int size) {
    final int ix = data.readerIndex();
    if (size != s.length()) {
        return false;
    }//from  ww w .  j  a v a  2s .c  om
    for (int i = 0; i < size; i++) {
        char c = (char) data.getByte(ix + i);
        if (c != s.charAt(i)) {
            return false;
        }
    }
    return true;
}

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.streamsets.pipeline.lib.parser.collectd.CollectdParser.java

License:Apache License

/**
 * Parses the value part of the packet where metrics are located
 *
 * @param startOffset beginning offset for this part
 * @param buf         buffered packet//from w  ww.  ja va2s. c  om
 * @return offset after consuming part
 */
private int parseValues(int startOffset, ByteBuf buf) throws OnRecordErrorException {
    int offset = startOffset;
    // N Values
    // For each Value:
    // 1 byte data type code
    int numValues = buf.getUnsignedShort(offset); // 4-5
    offset += 2;

    List<Byte> types = new ArrayList<>(numValues);

    while (numValues-- > 0) {
        types.add(buf.getByte(offset));
        offset += 1;
    }

    for (int i = 0; i < types.size(); i++) {
        Byte type = types.get(i);
        String label = getValueLabel(i, type);
        switch (type) {
        case COUNTER:
            fields.put(label, Field.create(buf.getUnsignedInt(offset)));
            offset += 8;
            break;
        case GAUGE:
            fields.put(label, Field.create(buf.order(ByteOrder.LITTLE_ENDIAN).getDouble(offset)));
            offset += 8;
            break;
        case DERIVE:
            fields.put(label, Field.create(buf.getLong(offset)));
            offset += 8;
            break;
        case ABSOLUTE:
            fields.put(label, Field.create(buf.getUnsignedInt(offset)));
            offset += 8;
            break;
        default:
            // error
            throw new OnRecordErrorException(Errors.COLLECTD_01, type);
        }
    }
    return offset;
}

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 .java 2  s  . co m
 */
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.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 };//from   w  w w  .  j  av a2s.  co  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++;

}