Example usage for io.netty.buffer ByteBuf readByte

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

Introduction

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

Prototype

public abstract byte readByte();

Source Link

Document

Gets a byte at the current readerIndex and increases the readerIndex by 1 in this buffer.

Usage

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

License:Apache License

/**
 * Read enough bytes from buffer to deduce the remote protocol version in a backwards compatible
 * ZMTP handshake./*  ww  w .j  av  a2  s.  c  o  m*/
 *
 * @param in the buffer of data to determine version from.
 * @return The detected {@link ZMTPVersion}.
 * @throws IndexOutOfBoundsException if there is not enough data available in buffer.
 */
static ZMTPVersion detectProtocolVersion(final ByteBuf in) {
    if (in.readByte() != (byte) 0xff) {
        return ZMTPVersion.ZMTP10;
    }
    in.skipBytes(8);
    if ((in.readByte() & 0x01) == 0) {
        return ZMTPVersion.ZMTP10;
    }
    return ZMTPVersion.ZMTP20;
}

From source file:com.srotya.sidewinder.core.ingress.binary.SeriesDataPointDecoder.java

License:Apache License

public static DataPoint decodeBufToDPoint(ByteBuf buf) {
    int dbNameLength = buf.readInt();
    if (dbNameLength < 0) {
        return null;
    }/*from  www. j  av a2 s.  co m*/
    byte[] dbBytes = new byte[dbNameLength];
    buf.readBytes(dbBytes);
    String dbName = new String(dbBytes);
    int measurementNameLength = buf.readInt();
    if (measurementNameLength < 0) {
        return null;
    }
    byte[] measurementNameBytes = new byte[measurementNameLength];
    buf.readBytes(measurementNameBytes);
    String measurementName = new String(measurementNameBytes);

    int valueNameLength = buf.readInt();
    if (valueNameLength < 0) {
        return null;
    }
    byte[] valueNameBytes = new byte[valueNameLength];
    buf.readBytes(valueNameBytes);
    String valueFieldName = new String(valueNameBytes);
    long timestamp = buf.readLong();
    byte flag = buf.readByte();
    DataPoint dp;
    if (flag == '0') {
        double value = buf.readDouble();
        dp = new DataPoint(dbName, measurementName, valueFieldName, null, timestamp, value);
        dp.setFp(true);
    } else {
        long value = buf.readLong();
        dp = new DataPoint(dbName, measurementName, valueFieldName, null, timestamp, value);
    }
    return dp;
}

From source file:com.streamsets.pipeline.lib.parser.net.netflow.v5.NetflowV5Decoder.java

License:Apache License

@Override
public List<NetflowV5Message> parse(int netflowVersion, int packetLength, boolean packetLengthCheck,
        ByteBuf buf, InetSocketAddress sender, InetSocketAddress recipient) throws OnRecordErrorException {
    if (!readHeader) {
        // 2-3//from   w ww . jav a2  s. co  m
        count = buf.readUnsignedShort();
        if (count <= 0) {
            throw new OnRecordErrorException(Errors.NETFLOW_01, Utils.format("Count is invalid: {}", count));
        } else if (packetLengthCheck && packetLength < V5_HEADER_SIZE + count * V5_FLOW_SIZE) {
            String msg = Utils.format("Readable bytes {} too small for count {} (max {})", packetLength, count,
                    (V5_HEADER_SIZE + count * V5_FLOW_SIZE));
            throw new OnRecordErrorException(Errors.NETFLOW_01, msg);
        }
        readerId = String.valueOf(recipient);
        // 4-7
        uptime = buf.readUnsignedInt();
        // 8-11
        seconds = buf.readUnsignedInt();
        // 12-15
        nanos = buf.readUnsignedInt();

        millis = nanos / 1000000;

        // java timestamp, which is milliseconds
        timestamp = (seconds * 1000L) + millis;
        packetId = UUIDs.startOfJavaTimestamp(timestamp);

        // 16-19
        flowSequence = buf.readUnsignedInt();
        // 20
        engineType = buf.readUnsignedByte();
        // 21
        engineId = buf.readUnsignedByte();
        // the first 2 bits are the sampling mode, the remaining 14 the interval
        // 22-23
        sampling = buf.readUnsignedShort();
        samplingInterval = sampling & 0x3FFF;
        samplingMode = sampling >> 14;
        readHeader = true;
        parentDecoder.doCheckpoint();
    }

    while (readIndex < count) {
        //ByteBuf flowBuf = buf.slice(V5_HEADER_SIZE + (readIndex * V5_FLOW_SIZE), V5_FLOW_SIZE);

        NetflowV5Message msg = new NetflowV5Message();
        msg.setSeconds(seconds);
        msg.setNanos(nanos);
        msg.setCount(count);

        // 0
        int srcaddr = (int) buf.readUnsignedInt();
        // 4
        int dstaddr = (int) buf.readUnsignedInt();
        // 8
        int nexthop = (int) buf.readUnsignedInt();
        // 12
        msg.setSnmpInput(buf.readUnsignedShort());
        // 14
        msg.setSnmpOnput(buf.readUnsignedShort());

        msg.setPacketId(packetId.toString());
        msg.setSender((sender == null) ? "unknown" : sender.getAddress().toString());
        msg.setLength(packetLength);
        msg.setUptime(uptime);
        msg.setTimestamp(timestamp);
        msg.setFlowSequence(flowSequence);
        msg.setEngineId(engineId);
        msg.setEngineType(engineType);
        msg.setRawSampling(sampling);
        msg.setSamplingInterval(samplingInterval);
        msg.setSamplingMode(samplingMode);
        msg.setReaderId(readerId);

        // 16
        long packets = buf.readUnsignedInt();
        // 20
        long octets = buf.readUnsignedInt();
        // 24
        long first = buf.readUnsignedInt();
        msg.setRawFirst(first);
        if (first > 0) {
            msg.setFirst(timestamp - uptime + first);
        } else {
            msg.setFirst(0L);
        }

        // 28
        long last = buf.readUnsignedInt();
        msg.setRawLast(last);
        if (last > 0) {
            msg.setLast(timestamp - uptime + last);
        } else {
            msg.setLast(0L);
        }

        msg.setId(UUIDs.timeBased().toString());
        msg.setSrcAddr(srcaddr);
        msg.setDstAddr(dstaddr);
        msg.setNextHop(nexthop);
        msg.setSrcAddrString(NetflowCommonDecoder.ipV4ToString(srcaddr));
        msg.setDstAddrString(NetflowCommonDecoder.ipV4ToString(dstaddr));
        msg.setNexthopString(NetflowCommonDecoder.ipV4ToString(nexthop));
        // 32
        msg.setSrcPort(buf.readUnsignedShort());
        // 34
        msg.setDstPort(buf.readUnsignedShort());
        // 36 is "pad1" (unused zero bytes)
        buf.readByte();
        // 37
        msg.setTcpFlags(buf.readUnsignedByte());
        // 38
        msg.setProto(buf.readUnsignedByte());
        // 39
        msg.setTos(buf.readUnsignedByte());
        // 40
        msg.setSrcAs(buf.readUnsignedShort());
        // 42
        msg.setDstAs(buf.readUnsignedShort());
        // 44
        msg.setSrcMask(buf.readUnsignedByte());
        // 45
        msg.setDstMask(buf.readUnsignedByte());
        msg.setdPkts(packets);
        msg.setdOctets(octets);

        // 46-47 is "pad2" (unused zero bytes)
        buf.skipBytes(2);
        result.add(msg);
        readIndex++;
        parentDecoder.doCheckpoint();
    }

    // if we reached this point without any further Signal errors, we have finished consuming
    //checkpoint();
    LinkedList<NetflowV5Message> returnResults = new LinkedList<>(result);
    resetState();
    return returnResults;
}

From source file:com.superman.netty.handler.DiscardServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {/* w  w w  .  ja  va  2  s.com*/
        ByteBuf bb = (ByteBuf) msg;
        while (bb.isReadable()) {
            System.out.print((char) bb.readByte());
            System.out.flush();
        }
    } finally {
        // ((ByteBuf) msg).release();
        ReferenceCountUtil.release(msg);
    }
    LOGGER.info("?");
}

From source file:com.tesora.dve.db.mysql.common.MysqlAPIUtils.java

License:Open Source License

/**
 * Methods to read and write length coded dates in the Binary Protocol
 * /*from w ww. j ava 2 s.  c  om*/
 * if year, month, day, hour, minutes, seconds and micro_seconds are all 0,
 * length is 0 and no other field is sent if hour, minutes, seconds and
 * micro_seconds are all 0, length is 4 and no other field is sent if
 * micro_seconds is 0, length is 7 and micro_seconds is not sent otherwise
 * length is 11
 * 
 * Fields 
 *       length (1) -- number of bytes following (valid values: 0, 4, 7, 11) 
 *       year (2) -- year 
 *       month (1) -- month 
 *       day (1) -- day 
 *       hour (1) -- hour
 *       minute (1) -- minutes 
 *       second (1) -- seconds 
 *       micro_second (4) -- micro-seconds
 * 
 */
public static Date getLengthCodedDate(ByteBuf cb) throws PEException {
    final Calendar cal = Calendar.getInstance();
    cal.clear();

    short length = cb.readUnsignedByte();
    if (length >= 4) {
        cal.set(Calendar.YEAR, cb.readUnsignedShort());
        cal.set(Calendar.MONTH, cb.readByte() - 1); // MONTH is zero based
        cal.set(Calendar.DAY_OF_MONTH, cb.readByte());

        if (length >= 7) {
            cal.set(Calendar.HOUR_OF_DAY, cb.readByte());
            cal.set(Calendar.MINUTE, cb.readByte());
            cal.set(Calendar.SECOND, cb.readByte());
        }

        if (length == 11) {
            long microSeconds = cb.readUnsignedInt();
            cal.set(Calendar.MILLISECOND, (int) (microSeconds / 1000));
        }

        if (length > 11) {
            throw new PEException("Invalid length specified to date type (" + length + ")");
        }

        return cal.getTime();
    }

    return null;
}

From source file:com.tesora.dve.db.mysql.common.MysqlAPIUtils.java

License:Open Source License

/**
 * Methods to read and write length coded times in the Binary Protocol
 * //from   ww w.  j  av a 2  s.  c  o m
 * if days, hours, minutes, seconds and micro_seconds are all 0, length is 0
 * and no other field is sent
 * 
 * if micro_seconds is 0, length is 8 and micro_seconds is not sent
 * otherwise length is 12
 * 
 * Fields 
 *       length (1) -- number of bytes following (valid values: 0, 8, 12)
 *       is_negative (1) -- (1 if minus, 0 for plus) 
 *       days (4) -- days 
 *       hours (1) -- hours
 *       minutes (1) -- minutes
 *       seconds (1) -- seconds
 *       micro_seconds (4) -- micro-seconds
 */
public static Time getLengthCodedTime(ByteBuf cb) throws PEException {
    Calendar cal = Calendar.getInstance();
    cal.clear();
    short length = cb.readUnsignedByte();

    if (length == 0)
        return null;

    Time ret = null;

    if (length >= 8) {
        cb.skipBytes(1); // this is the sign - we are ignoring this for now
        cb.skipBytes(4); // this is "days" - we are ignoring this for now
        cal.set(Calendar.HOUR_OF_DAY, cb.readByte());
        cal.set(Calendar.MINUTE, cb.readByte());
        cal.set(Calendar.SECOND, cb.readByte());
        if (length == 12) {
            long microSeconds = cb.readUnsignedInt();
            cal.set(Calendar.MILLISECOND, (int) (microSeconds / 1000));
        }
        if (length > 12) {
            throw new PEException("Invalid length specified to date type (" + length + ")");
        }

        ret = new Time(cal.getTimeInMillis());
    }
    return ret;
}

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

License:Open Source License

private void unpackTypeInfo(ByteBuf cb) {
    int remainingPayload = cb.readableBytes();
    int charsetOffset = remainingPayload + CHARSET_OFFSET_RELATIVE_TO_EOF;
    cb.skipBytes(charsetOffset);//from   w  w w  . jav a2s .c om

    charset = cb.readByte();
    cb.skipBytes(1);
    column_length = cb.readInt();//TODO: this should be an unsigned int.  Will cause problems if length exceeds Integer.MAX_VALUE.
    column_type = MyFieldType.fromByte(cb.readByte());
    flags = cb.readShort();
    scale = cb.readByte();
    //plus two pad bytes of zero
}

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

License:Open Source License

@Override
public void unmarshallMessage(ByteBuf cb) {
    cb.readByte();
    setErrorNumber(cb.readShort());
    setErrorMsg(cb.slice().toString(charset));
}

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

License:Open Source License

@Override
public void unmarshallMessage(ByteBuf cb) {
    protocolVersion = cb.readByte();
    serverVersion = cb.readSlice(cb.bytesBefore((byte) 0)).toString(CharsetUtil.UTF_8);
    cb.skipBytes(1); // skip the NULL terminator
    threadID = cb.readInt();//www  .  j a v  a 2 s . c  om
    scrambleBuffer1st = MysqlAPIUtils.readBytesAsString(cb, 8, CharsetUtil.ISO_8859_1);
    cb.skipBytes(1);
    long sc1 = cb.readUnsignedShort();
    serverCharset = cb.readByte();
    serverStatus = cb.readShort();
    long sc2 = Long.rotateLeft(cb.readUnsignedShort(), 16);
    setServerCapabilities(sc1 + sc2);
    scrambleBufferSize = new Integer(cb.readByte());
    cb.skipBytes(10); //unused bytes
    scrambleBuffer2nd = cb.readSlice(cb.bytesBefore((byte) 0)).toString(CharsetUtil.ISO_8859_1);
    cb.skipBytes(1);
    if ((serverCapabilitiesasLong
            & ClientCapabilities.CLIENT_PLUGIN_AUTH) == ClientCapabilities.CLIENT_PLUGIN_AUTH) {
        plugInProvidedData = cb.readSlice(cb.bytesBefore((byte) 0)).toString(CharsetUtil.UTF_8);
    }
}

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

License:Open Source License

@Override
public void unmarshallMessage(ByteBuf cb) {
    clientCapabilities = cb.readUnsignedInt();
    boolean hasConnectDatabase = ((clientCapabilities
            & ClientCapabilities.CLIENT_CONNECT_WITH_DB) == ClientCapabilities.CLIENT_CONNECT_WITH_DB);
    maxPacketSize = cb.readInt();/*from  w w w.j av a  2 s  .com*/
    clientCharset = cb.readByte();

    cb.skipBytes(23); // login request has a 23 byte filler
    username = cb.readSlice(cb.bytesBefore((byte) 0)).toString(CharsetUtil.UTF_8);
    cb.skipBytes(1); // skip the NULL terminator
    byte passwordLength = cb.readByte();
    byte[] passwordBytes = new byte[passwordLength];
    cb.getBytes(cb.readerIndex(), passwordBytes, 0, passwordLength);
    password = new String(passwordBytes, CharsetUtil.ISO_8859_1);
    cb.skipBytes(passwordLength);
    // if the clientCapabilities flag has the CLIENT_CONNECT_WITH_DB bit set,
    // then this message contains an initial database to connect to
    if (hasConnectDatabase) {
        database = cb.readSlice(cb.bytesBefore((byte) 0)).toString(CharsetUtil.UTF_8);
        if (database.length() < 1) {
            database = null;
        }
    }
}