Example usage for io.netty.buffer ByteBuf readShort

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

Introduction

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

Prototype

public abstract short readShort();

Source Link

Document

Gets a 16-bit short integer at the current readerIndex and increases the readerIndex by 2 in this buffer.

Usage

From source file:io.airlift.drift.transport.netty.codec.HeaderTransport.java

License:Apache License

public static Optional<FrameInfo> tryDecodeFrameInfo(ByteBuf input) {
    ByteBuf buffer = input.retainedDuplicate();
    try {/* www .  j  a  v a2 s.c  o m*/
        if (buffer.readableBytes() < FRAME_HEADER_SIZE) {
            return Optional.empty();
        }
        // skip magic
        buffer.readShort();
        short flags = buffer.readShort();
        boolean outOfOrderResponse = (flags & FLAG_SUPPORT_OUT_OF_ORDER_MASK) == 1;
        int headerSequenceId = buffer.readInt();
        int headerSize = buffer.readShort() << 2;

        if (buffer.readableBytes() < headerSize) {
            return Optional.empty();
        }

        byte protocolId = buffer.getByte(buffer.readerIndex());
        Protocol protocol = Protocol.getProtocolByHeaderTransportId(protocolId);

        buffer.skipBytes(headerSize);
        SimpleFrameInfoDecoder simpleFrameInfoDecoder = new SimpleFrameInfoDecoder(HEADER, protocol,
                outOfOrderResponse);
        Optional<FrameInfo> frameInfo = simpleFrameInfoDecoder.tryDecodeFrameInfo(buffer);
        if (frameInfo.isPresent()) {
            int messageSequenceId = frameInfo.get().getSequenceId();
            checkArgument(headerSequenceId == messageSequenceId,
                    "Sequence ids don't match. headerSequenceId: %s. messageSequenceId: %s", headerSequenceId,
                    messageSequenceId);
        }
        return frameInfo;
    } finally {
        buffer.release();
    }
}

From source file:io.airlift.drift.transport.netty.HeaderMessageEncoding.java

License:Apache License

@Override
@SuppressFBWarnings("DLS_DEAD_LOCAL_STORE")
public Object readResponse(ByteBuf buffer, int sequenceId, MethodMetadata method) throws Exception {
    short magic = buffer.readShort();
    verify(magic == HEADER_MAGIC, "Unexpected response header magic");
    short flags = buffer.readShort();
    verify(flags == 1, "Unexpected response header flags");

    int frameSequenceId = buffer.readInt();
    if (frameSequenceId != sequenceId) {
        throw new TApplicationException(BAD_SEQUENCE_ID,
                method.getName() + " failed: out of sequence response");
    }//from   w  w w.  j  a  va 2s .c  o  m
    int headerSize = buffer.readShort() << 2;

    ByteBuf messageHeader = buffer.readBytes(headerSize);
    int protocolId = messageHeader.readUnsignedByte();
    verify(protocolId == this.protocolId, "response protocol is different than request protocol");

    int numberOfTransforms = messageHeader.readUnsignedByte();
    verify(numberOfTransforms < 128, "Too many transforms for response");

    boolean gzipCompressed = false;
    for (int i = 0; i < numberOfTransforms; i++) {
        int transform = messageHeader.readUnsignedByte();
        verify(transform == 0x01, "Unsupported response transform");
        gzipCompressed = true;
    }

    // Currently we ignore response headers from the server because there is no API to fetch the headers
    Map<String, String> normalHeaders = decodeHeaders(NORMAL_HEADERS, messageHeader);
    Map<String, String> persistentHeaders = decodeHeaders(PERSISTENT_HEADERS, messageHeader);

    ByteBuf message = buffer.readBytes(buffer.readableBytes());
    if (gzipCompressed) {
        // todo decompress
        throw new TTransportException("gzip compression not implemented");
    }

    return MessageEncoding.decodeResponse(protocolFactory, message, sequenceId, method);
}

From source file:io.atomix.cluster.messaging.impl.MessageDecoder.java

License:Apache License

@Override
@SuppressWarnings("squid:S128") // suppress switch fall through warning
protected void decode(ChannelHandlerContext context, ByteBuf buffer, List<Object> out) throws Exception {

    switch (currentState) {
    case READ_SENDER_VERSION:
        if (buffer.readableBytes() < SHORT_SIZE) {
            return;
        }/*w ww. j a  va  2  s  .co  m*/
        version = buffer.readShort();
        currentState = DecoderState.READ_SENDER_IP;
    case READ_SENDER_IP:
        if (buffer.readableBytes() < BYTE_SIZE) {
            return;
        }
        buffer.markReaderIndex();
        int octetsLength = buffer.readByte();
        if (buffer.readableBytes() < octetsLength) {
            buffer.resetReaderIndex();
            return;
        }

        byte[] octets = new byte[octetsLength];
        buffer.readBytes(octets);
        senderIp = InetAddress.getByAddress(octets);
        currentState = DecoderState.READ_SENDER_PORT;
    case READ_SENDER_PORT:
        if (buffer.readableBytes() < INT_SIZE) {
            return;
        }
        senderPort = buffer.readInt();
        address = new Address(senderIp.getHostName(), senderPort, senderIp);
        currentState = DecoderState.READ_TYPE;
    case READ_TYPE:
        if (buffer.readableBytes() < BYTE_SIZE) {
            return;
        }
        type = InternalMessage.Type.forId(buffer.readByte());
        currentState = DecoderState.READ_PREAMBLE;
    case READ_PREAMBLE:
        if (buffer.readableBytes() < INT_SIZE) {
            return;
        }
        preamble = buffer.readInt();
        currentState = DecoderState.READ_MESSAGE_ID;
    case READ_MESSAGE_ID:
        if (buffer.readableBytes() < LONG_SIZE) {
            return;
        }
        messageId = buffer.readLong();
        currentState = DecoderState.READ_CONTENT_LENGTH;
    case READ_CONTENT_LENGTH:
        if (buffer.readableBytes() < INT_SIZE) {
            return;
        }
        contentLength = buffer.readInt();
        currentState = DecoderState.READ_CONTENT;
    case READ_CONTENT:
        if (buffer.readableBytes() < contentLength) {
            return;
        }
        if (contentLength > 0) {
            // TODO: Perform a sanity check on the size before allocating
            content = new byte[contentLength];
            buffer.readBytes(content);
        } else {
            content = EMPTY_PAYLOAD;
        }

        switch (type) {
        case REQUEST:
            currentState = DecoderState.READ_SUBJECT_LENGTH;
            break;
        case REPLY:
            currentState = DecoderState.READ_STATUS;
            break;
        default:
            checkState(false, "Must not be here");
        }
        break;
    default:
        break;
    }

    switch (type) {
    case REQUEST:
        switch (currentState) {
        case READ_SUBJECT_LENGTH:
            if (buffer.readableBytes() < SHORT_SIZE) {
                return;
            }
            subjectLength = buffer.readShort();
            currentState = DecoderState.READ_SUBJECT;
        case READ_SUBJECT:
            if (buffer.readableBytes() < subjectLength) {
                return;
            }
            final String subject = readString(buffer, subjectLength, UTF_8);
            InternalRequest message = new InternalRequest(preamble, messageId, address, subject, content);
            out.add(message);
            currentState = DecoderState.READ_TYPE;
            break;
        default:
            break;
        }
        break;
    case REPLY:
        switch (currentState) {
        case READ_STATUS:
            if (buffer.readableBytes() < BYTE_SIZE) {
                return;
            }
            InternalReply.Status status = InternalReply.Status.forId(buffer.readByte());
            InternalReply message = new InternalReply(preamble, messageId, content, status);
            out.add(message);
            currentState = DecoderState.READ_TYPE;
            break;
        default:
            break;
        }
        break;
    default:
        checkState(false, "Must not be here");
    }
}

From source file:io.crate.protocols.postgres.FormatCodes.java

License:Apache License

/**
 * Read format codes from a ByteBuf./*from ww w .j  a  v  a2s. c om*/
 * <p>
 * Buffer must contain:
 * <pre>
 * int16 num formatCodes
 *      foreach:
 *      int16 formatCode
 * </pre>
 */
static FormatCode[] fromBuffer(ByteBuf buffer) {
    short numFormatCodes = buffer.readShort();
    if (numFormatCodes == 0) {
        return EMPTY_FORMAT_CODES;
    }
    FormatCode[] formatCodes = new FormatCode[numFormatCodes];
    for (int i = 0; i < numFormatCodes; i++) {
        formatCodes[i] = FormatCode.values()[buffer.readShort()];
    }
    return formatCodes;
}

From source file:io.crate.protocols.postgres.PostgresWireProtocol.java

License:Apache License

/**
 * Parse Message// ww w . jav a 2  s . c  om
 * header:
 * | 'P' | int32 len
 * <p>
 * body:
 * | string statementName | string query | int16 numParamTypes |
 * foreach param:
 * | int32 type_oid (zero = unspecified)
 */
private void handleParseMessage(ByteBuf buffer, final Channel channel) {
    String statementName = readCString(buffer);
    final String query = readCString(buffer);
    short numParams = buffer.readShort();
    List<DataType> paramTypes = new ArrayList<>(numParams);
    for (int i = 0; i < numParams; i++) {
        int oid = buffer.readInt();
        DataType dataType = PGTypes.fromOID(oid);
        if (dataType == null) {
            throw new IllegalArgumentException(
                    String.format(Locale.ENGLISH, "Can't map PGType with oid=%d to Crate type", oid));
        }
        paramTypes.add(dataType);
    }
    session.parse(statementName, query, paramTypes);
    Messages.sendParseComplete(channel);
}

From source file:io.crate.protocols.postgres.PostgresWireProtocol.java

License:Apache License

/**
 * Bind Message//from   w ww . ja  v  a 2  s  .c  o  m
 * Header:
 * | 'B' | int32 len
 * <p>
 * Body:
 * <pre>
 * | string portalName | string statementName
 * | int16 numFormatCodes
 *      foreach
 *      | int16 formatCode
 * | int16 numParams
 *      foreach
 *      | int32 valueLength
 *      | byteN value
 * | int16 numResultColumnFormatCodes
 *      foreach
 *      | int16 formatCode
 * </pre>
 */
private void handleBindMessage(ByteBuf buffer, Channel channel) {
    String portalName = readCString(buffer);
    String statementName = readCString(buffer);

    FormatCodes.FormatCode[] formatCodes = FormatCodes.fromBuffer(buffer);

    short numParams = buffer.readShort();
    List<Object> params = createList(numParams);
    for (int i = 0; i < numParams; i++) {
        int valueLength = buffer.readInt();
        if (valueLength == -1) {
            params.add(null);
        } else {
            DataType paramType = session.getParamType(statementName, i);
            PGType pgType = PGTypes.get(paramType);
            FormatCodes.FormatCode formatCode = getFormatCode(formatCodes, i);
            switch (formatCode) {
            case TEXT:
                params.add(pgType.readTextValue(buffer, valueLength));
                break;

            case BINARY:
                params.add(pgType.readBinaryValue(buffer, valueLength));
                break;

            default:
                Messages.sendErrorResponse(channel,
                        new UnsupportedOperationException(
                                String.format(Locale.ENGLISH, "Unsupported format code '%d' for param '%s'",
                                        formatCode.ordinal(), paramType.getName())));
                return;
            }
        }
    }

    FormatCodes.FormatCode[] resultFormatCodes = FormatCodes.fromBuffer(buffer);
    session.bind(portalName, statementName, params, resultFormatCodes);
    Messages.sendBindComplete(channel);
}

From source file:io.crate.protocols.postgres.PostgresWireProtocolTest.java

License:Apache License

@Test
public void testDescribePortalMessage() throws Exception {
    PostgresWireProtocol ctx = new PostgresWireProtocol(sqlOperations, new AlwaysOKNullAuthentication(), null);

    EmbeddedChannel channel = new EmbeddedChannel(ctx.decoder, ctx.handler);
    {/* w w w .j a  va2 s. com*/
        ByteBuf buffer = Unpooled.buffer();

        ClientMessages.sendStartupMessage(buffer, "doc");
        ClientMessages.sendParseMessage(buffer, "S1", "select ? in (1, 2, 3)",
                new int[] { PGTypes.get(DataTypes.LONG).oid() });
        ClientMessages.sendBindMessage(buffer, "P1", "S1", Collections.singletonList(1));
        channel.writeInbound(buffer);

        // we're not interested in the startup, parse, or bind replies
        channel.flushOutbound();
        channel.outboundMessages().clear();
    }
    {
        // try portal describe message
        ByteBuf buffer = Unpooled.buffer();
        ClientMessages.sendDescribeMessage(buffer, ClientMessages.DescribeType.PORTAL, "P1");
        channel.writeInbound(buffer);

        // we should get back a RowDescription message
        ByteBuf response = channel.readOutbound();
        assertThat(response.readByte(), is((byte) 'T'));
        assertThat(response.readInt(), is(42));
        assertThat(response.readShort(), is((short) 1));
        assertThat(PostgresWireProtocol.readCString(response), is("($1 IN (1, 2, 3))"));

        assertThat(response.readInt(), is(0));
        assertThat(response.readShort(), is((short) 0));
        assertThat(response.readInt(), is(PGTypes.get(DataTypes.BOOLEAN).oid()));
        assertThat(response.readShort(), is((short) PGTypes.get(DataTypes.BOOLEAN).typeLen()));
        assertThat(response.readInt(), is(PGTypes.get(DataTypes.LONG).typeMod()));
        assertThat(response.readShort(), is((short) 0));
    }
}

From source file:io.crate.protocols.postgres.PostgresWireProtocolTest.java

License:Apache License

@Test
public void testDescribeStatementMessage() throws Exception {
    PostgresWireProtocol ctx = new PostgresWireProtocol(sqlOperations, new AlwaysOKNullAuthentication(), null);

    EmbeddedChannel channel = new EmbeddedChannel(ctx.decoder, ctx.handler);
    {//from  w w w .j a  va2  s . c o  m
        ByteBuf buffer = Unpooled.buffer();

        ClientMessages.sendStartupMessage(buffer, "doc");
        ClientMessages.sendParseMessage(buffer, "S1", "select ? in (1, 2, 3)", new int[0]);
        channel.writeInbound(buffer);

        // we're not interested in the startup, parse, or bind replies
        channel.flushOutbound();
        channel.outboundMessages().clear();
    }
    {
        // try the describe statement variant
        ByteBuf buffer = Unpooled.buffer();
        ClientMessages.sendDescribeMessage(buffer, ClientMessages.DescribeType.STATEMENT, "S1");
        channel.writeInbound(buffer);

        // we should get back a ParameterDescription message
        ByteBuf response = channel.readOutbound();
        assertThat(response.readByte(), is((byte) 't'));
        assertThat(response.readInt(), is(10));
        assertThat(response.readShort(), is((short) 1));
        assertThat(response.readInt(), is(PGTypes.get(DataTypes.LONG).oid()));

        // we should get back a RowDescription message
        response = channel.readOutbound();
        assertThat(response.readByte(), is((byte) 'T'));
        assertThat(response.readInt(), is(42));
        assertThat(response.readShort(), is((short) 1));
        assertThat(PostgresWireProtocol.readCString(response), is("($1 IN (1, 2, 3))"));

        assertThat(response.readInt(), is(0));
        assertThat(response.readShort(), is((short) 0));
        assertThat(response.readInt(), is(PGTypes.get(DataTypes.BOOLEAN).oid()));
        assertThat(response.readShort(), is((short) PGTypes.get(DataTypes.BOOLEAN).typeLen()));
        assertThat(response.readInt(), is(PGTypes.get(DataTypes.LONG).typeMod()));
        assertThat(response.readShort(), is((short) 0));
    }
}

From source file:io.crate.protocols.postgres.types.SmallIntType.java

License:Apache License

@Override
public Object readBinaryValue(ByteBuf buffer, int valueLength) {
    assert valueLength == TYPE_LEN : "length should be " + TYPE_LEN + " because short is int16. Actual length: "
            + valueLength;//from  w  w  w .j  a va2s  . c o  m
    return buffer.readShort();
}

From source file:io.datty.msgpack.core.AbstractMessageReader.java

License:Apache License

public short readShort(ByteBuf buffer) {
    return buffer.readShort();
}