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.antsdb.saltedfish.server.mysql.ReplicationPacketDecoder.java

License:Open Source License

@SuppressWarnings("unused")
private ReplicationPacket readPacket(ByteBuf in, int size) {
    // packet sequence number for multiple packets

    // byte packetSequence = in.readByte();
    byte seqId = in.readByte();

    // handshake//from w ww. j a va 2 s . c  o  m

    ReplicationPacket packet = null;

    // using state to decide how to handle connecting messages.
    if (state == StateIndicator.INITIAL_STATE) {
        packet = new StateIndicator(StateIndicator.INITIAL_STATE);
        packet.packetLength = size;
        packet.packetId = seqId;
        packet.read(this.handler, in);
        state = StateIndicator.RESPONSED_STATE;
    } else if (state == StateIndicator.RESPONSED_STATE) {
        byte header = in.readByte();

        if (header == 0) {
            packet = new StateIndicator(StateIndicator.HANDSHAKEN_STATE);
            state = StateIndicator.HANDSHAKEN_STATE;
        } else {
            packet = new StateIndicator(StateIndicator.HANDSHAKE_FAIL_STATE);
            state = StateIndicator.HANDSHAKE_FAIL_STATE;
        }
        char[] bytes = new char[size];
        for (int i = 0; i < size; i++) {
            int ch = in.getByte(i);
            bytes[i] = (char) ch;
        }
        packet.packetId = seqId;
        packet.packetLength = size;
        packet.read(this.handler, in);
    } else if (state == StateIndicator.HANDSHAKEN_STATE) {
        // expecting response for registered slave
        byte header = in.readByte();

        if (header == 0) {
            packet = new StateIndicator(StateIndicator.REGISTERED_STATE);
            state = StateIndicator.REGISTERED_STATE;
        } else {
            packet = new StateIndicator(StateIndicator.REGISTER_FAIL_STATE);
            state = StateIndicator.REGISTER_FAIL_STATE;
        }
        packet.packetId = seqId;
        packet.packetLength = size;
        packet.read(this.handler, in);
    } else {

        // binlog stream started with 00 ok-byte
        byte okByte = in.readByte();

        if (okByte == 0) {
            // read event header

            // timestamp 4 bytes
            int timeStamp = in.readInt();
            // event type
            byte eventType = in.readByte();
            // server id, 4 bytes
            int serverId = (int) BufferUtils.readLong(in);
            // event length, 4 bytes
            long eventLength = BufferUtils.readLong(in);
            // next position, 4 bytes
            long nextPosition = BufferUtils.readLong(in);
            // flags
            int flags = in.readShort();

            // events

            switch (eventType) {
            case ReplicationPacket.ROTATE_EVENT:
                packet = new RotatePacket(eventType, eventLength, nextPosition);
                break;
            case ReplicationPacket.TABLE_MAP_EVENT:
                packet = new TableMapPacket(eventType, eventLength, nextPosition);
                break;
            case ReplicationPacket.WRITE_ROWS_EVENT:
            case ReplicationPacket.UPDATE_ROWS_EVENT:
            case ReplicationPacket.DELETE_ROWS_EVENT:
                packet = new RowsEventV2Packet(eventType, eventLength, nextPosition);
                break;
            case ReplicationPacket.STOP_EVENT:
                packet = new StopPacket(eventType, eventLength, nextPosition);
                break;
            case ReplicationPacket.XID_EVENT:
                packet = new XIDPacket(eventType, eventLength, nextPosition);
                break;
            case ReplicationPacket.QUERY_EVENT:
            case ReplicationPacket.FORMAT_DESCRIPTION_EVENT:
            case ReplicationPacket.START_EVENT_V3:
                // use GenericPacket to ignore unsupported events for now
                packet = new GenericPacket(eventType, eventLength, nextPosition);
                break;
            default:
                _log.error("unknown event: " + eventType);
                throw new CodingError("unknown event: " + eventType);
            }

            if (packet != null) {
                packet.packetId = seqId;
                packet.packetLength = size;
                packet.read(this.handler, in);
            }
        } else {
            ByteBuf pkt = (ByteBuf) in;
            ByteBuffer bbuf = pkt.nioBuffer();

            int i = bbuf.remaining();

            byte[] bytes = new byte[i];
            pkt.readBytes(bytes);
            String dump = '\n' + UberUtil.hexDump(bytes);
            _log.error("unknown packet: " + dump);
            throw new CodingError("unknown packet");
        }
    }
    return packet;
}

From source file:com.cloudhopper.smpp.util.ChannelBufferUtil.java

License:Apache License

/**
 * Reads a C-String (null terminated) from a buffer.  This method will
 * attempt to find the null byte and read all data up to and including
 * the null byte.  The returned String does not include the null byte.
 * Will throw an exception if no null byte is found and it runs out of data
 * in the buffer to read.// w w w.  ja v a2  s .  c o m
 * @param buffer
 * @return
 * @throws TerminatingNullByteNotFoundException
 */
static public String readNullTerminatedString(ByteBuf buffer) throws TerminatingNullByteNotFoundException {
    // maximum possible length are the readable bytes in buffer
    int maxLength = buffer.readableBytes();

    // if there are no readable bytes, return null
    if (maxLength == 0) {
        return null;
    }

    // the reader index is defaulted to the readerIndex
    int offset = buffer.readerIndex();
    int zeroPos = 0;

    // search for NULL byte until we hit end or find it
    while ((zeroPos < maxLength) && (buffer.getByte(zeroPos + offset) != 0x00)) {
        zeroPos++;
    }

    if (zeroPos >= maxLength) {
        // a NULL byte was not found
        throw new TerminatingNullByteNotFoundException(
                "Terminating null byte not found after searching [" + maxLength + "] bytes");
    }

    // at this point, we found a terminating zero
    String result = null;
    if (zeroPos > 0) {
        // read a new byte array
        byte[] bytes = new byte[zeroPos];
        buffer.readBytes(bytes);
        try {
            result = new String(bytes, "ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            logger.error("Impossible error", e);
        }
    } else {
        result = "";
    }

    // at this point, we have just one more byte to skip over (the null byte)
    byte b = buffer.readByte();
    if (b != 0x00) {
        logger.error("Impossible error: last byte read SHOULD have been a null byte, but was [" + b + "]");
    }

    return result;
}

From source file:com.corundumstudio.socketio.parser.Decoder.java

License:Apache License

private long parseLong(ByteBuf chars, int length) {
    long result = 0;
    for (int i = chars.readerIndex(); i < length; i++) {
        int digit = ((int) chars.getByte(i) & 0xF);
        for (int j = 0; j < length - 1 - i; j++) {
            digit *= 10;/*from w  w  w. j a  va  2  s.c  om*/
        }
        result += digit;
    }
    return result;
}

From source file:com.corundumstudio.socketio.parser.Decoder.java

License:Apache License

private Packet decodePacket(ByteBuf buffer, UUID uuid) throws IOException {
    if (buffer.readableBytes() < 3) {
        throw new DecoderException("Can't parse " + buffer.toString(CharsetUtil.UTF_8));
    }/*from  ww  w  .  j  av  a 2  s. com*/
    PacketType type = getType(buffer);

    int readerIndex = buffer.readerIndex() + 1;
    // 'null' to avoid unnecessary StringBuilder creation
    boolean hasData = false;
    StringBuilder messageId = null;
    for (readerIndex += 1; readerIndex < buffer.readableBytes(); readerIndex++) {
        if (messageId == null) {
            messageId = new StringBuilder(4);
        }
        byte msg = buffer.getByte(readerIndex);
        if (msg == Packet.SEPARATOR) {
            break;
        }
        if (msg != (byte) '+') {
            messageId.append((char) msg);
        } else {
            hasData = true;
        }
    }
    Long id = null;
    if (messageId != null && messageId.length() > 0) {
        id = Long.valueOf(messageId.toString());
    }

    // 'null' to avoid unnecessary StringBuilder creation
    StringBuilder endpointBuffer = null;
    for (readerIndex += 1; readerIndex < buffer.readableBytes(); readerIndex++) {
        if (endpointBuffer == null) {
            endpointBuffer = new StringBuilder();
        }
        byte msg = buffer.getByte(readerIndex);
        if (msg == Packet.SEPARATOR) {
            break;
        }
        endpointBuffer.append((char) msg);
    }

    String endpoint = Namespace.DEFAULT_NAME;
    if (endpointBuffer != null && endpointBuffer.length() > 0) {
        endpoint = endpointBuffer.toString();
    }

    if (buffer.readableBytes() == readerIndex) {
        buffer.readerIndex(buffer.readableBytes());
    } else {
        readerIndex += 1;
        buffer.readerIndex(readerIndex);
    }

    Packet packet = new Packet(type);
    packet.setEndpoint(endpoint);
    if (id != null) {
        packet.setId(id);
        if (hasData) {
            packet.setAck(Packet.ACK_DATA);
        } else {
            packet.setAck(true);
        }
    }

    switch (type) {
    case ERROR: {
        if (!buffer.isReadable()) {
            break;
        }
        String[] pieces = buffer.toString(CharsetUtil.UTF_8).split("\\+");
        if (pieces.length > 0 && pieces[0].trim().length() > 0) {
            ErrorReason reason = ErrorReason.valueOf(Integer.valueOf(pieces[0]));
            packet.setReason(reason);
            if (pieces.length > 1) {
                ErrorAdvice advice = ErrorAdvice.valueOf(Integer.valueOf(pieces[1]));
                packet.setAdvice(advice);
            }
        }
        break;
    }

    case MESSAGE: {
        if (buffer.isReadable()) {
            packet.setData(buffer.toString(CharsetUtil.UTF_8));
        } else {
            packet.setData("");
        }
        break;
    }

    case EVENT: {
        ByteBufInputStream in = new ByteBufInputStream(buffer);
        Event event = jsonSupport.readValue(in, Event.class);
        packet.setName(event.getName());
        if (event.getArgs() != null) {
            packet.setArgs(event.getArgs());
        }
        break;
    }

    case JSON: {
        ByteBufInputStream in = new ByteBufInputStream(buffer);
        JsonObject obj = jsonSupport.readValue(in, JsonObject.class);
        if (obj != null) {
            packet.setData(obj.getObject());
        } else {
            in.reset();
            Object object = jsonSupport.readValue(in, Object.class);
            packet.setData(object);
        }
        break;
    }

    case CONNECT: {
        if (buffer.isReadable()) {
            packet.setQs(buffer.toString(CharsetUtil.UTF_8));
        }
        break;
    }

    case ACK: {
        if (!buffer.isReadable()) {
            break;
        }
        boolean validFormat = true;
        int plusIndex = -1;
        for (int i = buffer.readerIndex(); i < buffer.readerIndex() + buffer.readableBytes(); i++) {
            byte dataChar = buffer.getByte(i);
            if (!Character.isDigit(dataChar)) {
                if (dataChar == '+') {
                    plusIndex = i;
                    break;
                } else {
                    validFormat = false;
                    break;
                }
            }
        }
        if (!validFormat) {
            break;
        }

        if (plusIndex == -1) {
            packet.setAckId(parseLong(buffer));
            break;
        } else {
            packet.setAckId(parseLong(buffer, plusIndex));
            buffer.readerIndex(plusIndex + 1);

            ByteBufInputStream in = new ByteBufInputStream(buffer);
            AckCallback<?> callback = ackManager.getCallback(uuid, packet.getAckId());
            AckArgs args = jsonSupport.readAckArgs(in, callback);
            packet.setArgs(args.getArgs());
        }
        break;
    }

    case DISCONNECT:
    case HEARTBEAT:
    case NOOP:
        break;
    }

    buffer.readerIndex(buffer.readerIndex() + buffer.readableBytes());
    return packet;
}

From source file:com.corundumstudio.socketio.parser.Decoder.java

License:Apache License

private PacketType getType(ByteBuf buffer) {
    int typeId = buffer.getByte(buffer.readerIndex()) & 0xF;
    if (typeId >= PacketType.VALUES.length || buffer.getByte(buffer.readerIndex() + 1) != Packet.SEPARATOR) {
        throw new DecoderException("Can't parse " + buffer.toString(CharsetUtil.UTF_8));
    }//  w w w .  jav  a  2 s .c o m
    return PacketType.valueOf(typeId);
}

From source file:com.corundumstudio.socketio.parser.Decoder.java

License:Apache License

private boolean isCurrentDelimiter(ByteBuf buffer, int index) {
    for (int i = 0; i < Packet.DELIMITER_BYTES.length; i++) {
        if (buffer.getByte(index + i) != Packet.DELIMITER_BYTES[i]) {
            return false;
        }/*from ww  w.  ja  va  2s.c  om*/
    }
    return true;
}

From source file:com.corundumstudio.socketio.parser.UTF8CharsScanner.java

License:Apache License

private int getCharTailIndex(ByteBuf inputBuffer, int i) {
    int c = (int) inputBuffer.getByte(i) & 0xFF;
    switch (sInputCodesUtf8[c]) {
    case 2: // 2-byte UTF
        i += 2;/*from www.j a  v  a  2s.  co  m*/
        break;
    case 3: // 3-byte UTF
        i += 3;
        break;
    case 4: // 4-byte UTF
        i += 4;
        break;
    default:
        i++;
        break;
    }
    return i;
}

From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java

License:Apache License

private boolean isStringPacket(ByteBuf content) {
    return content.getByte(content.readerIndex()) == 0x0;
}

From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java

License:Apache License

private long readLong(ByteBuf chars, int length) {
    long result = 0;
    for (int i = chars.readerIndex(); i < chars.readerIndex() + length; i++) {
        int digit = ((int) chars.getByte(i) & 0xF);
        for (int j = 0; j < chars.readerIndex() + length - 1 - i; j++) {
            digit *= 10;/*from w ww  .j  a  v  a  2s.c  o  m*/
        }
        result += digit;
    }
    chars.readerIndex(chars.readerIndex() + length);
    return result;
}

From source file:com.corundumstudio.socketio.protocol.PacketDecoder.java

License:Apache License

private boolean hasLengthHeader(ByteBuf buffer) {
    for (int i = 0; i < Math.min(buffer.readableBytes(), 10); i++) {
        byte b = buffer.getByte(buffer.readerIndex() + i);
        if (b == (byte) ':' && i > 0) {
            return true;
        }// w w w.ja v a 2  s.c  o m
        if (b > 57 || b < 48) {
            return false;
        }
    }
    return false;
}