Example usage for io.netty.buffer ByteBuf order

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

Introduction

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

Prototype

@Deprecated
public abstract ByteBuf order(ByteOrder endianness);

Source Link

Document

Returns a buffer with the specified endianness which shares the whole region, indexes, and marks of this buffer.

Usage

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  ww  w.j ava 2s .c  o m
 * @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.talent.mysql.packet.request.AuthPacket.java

License:Open Source License

/**
 * @param args/*  ww w  .  j  av  a  2s  .  c  o m*/
 */
public static void main(String[] args) {
    AuthPacket authPacket1 = new AuthPacket();
    authPacket1.decodeBody(null);

    byte[] bs = new byte[] { 82, 0, 0, 0, 10, 49, 48, 46, 48, 46, 49, 45, 77, 97, 114, 105, 97, 68, 66, 0, -98,
            1, 0, 0, 110, 104, 61, 56, 64, 122, 101, 107, 0, -1, -9, 8, 2, 0, 15, -96, 21, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 105, 78, 41, 35, 111, 43, 39, 124, 98, 82, 87, 60, 0, 109, 121, 115, 113, 108, 95, 110, 97,
            116, 105, 118, 101, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0 };
    ByteBuf byteBuf = Unpooled.buffer(bs.length);
    byteBuf = byteBuf.order(ByteOrder.LITTLE_ENDIAN);

    byteBuf.setBytes(0, bs);

    HandshakePacket handshakePacket = new HandshakePacket();
    try {
        handshakePacket.decode(byteBuf);
        byteBuf.readerIndex(0);
    } catch (DecodeException e) {
        e.printStackTrace();
    }

    BackendConf backendConf = BackendConf.getInstance();
    BackendServerConf backendServerConf = backendConf.getServers()[0];

    AuthPacket authPacket = new AuthPacket();
    authPacket.charsetIndex = (byte) (handshakePacket.charset & 0xff);
    authPacket.user = backendServerConf.getProps().get("user").getBytes();
    try {
        authPacket.password = getPass(backendServerConf.getProps().get("pwd"), handshakePacket);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    authPacket.passwordLen = (byte) authPacket.password.length;
    authPacket.database = backendServerConf.getProps().get("db").getBytes();
    ByteBuf byteBuf1 = authPacket.encode();
    System.out.println(Arrays.toString(byteBuf1.array()));

}

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 a va 2 s  .com
    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++;

}

From source file:com.talent.mysql.packet.response.HandshakePacket.java

License:Open Source License

/**
 * @param args//from  w ww . j  a  va  2s. c om
 * @throws DecodeException
 */
public static void main(String[] args) {
    byte[] bs = new byte[] { 82, 0, 0, 0, 10, 49, 48, 46, 48, 46, 49, 45, 77, 97, 114, 105, 97, 68, 66, 0, -98,
            1, 0, 0, 110, 104, 61, 56, 64, 122, 101, 107, 0, -1, -9, 8, 2, 0, 15, -96, 21, 0, 0, 0, 0, 0, 0, 0,
            0, 0, 0, 105, 78, 41, 35, 111, 43, 39, 124, 98, 82, 87, 60, 0, 109, 121, 115, 113, 108, 95, 110, 97,
            116, 105, 118, 101, 95, 112, 97, 115, 115, 119, 111, 114, 100, 0 };
    ByteBuf byteBuf = Unpooled.buffer(bs.length);
    byteBuf = byteBuf.order(ByteOrder.LITTLE_ENDIAN);

    byteBuf.setBytes(0, bs);

    HandshakePacket handshakePacket = new HandshakePacket();
    try {
        handshakePacket.decode(byteBuf);
        byteBuf.readerIndex(0);

        handshakePacket.decode(byteBuf);
        byteBuf.readerIndex(0);

        handshakePacket.decode(byteBuf);
        byteBuf.readerIndex(0);

        handshakePacket.decode(byteBuf);
        byteBuf.readerIndex(0);
    } catch (DecodeException e) {
        e.printStackTrace();
    }

}

From source file:com.talent.nio.communicate.receive.DecodeRunnable.java

License:Open Source License

@Override
public void run() {
    while (getMsgQueue().size() > 0) {
        ByteBuf queuedatas = null;
        CompositeByteBuf datas = Unpooled.compositeBuffer();

        if (lastDatas != null) {
            channelContext.getStatVo().setCurrentOgnzTimestamp(SystemTimer.currentTimeMillis());
            lastDatas.readerIndex(0);//w  w  w . j a  v a2  s.co m
            datas.addComponents(lastDatas);
            lastDatas = null;
        }

        int count = 0;

        label_2: while ((queuedatas = getMsgQueue().poll()) != null) {
            queuedatas = queuedatas.order(channelContext.getByteOrder());

            if (DebugUtils.isNeedDebug(channelContext)) {
                // long xx = 999999999999999999L;
                log.error("queuedatas:" + ArrayUtils.toString(queuedatas));
            }
            datas.addComponents(queuedatas);
            channelContext.getStatVo().setCurrentOgnzTimestamp(SystemTimer.currentTimeMillis());
            count++;

            if (needLength != -1) // ????
            {
                if (datas.capacity() < needLength) // ??
                {
                    //                        log.error("??----capacity:{}, needLength:{}", datas.capacity(), needLength);
                    continue;
                } else {
                    //                        log.error("?----capacity:{}, needLength:{}", datas.capacity(), needLength);
                    break label_2;
                }

            } else
            // ???
            {
                if (count == 50) {
                    log.warn(
                            "???{}???{}",
                            count, getMsgQueue().size());
                    break label_2;
                }
            }
        }
        channelContext.getStatVo().setCurrentOgnzTimestamp(SystemTimer.currentTimeMillis());

        PacketWithMeta packetWithMeta = null;
        try {
            // ByteBuffer buffer = ByteBuffer.wrap(datas);
            datas.writerIndex(datas.capacity());
            datas.readerIndex(0);
            packetWithMeta = channelContext.getDecoder().decode(datas, channelContext);
            needLength = -1;
            if (packetWithMeta == null) { // ???
                lastDatas = datas;
                lastDatas.readerIndex(0);

                if (DebugUtils.isNeedDebug(channelContext)) {
                    log.error("???:{}", lastDatas);
                }
            } else if (packetWithMeta.getPackets() == null || packetWithMeta.getPackets().size() == 0) {
                // ???
                lastDatas = datas;
                lastDatas.readerIndex(0);
                needLength = packetWithMeta.getNeedLength();
                if (DebugUtils.isNeedDebug(channelContext)) {
                    log.error("????:{}", needLength);
                }
            } else {
                int len = packetWithMeta.getPacketLenght();
                // lastDatas = new byte[datas.capacity() - len];
                // System.arraycopy(datas, len, lastDatas, 0,
                // lastDatas.length);

                if (datas.capacity() - len > 0) {

                    lastDatas = datas.copy(len, datas.capacity() - len);
                    if (DebugUtils.isNeedDebug(channelContext)) {
                        log.error("??:{}, {}", datas.capacity() - len, lastDatas);
                    }
                } else {
                    lastDatas = null;
                    if (DebugUtils.isNeedDebug(channelContext)) {
                        log.error("??:{}", lastDatas);
                    }
                }
                processMsgAndStat(packetWithMeta.getPackets(), len, false);
            }

        } catch (DecodeException e) {
            log.error(e.getMessage(), e);
            channelContext.getErrorPackageHandler().handle(channelContext.getSocketChannel(), channelContext,
                    e.getMessage());
        }
    }

}

From source file:com.tesora.dve.db.mysql.libmy.MyBinaryResultRow.java

License:Open Source License

@Override
public void unmarshallMessage(ByteBuf cb) throws PEException {
    int expectedFieldCount = fieldConverters.size();
    int expectedBitmapLength = MyNullBitmap.computeSize(expectedFieldCount, MyNullBitmap.BitmapType.RESULT_ROW);
    cb = cb.order(ByteOrder.LITTLE_ENDIAN);
    cb.skipBytes(1);//skip the bin row marker.

    byte[] nullBitmap = new byte[expectedBitmapLength];
    cb.readBytes(nullBitmap);//w  ww  .jav a2 s  . com
    MyNullBitmap resultBitmap = new MyNullBitmap(nullBitmap, expectedFieldCount,
            MyNullBitmap.BitmapType.RESULT_ROW);

    ByteBuf values = cb;

    for (int i = 0; i < expectedFieldCount; i++) {
        ByteBuf existing = fieldSlices.get(i);
        ByteBuf nextSlice = null;
        int startIndex = values.readerIndex();
        if (!resultBitmap.getBit(i + 1)) {
            fieldConverters.get(i).readObject(values);//TODO: we throw out the unmarshalled value, we could cache it.
            int endingOffset = values.readerIndex();
            nextSlice = values.slice(startIndex, endingOffset - startIndex);
        }

        if (existing != null)
            existing.release();
        fieldSlices.set(i, nextSlice);
    }
    if (cb.readableBytes() > 0) {
        log.warn("Decoded binary row had {} leftover bytes, re-encoding may fail.", cb.readableBytes());
        cb.skipBytes(cb.readableBytes());//consume rest of buffer.
    }
}

From source file:com.tesora.dve.db.mysql.libmy.MyErrorResponse.java

License:Open Source License

public static PESQLStateException asException(ByteBuf in) {

    ByteBuf cb = in.order(ByteOrder.LITTLE_ENDIAN);
    cb.skipBytes(1); // error header
    int errorNumber = cb.readUnsignedShort();
    cb.skipBytes(1); // sqlState header
    String sqlState = MysqlAPIUtils.readBytesAsString(cb, 5, CharsetUtil.UTF_8);
    String errorMsg = MysqlAPIUtils.readBytesAsString(cb, CharsetUtil.UTF_8);
    return new PESQLStateException(errorNumber, sqlState, errorMsg);
}

From source file:com.tesora.dve.db.mysql.libmy.MyMessage.java

License:Open Source License

public void marshallPayload(ByteBuf destination) {
    destination = destination.order(ByteOrder.LITTLE_ENDIAN);

    if (this.isMessageTypeEncoded())
        destination.writeByte(this.getMessageType().getByteValue());

    this.marshallMessage(destination);
}

From source file:com.tesora.dve.db.mysql.libmy.MyOKResponse.java

License:Open Source License

@Override
public void marshallMessage(ByteBuf in) {
    ByteBuf cb = in.order(ByteOrder.LITTLE_ENDIAN);
    cb.writeByte(0); // field_count - spec says this is always 0
    MysqlAPIUtils.putLengthCodedLong(cb, affectedRows);
    MysqlAPIUtils.putLengthCodedLong(cb, insertId);
    cb.writeShort(serverStatus);// w  w w  . j a v a  2 s . c o m
    cb.writeShort(warningCount);
    if (message != null && message.length() > 0) {
        cb.writeBytes(message.getBytes());
    }
}

From source file:com.tesora.dve.db.mysql.portal.protocol.MSPAuthenticateV10MessageMessage.java

License:Open Source License

public static void write(ByteBuf out, String userName, String userPassword, String salt, Charset charset,
        int mysqlCharsetID, int capabilitiesFlag) {
    ByteBuf leBuf = out.order(ByteOrder.LITTLE_ENDIAN);

    int payloadSizeIndex = leBuf.writerIndex();
    leBuf.writeMedium(0);//from   w  w w  .j a v  a 2 s  .c o  m
    leBuf.writeByte(1);
    int payloadStartIndex = leBuf.writerIndex();
    leBuf.writeInt(capabilitiesFlag);
    leBuf.writeInt(MAX_PACKET_SIZE);
    //      leBuf.writeByte(serverGreeting.getServerCharsetId());
    leBuf.writeByte(mysqlCharsetID);
    leBuf.writeZero(23);
    leBuf.writeBytes(userName.getBytes(charset));
    leBuf.writeZero(1);

    if ((capabilitiesFlag & ClientCapabilities.CLIENT_SECURE_CONNECTION) > 0) {

        byte[] securePassword = computeSecurePassword(userPassword, salt);
        leBuf.writeByte(securePassword.length);
        leBuf.writeBytes(securePassword);
    } else {
        leBuf.writeBytes(userPassword.getBytes(charset));
        leBuf.writeZero(1);
    }

    leBuf.setMedium(payloadSizeIndex, leBuf.writerIndex() - payloadStartIndex);
}