Example usage for io.netty.buffer ByteBuf skipBytes

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

Introduction

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

Prototype

public abstract ByteBuf skipBytes(int length);

Source Link

Document

Increases the current readerIndex by the specified length in this buffer.

Usage

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

License:Open Source License

public void readParameterMetadata(MyPreparedStatement<String> pStmt) throws PEException {
    //TODO: this belongs in unmarshall, but requires knowledge about the expected number of parameters, provided by a previous prepare response.
    ParsedData cachedParse = readState();
    ByteBuf backingData = readBuffer();//from w ww .  ja va  2  s. c  o  m
    int lengthOfMetadata = backingData.readableBytes() - cachedParse.metadataOffset;
    ByteBuf in = backingData.slice(cachedParse.metadataOffset, lengthOfMetadata).order(ByteOrder.LITTLE_ENDIAN);
    if (pStmt.getNumParams() > 0) {
        int nullBitmapLength = (pStmt.getNumParams() + 7) / 8;
        MyNullBitmap nullBitmap = new MyNullBitmap(MysqlAPIUtils.readBytes(in, nullBitmapLength),
                pStmt.getNumParams(), MyNullBitmap.BitmapType.EXECUTE_REQUEST);
        if (in.readByte() == 1) { // this is new params bound flag; only
            // =1 on first stmt_execute
            pStmt.clearParameters();
            for (int i = 0; i < pStmt.getNumParams(); i++) {
                pStmt.addParameter(new MyParameter(MyFieldType.fromByte(in.readByte())));
                in.skipBytes(1);
            }
        }

        for (int paramNum = 1; paramNum <= pStmt.getNumParams(); paramNum++) {
            MyParameter parameter = pStmt.getParameter(paramNum);
            if (nullBitmap.getBit(paramNum)) {
                parameter.setValue(null);
            } else {
                //TODO - may need to figure out how to get the proper flags and length into this call
                parameter.setValue(DBTypeBasedUtils.getMysqlTypeFunc(parameter.getType()).readObject(in));
            }
        }
    }
}

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

License:Open Source License

protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out, boolean isLastBytes)
        throws Exception {
    ByteBuf leBuf = in.order(ByteOrder.LITTLE_ENDIAN);

    leBuf.markReaderIndex();/* w  w  w  . jav a  2 s.  c  o m*/
    boolean messageProcessed = false;

    try {
        if (leBuf.readableBytes() > MESSAGE_HEADER_LEN) {
            int payloadLen = leBuf.readMedium();
            leBuf.readByte(); // seq

            if (leBuf.readableBytes() >= payloadLen) {
                ByteBuf payload = leBuf.slice(leBuf.readerIndex(), payloadLen).order(ByteOrder.LITTLE_ENDIAN);
                Byte protocolVersion = leBuf.readByte();
                leBuf.skipBytes(payloadLen - 1);
                messageProcessed = true;

                if (state == AuthenticationState.AWAIT_GREETING)
                    processGreeting(ctx, payload, protocolVersion);
                else
                    processAcknowlegement(ctx, payload);
            }
        }

    } catch (Throwable t) {
        enterState(AuthenticationState.FAILURE);
        log.warn("Unexpected problem on outbound mysql connection.", t);
        throw t;
    } finally {
        if (!messageProcessed)
            leBuf.resetReaderIndex();

        if (isLastBytes && (state == AuthenticationState.AWAIT_ACKNOWLEGEMENT
                || state == AuthenticationState.AWAIT_GREETING)) {
            //we are waiting for handshake packets from mysql, but no more packets will ever arrive.  release blocked callers.
            Channel channel = ctx.channel();
            SocketAddress addr = (channel == null ? null : channel.remoteAddress());
            log.warn("Socket closed in middle of authentication handshake on socket " + addr);
            enterState(AuthenticationState.FAILURE);
        }
    }
}

From source file:com.tesora.dve.mysqlapi.repl.messages.MyComBinLogDumpRequest.java

License:Open Source License

@Override
public void unmarshallMessage(ByteBuf cb) {
    binlogPosition = cb.readUnsignedInt();
    cb.skipBytes(2);
    slaveServerID = cb.readInt();/*from  www .  ja  va  2 s.  com*/
    if (cb.readableBytes() > 0) {
        binlogFileName = cb.readSlice(cb.readableBytes()).toString(CharsetUtil.UTF_8);
    }
}

From source file:com.tesora.dve.mysqlapi.repl.messages.MyExecuteLoadLogEvent.java

License:Open Source License

@Override
public void unmarshallMessage(ByteBuf cb) throws PEException {
    threadId = cb.readInt();/*  w w  w.java 2s  .  co m*/
    time = cb.readInt();
    dbLen = cb.readByte();
    errorCode = cb.readShort();
    statusBlockLen = cb.readShort();
    fileId = cb.readInt();
    startPos = cb.readInt();
    endPos = cb.readInt();
    duplicateFlag = cb.readByte();
    // really we should check if replication version >=4 or else this is wrong
    statusVars.parseStatusVariables(cb, statusBlockLen);

    dbName = MysqlAPIUtils.readBytesAsString(cb, dbLen, CharsetUtil.UTF_8);
    cb.skipBytes(1); //for trailing 0
    query = Unpooled.buffer(cb.readableBytes());
    query.writeBytes(cb);
    origQuery = query.toString(CharsetUtil.UTF_8);
}

From source file:com.tesora.dve.mysqlapi.repl.messages.MyFormatDescriptionLogEvent.java

License:Open Source License

@Override
public void unmarshallMessage(ByteBuf cb) {
    binaryLogVersion = cb.readShort();/*from w ww  .  j  a va  2s  .c  om*/
    serverVersion = MysqlAPIUtils.readBytesAsString(cb, ST_SERVER_VER_LEN, CharsetUtil.UTF_8);
    createTime = cb.readUnsignedInt();
    eventTypeLength = cb.readUnsignedByte();
    int numberOfEntries = cb.readableBytes() - 1;//string is null terminated.

    switch (MyBinLogVerType.fromByte((byte) binaryLogVersion)) {

    case MySQL_5_0:
        for (int i = 1; i <= numberOfEntries; i++) {
            eventTypeValues.put(MyLogEventType.fromByte((byte) i), cb.readByte());
        }
        cb.skipBytes(1);//throw out EOF
        break;

    default:
        // TODO throw????
        logger.error("Cannot process binary log messages that are not for MySQL 5.0");
    }
}

From source file:com.tesora.dve.mysqlapi.repl.messages.MyQueryLogEvent.java

License:Open Source License

@Override
public void unmarshallMessage(ByteBuf cb) throws PEException {

    // read event header
    slaveProxyId = cb.readUnsignedInt();
    execTime = cb.readUnsignedInt();//www . j  a v a2  s.  com
    dbNameLen = cb.readByte();
    errorCode = cb.readUnsignedShort();
    statusVarsLen = cb.readUnsignedShort();

    statusVars.parseStatusVariables(cb, statusVarsLen);

    dbName = MysqlAPIUtils.readBytesAsString(cb, dbNameLen, CharsetUtil.UTF_8);
    cb.skipBytes(1); //for trailing 0
    query = Unpooled.buffer(cb.readableBytes());
    query.writeBytes(cb);
    origQuery = query.toString(CharsetUtil.UTF_8);
}

From source file:com.tesora.dve.mysqlapi.repl.messages.MyRotateLogEvent.java

License:Open Source License

@Override
public void unmarshallMessage(ByteBuf cb) {
    position = cb.readLong();/*from   w w  w .ja  v a2 s  .co m*/
    newLogFileName = cb.toString(CharsetUtil.UTF_8);
    cb.skipBytes(cb.readableBytes());//consume the rest of the buffer.
}

From source file:com.twitter.http2.HttpFrameDecoder.java

License:Apache License

/**
 * Decode the byte buffer./* w  w  w  .  j  av  a 2  s.co m*/
 */
public void decode(ByteBuf buffer) {
    boolean endStream;
    boolean endSegment;
    int minLength;
    int dependency;
    int weight;
    boolean exclusive;
    int errorCode;

    while (true) {
        switch (state) {
        case READ_CONNECTION_HEADER:
            while (buffer.isReadable()) {
                byte b = buffer.readByte();
                if (b != CLIENT_CONNECTION_PREFACE[length++]) {
                    state = State.FRAME_ERROR;
                    delegate.readFrameError("Invalid Connection Header");
                    return;
                }

                if (length == CLIENT_CONNECTION_PREFACE.length) {
                    state = State.READ_FRAME_HEADER;
                    break;
                }
            }
            if (buffer.isReadable()) {
                break;
            } else {
                return;
            }

        case READ_FRAME_HEADER:
            // Wait until entire header is readable
            if (buffer.readableBytes() < HTTP_FRAME_HEADER_SIZE) {
                return;
            }

            // Read frame header fields
            readFrameHeader(buffer);

            // TODO(jpinner) Sec 4.2 FRAME_SIZE_ERROR

            if (!isValidFrameHeader(length, type, flags, streamId)) {
                state = State.FRAME_ERROR;
                delegate.readFrameError("Invalid Frame Header");
            } else if (frameHasPadding(type, flags)) {
                state = State.READ_PADDING_LENGTH;
            } else {
                paddingLength = 0;
                state = getNextState(length, type);
            }
            break;

        case READ_PADDING_LENGTH:
            if (buffer.readableBytes() < 1) {
                return;
            }

            paddingLength = buffer.readUnsignedByte();
            --length;

            if (!isValidPaddingLength(length, type, flags, paddingLength)) {
                state = State.FRAME_ERROR;
                delegate.readFrameError("Invalid Frame Padding Length");
            } else {
                state = getNextState(length, type);
            }
            break;

        case READ_DATA_FRAME:
            endStream = hasFlag(flags, HTTP_FLAG_END_STREAM);
            state = State.READ_DATA;
            if (hasFlag(flags, HTTP_FLAG_PADDED)) {
                delegate.readDataFramePadding(streamId, endStream, paddingLength + 1);
            }
            break;

        case READ_DATA:
            // Generate data frames that do not exceed maxChunkSize
            // maxChunkSize must be > 0 so we cannot infinitely loop
            int dataLength = Math.min(maxChunkSize, length - paddingLength);

            // Wait until entire frame is readable
            if (buffer.readableBytes() < dataLength) {
                return;
            }

            ByteBuf data = buffer.readBytes(dataLength);
            length -= dataLength;

            if (length == paddingLength) {
                if (paddingLength == 0) {
                    state = State.READ_FRAME_HEADER;
                } else {
                    state = State.SKIP_FRAME_PADDING;
                }
            }

            endStream = length == paddingLength && hasFlag(flags, HTTP_FLAG_END_STREAM);
            endSegment = length == paddingLength && hasFlag(flags, HTTP_FLAG_END_SEGMENT);

            delegate.readDataFrame(streamId, endStream, endSegment, data);
            break;

        case READ_HEADERS_FRAME:
            minLength = 0;
            if (hasFlag(flags, HTTP_FLAG_PRIORITY)) {
                minLength = 5;
            }
            if (buffer.readableBytes() < minLength) {
                return;
            }

            endStream = hasFlag(flags, HTTP_FLAG_END_STREAM);
            endSegment = hasFlag(flags, HTTP_FLAG_END_SEGMENT);

            exclusive = false;
            dependency = 0;
            weight = 16;
            if (hasFlag(flags, HTTP_FLAG_PRIORITY)) {
                dependency = getSignedInt(buffer, buffer.readerIndex());
                buffer.skipBytes(4);
                weight = buffer.readUnsignedByte() + 1;
                if (dependency < 0) {
                    dependency = dependency & 0x7FFFFFFF;
                    exclusive = true;
                }
                length -= 5;
            }

            state = State.READ_HEADER_BLOCK;
            delegate.readHeadersFrame(streamId, endStream, endSegment, exclusive, dependency, weight);
            break;

        case READ_PRIORITY_FRAME:
            if (buffer.readableBytes() < length) {
                return;
            }

            exclusive = false;
            dependency = getSignedInt(buffer, buffer.readerIndex());
            buffer.skipBytes(4);
            weight = buffer.readUnsignedByte() + 1;
            if (dependency < 0) {
                dependency = dependency & 0x7FFFFFFF;
                exclusive = true;
            }

            state = State.READ_FRAME_HEADER;
            delegate.readPriorityFrame(streamId, exclusive, dependency, weight);
            break;

        case READ_RST_STREAM_FRAME:
            if (buffer.readableBytes() < length) {
                return;
            }

            errorCode = getSignedInt(buffer, buffer.readerIndex());
            buffer.skipBytes(length);

            state = State.READ_FRAME_HEADER;
            delegate.readRstStreamFrame(streamId, errorCode);
            break;

        case READ_SETTINGS_FRAME:
            boolean ack = hasFlag(flags, HTTP_FLAG_ACK);

            state = State.READ_SETTING;
            delegate.readSettingsFrame(ack);
            break;

        case READ_SETTING:
            if (length == 0) {
                state = State.READ_FRAME_HEADER;
                delegate.readSettingsEnd();
                break;
            }

            if (buffer.readableBytes() < 6) {
                return;
            }

            int id = getUnsignedShort(buffer, buffer.readerIndex());
            int value = getSignedInt(buffer, buffer.readerIndex() + 2);
            buffer.skipBytes(6);
            length -= 6;

            delegate.readSetting(id, value);
            break;

        case READ_PUSH_PROMISE_FRAME:
            if (buffer.readableBytes() < 4) {
                return;
            }

            int promisedStreamId = getUnsignedInt(buffer, buffer.readerIndex());
            buffer.skipBytes(4);
            length -= 4;

            if (promisedStreamId == 0) {
                state = State.FRAME_ERROR;
                delegate.readFrameError("Invalid Promised-Stream-ID");
            } else {
                state = State.READ_HEADER_BLOCK;
                delegate.readPushPromiseFrame(streamId, promisedStreamId);
            }
            break;

        case READ_PING_FRAME:
            if (buffer.readableBytes() < length) {
                return;
            }

            long ping = getSignedLong(buffer, buffer.readerIndex());
            buffer.skipBytes(length);

            boolean pong = hasFlag(flags, HTTP_FLAG_ACK);

            state = State.READ_FRAME_HEADER;
            delegate.readPingFrame(ping, pong);
            break;

        case READ_GOAWAY_FRAME:
            if (buffer.readableBytes() < 8) {
                return;
            }

            int lastStreamId = getUnsignedInt(buffer, buffer.readerIndex());
            errorCode = getSignedInt(buffer, buffer.readerIndex() + 4);
            buffer.skipBytes(8);
            length -= 8;

            if (length == 0) {
                state = State.READ_FRAME_HEADER;
            } else {
                paddingLength = length;
                state = State.SKIP_FRAME_PADDING;
            }
            delegate.readGoAwayFrame(lastStreamId, errorCode);
            break;

        case READ_WINDOW_UPDATE_FRAME:
            // Wait until entire frame is readable
            if (buffer.readableBytes() < length) {
                return;
            }

            int windowSizeIncrement = getUnsignedInt(buffer, buffer.readerIndex());
            buffer.skipBytes(length);

            if (windowSizeIncrement == 0) {
                state = State.FRAME_ERROR;
                delegate.readFrameError("Invalid Window Size Increment");
            } else {
                state = State.READ_FRAME_HEADER;
                delegate.readWindowUpdateFrame(streamId, windowSizeIncrement);
            }
            break;

        case READ_CONTINUATION_FRAME_HEADER:
            // Wait until entire frame header is readable
            if (buffer.readableBytes() < HTTP_FRAME_HEADER_SIZE) {
                return;
            }

            // Read and validate continuation frame header fields
            int prevStreamId = streamId;
            readFrameHeader(buffer);

            // TODO(jpinner) Sec 4.2 FRAME_SIZE_ERROR
            // TODO(jpinner) invalid flags

            if (type != HTTP_CONTINUATION_FRAME || streamId != prevStreamId) {
                state = State.FRAME_ERROR;
                delegate.readFrameError("Invalid Continuation Frame");
            } else {
                paddingLength = 0;
                state = State.READ_HEADER_BLOCK;
            }
            break;

        case READ_HEADER_BLOCK:
            if (length == paddingLength) {
                boolean endHeaders = hasFlag(flags, HTTP_FLAG_END_HEADERS);
                if (endHeaders) {
                    state = State.SKIP_FRAME_PADDING;
                    delegate.readHeaderBlockEnd();
                } else {
                    state = State.SKIP_FRAME_PADDING_CONTINUATION;
                }
                break;
            }

            if (!buffer.isReadable()) {
                return;
            }

            int readableBytes = Math.min(buffer.readableBytes(), length - paddingLength);
            ByteBuf headerBlockFragment = buffer.readBytes(readableBytes);
            length -= readableBytes;

            delegate.readHeaderBlock(headerBlockFragment);
            break;

        case SKIP_FRAME_PADDING:
            int numBytes = Math.min(buffer.readableBytes(), length);
            buffer.skipBytes(numBytes);
            length -= numBytes;
            if (length == 0) {
                state = State.READ_FRAME_HEADER;
                break;
            }
            return;

        case SKIP_FRAME_PADDING_CONTINUATION:
            int numPaddingBytes = Math.min(buffer.readableBytes(), length);
            buffer.skipBytes(numPaddingBytes);
            length -= numPaddingBytes;
            if (length == 0) {
                state = State.READ_CONTINUATION_FRAME_HEADER;
                break;
            }
            return;

        case FRAME_ERROR:
            buffer.skipBytes(buffer.readableBytes());
            return;

        default:
            throw new Error("Shouldn't reach here.");
        }
    }
}

From source file:com.twitter.http2.HttpFrameDecoder.java

License:Apache License

/**
 * Reads the HTTP/2 Frame Header and sets the length, type, flags, and streamId member variables.
 *
 * @param buffer input buffer containing the entire 9-octet header
 *///from   w w w .j  a v  a  2s .  com
private void readFrameHeader(ByteBuf buffer) {
    int frameOffset = buffer.readerIndex();
    length = getUnsignedMedium(buffer, frameOffset);
    type = buffer.getUnsignedByte(frameOffset + 3);
    flags = buffer.getByte(frameOffset + 4);
    streamId = getUnsignedInt(buffer, frameOffset + 5);
    buffer.skipBytes(HTTP_FRAME_HEADER_SIZE);
}

From source file:com.uber.tchannel.codecs.TFrameCodec.java

License:Open Source License

public static TFrame decode(ByteBuf buffer) {
    // size:2//from   ww w  .  ja  va2s .  co  m
    int size = buffer.readUnsignedShort() - TFrame.FRAME_HEADER_LENGTH;

    // type:1
    byte type = buffer.readByte();

    // reserved:1
    buffer.skipBytes(1);

    // id:4
    long id = buffer.readUnsignedInt();

    // reserved:8
    buffer.skipBytes(8);

    // payload:16+
    ByteBuf payload = buffer.readSlice(size);
    //        payload.retain();

    return new TFrame(size, type, id, payload);
}