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:io.reactivex.netty.protocol.http.sse.ServerSentEventDecoder.java

License:Apache License

private static ServerSentEvent.Type readCurrentFieldTypeFromBuffer(final ByteBuf fieldNameBuffer) {
    /**/*from  w ww .ja v  a 2s  . c  om*/
     * This code tries to eliminate the need of creating a string from the ByteBuf as the field names are very
     * constrained. The algorithm is as follows:
     *
     * -- Scan the bytes in the buffer.
     * -- If the first byte matches the expected field names then use the matching field name char array to verify
     * the rest of the field name.
     * -- If the first byte does not match, reject the field name.
     * -- After the first byte, exact match the rest of the field name with the expected field name, byte by byte.
     * -- If the name does not exactly match the expected value, then reject the field name.
     */
    ServerSentEvent.Type toReturn = ServerSentEvent.Type.Data;
    int readableBytes = fieldNameBuffer.readableBytes();
    final int readerIndexAtStart = fieldNameBuffer.readerIndex();
    char[] fieldNameToVerify = DATA_FIELD_NAME;
    boolean verified = false;
    int actualFieldNameIndexToCheck = 0; // Starts with 1 as the first char is validated by equality.
    for (int i = readerIndexAtStart; i < readableBytes; i++) {
        final char charAtI = (char) fieldNameBuffer.getByte(i);

        if (i == readerIndexAtStart) {
            switch (charAtI) { // See which among the known field names this buffer belongs.
            case 'e':
                fieldNameToVerify = EVENT_ID_FIELD_NAME;
                toReturn = ServerSentEvent.Type.EventType;
                break;
            case 'd':
                fieldNameToVerify = DATA_FIELD_NAME;
                toReturn = ServerSentEvent.Type.Data;
                break;
            case 'i':
                fieldNameToVerify = ID_FIELD_NAME;
                toReturn = ServerSentEvent.Type.Id;
                break;
            default:
                return null;
            }
        } else {
            if (++actualFieldNameIndexToCheck >= fieldNameToVerify.length
                    || charAtI != fieldNameToVerify[actualFieldNameIndexToCheck]) {
                // If the character does not match or the buffer is bigger than the expected name, then discard.
                verified = false;
                break;
            } else {
                // Verified till now. If all characters are matching then this stays as verified, else changed to false.
                verified = true;
            }
        }
    }

    if (verified) {
        return toReturn;
    } else {
        return null;
    }
}

From source file:io.scalecube.socketio.serialization.PacketFramer.java

License:Apache License

private static boolean isDelimiter(final ByteBuf buffer, final int index) {
    for (int i = 0; i < DELIMITER_BYTES_SIZE; i++) {
        if (buffer.getByte(index + i) != DELIMITER_BYTES[i]) {
            return false;
        }//w ww  .ja  v  a 2  s.c  o m
    }
    return true;
}

From source file:io.vertx.core.http.impl.Http1xOrH2CHandler.java

License:Open Source License

@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf buf = (ByteBuf) msg;
    int len = Math.min(buf.readableBytes(), HTTP_2_PREFACE_ARRAY.length - current);
    int i = 0;/*  w  w  w . j  a va  2 s .c o m*/
    while (i < len) {
        if (buf.getByte(buf.readerIndex() + i) != HTTP_2_PREFACE_ARRAY[current + i]) {
            end(ctx, buf, false);
            return;
        }
        i++;
    }
    if (current + i == HTTP_2_PREFACE_ARRAY.length) {
        end(ctx, buf, true);
    } else {
        current += len;
        buf.release();
    }
}

From source file:jazmin.server.msg.codec.json.JSONDecoder.java

License:Open Source License

/**
 * Create a frame out of the {@link ByteBuf} and return it.
 *
 * @param   ctx             the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to
 * @param   buffer          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 a2s  . c o  m*/
 */
protected ByteBuf decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
    final int eol = findEndOfLine(buffer);
    if (!discarding) {
        if (eol >= 0) {
            final ByteBuf frame;
            final int length = eol - buffer.readerIndex();
            final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1;

            if (length > maxLength) {
                buffer.readerIndex(eol + delimLength);
                fail(ctx, length);
                return null;
            }

            if (stripDelimiter) {
                frame = buffer.readBytes(length);
                buffer.skipBytes(delimLength);
            } else {
                frame = buffer.readBytes(length + delimLength);
            }

            return frame;
        } else {
            final int length = buffer.readableBytes();
            if (length > maxLength) {
                discardedBytes = length;
                buffer.readerIndex(buffer.writerIndex());
                discarding = true;
                if (failFast) {
                    fail(ctx, "over " + discardedBytes);
                }
            }
            return null;
        }
    } else {
        if (eol >= 0) {
            final int length = discardedBytes + eol - buffer.readerIndex();
            final int delimLength = buffer.getByte(eol) == '\r' ? 2 : 1;
            buffer.readerIndex(eol + delimLength);
            discardedBytes = 0;
            discarding = false;
            if (!failFast) {
                fail(ctx, length);
            }
        } else {
            discardedBytes = buffer.readableBytes();
            buffer.readerIndex(buffer.writerIndex());
        }
        return null;
    }
}

From source file:jazmin.server.msg.codec.json.JSONDecoder.java

License:Open Source License

/**
 * Returns the index in the buffer of the end of line found.
 * Returns -1 if no end of line was found in the buffer.
 *//*w w  w  .j a va  2  s.  c  o  m*/
private static int findEndOfLine(final ByteBuf buffer) {
    final int n = buffer.writerIndex();
    for (int i = buffer.readerIndex(); i < n; i++) {
        final byte b = buffer.getByte(i);
        if (b == '\n') {
            return i;
        } else if (b == '\r' && i < n - 1 && buffer.getByte(i + 1) == '\n') {
            return i; // \r\n
        }
    }
    return -1; // Not found.
}

From source file:mysql.client.Session_Old.java

final String readString(ByteBuf buf, String encoding) throws Exception {
    int i = buf.readerIndex();
    int len = 0;// w ww . j a  v a2 s  .c  om
    int maxLen = buf.writerIndex();

    while ((i < maxLen) && (buf.getByte(i) != 0)) {
        len++;
        i++;
    }

    try {
        return StringUtils.toString(buf.array(), buf.readerIndex(), len, encoding);
    } catch (UnsupportedEncodingException uEE) {
        throw uEE;
    } finally {
        buf.readerIndex(buf.readerIndex() + (len + 1));
    }
}

From source file:net.epsilony.utils.codec.modbus.Utils.java

License:Open Source License

public static int crc(ByteBuf byteBuf, int start, int numBytes) {
    int polynomial = 0xA001;
    int crc = 0xFFFF;
    for (int i = start; i < start + numBytes; i++) {
        byte b = byteBuf.getByte(i);
        int low = (crc & 0xFF) ^ (b & 0xFF);
        crc &= (0xFF00);//from www  .  j a v  a2 s. com
        crc |= (low);
        for (int j = 0; j < 8; j++) {
            int t = crc & 0x01;
            crc >>= 1;
            if (t == 0) {
                continue;
            }
            crc ^= polynomial;
        }
    }
    int first = (crc & 0xFF) << 8;
    crc = (crc & 0xFF00) >> 8 | first;
    return crc;
}

From source file:net.hasor.rsf.protocol.rsf.RsfDecoder.java

License:Apache License

protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    ByteBuf frame = (ByteBuf) super.decode(ctx, in);
    if (frame == null) {
        return null;
    }//  w  w  w  . j  a va2 s . com
    //
    byte rsfHead = frame.getByte(0);//??
    short status = this.doDecode(rsfHead, ctx, frame);//???
    if (status != ProtocolStatus.OK) {
        frame = frame.resetReaderIndex().skipBytes(1);
        long requestID = frame.readLong();
        ResponseInfo info = ProtocolUtils.buildResponseStatus(this.rsfEnvironment, requestID, status, null);
        ctx.pipeline().writeAndFlush(info);
    }
    return null;
}

From source file:net.hasor.rsf.remoting.transport.netty.RSFProtocolDecoder.java

License:Apache License

protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    ByteBuf frame = (ByteBuf) super.decode(ctx, in);
    if (frame == null) {
        return null;
    }//from w w w.j a  v a  2  s. c  om
    //
    //* byte[1]  version                              RSF(0xC1)
    byte version = frame.getByte(0);
    short status = 0;
    //decode
    try {
        status = this.doDecode(version, ctx, frame);//???
    } catch (Throwable e) {
        status = ProtocolStatus.ProtocolError;
    } finally {
        if (status == ProtocolStatus.OK)
            return null;
        /*                    */
        frame = frame.resetReaderIndex().skipBytes(1);
        this.fireProtocolError(ctx, version, frame.readLong(), ProtocolStatus.ProtocolError);
    }
    return null;
}

From source file:net.openhft.fix.transport.codec.NettyFrameDecoder.java

License:Apache License

/**
 * TODO: loop for more messages in the ByteBuf
*///from  ww w  .j a  v  a 2s .  c om
void doDecode(ByteBuf in, List<Object> out) {
    if (m_msgLength == -1) {
        if (in.readableBytes() >= NettyFrameHelper.MSG_MIN_BYTES) {
            //int rindex = in.readerIndex();

            int bsi = in.indexOf(0, 12, NettyFrameHelper.BYTE_SOH);
            int bli = in.indexOf(12, 20, NettyFrameHelper.BYTE_SOH);

            // check the existence of:
            // - BeginString 8=
            // - BodyLength  9=
            if (in.getByte(0) == NettyFrameHelper.BYTE_BEGIN_STRING
                    && in.getByte(1) == NettyFrameHelper.BYTE_EQUALS
                    && in.getByte(bsi + 1) == NettyFrameHelper.BYTE_BODY_LENGTH
                    && in.getByte(bsi + 2) == NettyFrameHelper.BYTE_EQUALS) {

                int bodyLength = 0;
                for (int i = bsi + 3; i < bli; i++) {
                    bodyLength *= 10;
                    bodyLength += ((int) in.getByte(i) - (int) '0');
                }

                m_msgLength = 1 + bodyLength + bli + NettyFrameHelper.MSG_CSUM_LEN;
            } else {
                throw new Error("Unexpected state (header)");
            }
        }
    }

    if (m_msgLength != -1 && in.readableBytes() >= m_msgLength) {
        if (in.readableBytes() >= m_msgLength) {
            byte[] rv = new byte[m_msgLength];
            in.readBytes(rv);
            in.discardReadBytes();

            //TODO: validate checksum
            out.add(rv);

            m_msgLength = -1;
        } else {
            throw new Error("Unexpected state (body)");
        }
    }
}