Java Code Examples for io.netty.buffer.ByteBuf#readShort()

The following examples show how to use io.netty.buffer.ByteBuf#readShort() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ProduceMessageResponseCodec.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
public ProduceMessageResponse decode(JoyQueueHeader header, ByteBuf buffer) throws Exception {
    short dataSize = buffer.readShort();
    Map<String, ProduceMessageAckData> data = Maps.newHashMap();
    for (int i = 0; i < dataSize; i++) {
        String topic = Serializer.readString(buffer, Serializer.SHORT_SIZE);
        JoyQueueCode code = JoyQueueCode.valueOf(buffer.readInt());
        short itemSize = buffer.readShort();
        List<ProduceMessageAckItemData> item = Lists.newArrayListWithCapacity(itemSize);

        for (int j = 0; j < itemSize; j++) {
            short partition = buffer.readShort();
            long index = buffer.readLong();
            long startTime = buffer.readLong();
            item.add(new ProduceMessageAckItemData(partition, index, startTime));
        }
        data.put(topic, new ProduceMessageAckData(item, code));
    }

    ProduceMessageResponse produceMessageResponse = new ProduceMessageResponse();
    produceMessageResponse.setData(data);
    return produceMessageResponse;
}
 
Example 2
Source File: FetchTopicMessageRequestCodec.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Override
public FetchTopicMessageRequest decode(JoyQueueHeader header, ByteBuf buffer) throws Exception {
    FetchTopicMessageRequest fetchTopicMessageRequest = new FetchTopicMessageRequest();

    short topicSize = buffer.readShort();
    Map<String, FetchTopicMessageData> topics = Maps.newHashMapWithExpectedSize(topicSize);
    for (int i = 0; i < topicSize; i++) {
        String topic = Serializer.readString(buffer, Serializer.SHORT_SIZE);
        short count = buffer.readShort();
        FetchTopicMessageData fetchTopicMessageData = new FetchTopicMessageData();
        fetchTopicMessageData.setCount(count);
        topics.put(topic, fetchTopicMessageData);
    }

    fetchTopicMessageRequest.setTopics(topics);
    fetchTopicMessageRequest.setApp(Serializer.readString(buffer, Serializer.SHORT_SIZE));
    fetchTopicMessageRequest.setAckTimeout(buffer.readInt());
    fetchTopicMessageRequest.setLongPollTimeout(buffer.readInt());
    return fetchTopicMessageRequest;
}
 
Example 3
Source File: DFClusterActor.java    From dfactor with MIT License 6 votes vote down vote up
@Override
public int onQueryMsgActorId(int requestId, int channelId, InetSocketAddress addrRemote, Object msg) {
	ByteBuf buf = (ByteBuf) msg;
	buf.markReaderIndex();
	int cmd = buf.readShort();
	switch(cmd){
	case DMCmd.UserMsg:
		_procUserMsg(cmd, buf);
		break;
	case DMCmd.RpcFail:
		_procRpcCallFail(cmd, buf);
		break;
	default:   
		buf.resetReaderIndex();
		return id;
	}
	return 0;
}
 
Example 4
Source File: ListServices.java    From ethernet-ip with Apache License 2.0 5 votes vote down vote up
public static ServiceInformation decode(ByteBuf buffer) {
    int typeCode = buffer.readUnsignedShort();
    int itemLength = buffer.readShort();
    int version = buffer.readShort();
    int capabilityFlags = buffer.readShort();
    String name = readString(buffer, itemLength - 4).trim();
    return new ServiceInformation(typeCode, version, capabilityFlags, name);
}
 
Example 5
Source File: FetchClusterRequestCodec.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public Object decode(JoyQueueHeader header, ByteBuf buffer) throws Exception {
    FetchClusterRequest fetchClusterRequest = new FetchClusterRequest();

    short topicSize = buffer.readShort();
    List<String> topics = Lists.newArrayListWithCapacity(topicSize);
    for (int i = 0; i < topicSize; i++) {
        topics.add(Serializer.readString(buffer, Serializer.SHORT_SIZE));
    }

    fetchClusterRequest.setTopics(topics);
    fetchClusterRequest.setApp(Serializer.readString(buffer, Serializer.SHORT_SIZE));
    return fetchClusterRequest;
}
 
Example 6
Source File: ByteToPacketCodec.java    From IMServer with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

    Packet packet = new Packet(
            in.readInt(),
            in.readShort(),
            in.readShort(),
            in.readShort(),
            in.readShort(),
            in.readBytes(in.readableBytes())
    );
    out.add(packet);
}
 
Example 7
Source File: MiddleEntityRelMoveLook.java    From ProtocolSupport with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void readServerData(ByteBuf serverdata) {
	super.readServerData(serverdata);
	relX = serverdata.readShort();
	relY = serverdata.readShort();
	relZ = serverdata.readShort();
	yaw = serverdata.readByte();
	pitch = serverdata.readByte();
	onGround = serverdata.readBoolean();
}
 
Example 8
Source File: AddConsumerRequestCodec.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public AddConsumerRequest decode(JoyQueueHeader header, ByteBuf buffer) throws Exception {
    AddConsumerRequest addConsumerRequest = new AddConsumerRequest();

    short topicSize = buffer.readShort();
    List<String> topics = Lists.newArrayListWithCapacity(topicSize);
    for (int i = 0; i < topicSize; i++) {
        topics.add(Serializer.readString(buffer, Serializer.SHORT_SIZE));
    }

    addConsumerRequest.setTopics(topics);
    addConsumerRequest.setApp(Serializer.readString(buffer, Serializer.SHORT_SIZE));
    addConsumerRequest.setSequence(buffer.readLong());
    return addConsumerRequest;
}
 
Example 9
Source File: MiddleSpawnExpOrb.java    From ProtocolSupport with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
protected void readServerData(ByteBuf serverdata) {
	entity = new NetworkEntity(null, VarNumberSerializer.readVarInt(serverdata), NetworkEntityType.EXP_ORB);
	x = serverdata.readDouble();
	y = serverdata.readDouble();
	z = serverdata.readDouble();
	count = serverdata.readShort();
}
 
Example 10
Source File: WebSocket08FrameDecoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/** */
protected void checkCloseFrameBody(
        ChannelHandlerContext ctx, ByteBuf buffer) {
    if (buffer == null || !buffer.isReadable()) {
        return;
    }
    if (buffer.readableBytes() == 1) {
        protocolViolation(ctx, "Invalid close frame body");
    }

    // Save reader index
    int idx = buffer.readerIndex();
    buffer.readerIndex(0);

    // Must have 2 byte integer within the valid range
    int statusCode = buffer.readShort();
    if (statusCode >= 0 && statusCode <= 999 || statusCode >= 1004 && statusCode <= 1006
            || statusCode >= 1012 && statusCode <= 2999) {
        protocolViolation(ctx, "Invalid close frame getStatus code: " + statusCode);
    }

    // May have UTF-8 message
    if (buffer.isReadable()) {
        try {
            new Utf8Validator().check(buffer);
        } catch (CorruptedFrameException ex) {
            protocolViolation(ctx, ex);
        }
    }

    // Restore reader index
    buffer.readerIndex(idx);
}
 
Example 11
Source File: FindCoordinatorResponseCodec.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public FindCoordinatorResponse decode(JoyQueueHeader header, ByteBuf buffer) throws Exception {
    FindCoordinatorResponse findCoordinatorResponse = new FindCoordinatorResponse();
    Map<String, FindCoordinatorAckData> coordinators = Maps.newHashMap();

    short topicSize = buffer.readShort();
    for (int i = 0; i < topicSize; i++) {
        String topic = Serializer.readString(buffer, Serializer.SHORT_SIZE);
        BrokerNode node = null;
        int brokerId = buffer.readInt();
        if (brokerId != NONE_BROKER_ID) {
            node = new BrokerNode();
            node.setId(brokerId);
            node.setHost(Serializer.readString(buffer, Serializer.SHORT_SIZE));
            node.setPort(buffer.readInt());
            node.setDataCenter(Serializer.readString(buffer, Serializer.SHORT_SIZE));
            node.setNearby(buffer.readBoolean());
            node.setWeight(buffer.readInt());
        }

        JoyQueueCode code = JoyQueueCode.valueOf(buffer.readInt());
        FindCoordinatorAckData findCoordinatorAckData = new FindCoordinatorAckData(node, code);
        coordinators.put(topic, findCoordinatorAckData);
    }

    findCoordinatorResponse.setCoordinators(coordinators);
    return findCoordinatorResponse;
}
 
Example 12
Source File: AddPartitionsToTxnCodec.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public AddPartitionsToTxnRequest decode(KafkaHeader header, ByteBuf buffer) throws Exception {
    String transactionId = Serializer.readString(buffer, Serializer.SHORT_SIZE);
    long producerId = buffer.readLong();
    short producerEpoch = buffer.readShort();

    int topicSize = Math.max(buffer.readInt(), 0);
    Map<String, List<Integer>> partitions = Maps.newHashMapWithExpectedSize(topicSize);

    for (int i = 0; i < topicSize; i++) {
        String topic = Serializer.readString(buffer, Serializer.SHORT_SIZE);
        int partitionSize = Math.max(buffer.readInt(), 0);
        List<Integer> partitionList = Lists.newArrayListWithCapacity(partitionSize);
        for (int j = 0; j < partitionSize; j++) {
            partitionList.add(buffer.readInt());
        }

        partitions.put(topic, partitionList);
    }

    AddPartitionsToTxnRequest addPartitionsToTxnRequest = new AddPartitionsToTxnRequest();
    addPartitionsToTxnRequest.setTransactionId(transactionId);
    addPartitionsToTxnRequest.setProducerId(producerId);
    addPartitionsToTxnRequest.setProducerEpoch(producerEpoch);
    addPartitionsToTxnRequest.setPartitions(partitions);
    return addPartitionsToTxnRequest;
}
 
Example 13
Source File: SToCMessage.java    From Artifacts with MIT License 5 votes vote down vote up
/**
    * Convert from the supplied buffer into your specific message type
    * @param buffer 
    */
@Override
public void fromBytes(ByteBuf buffer) {
	//System.out.println("Decoding General Packet!");
       
	this.data = new byte[buffer.readShort()];
       buffer.readBytes(this.data);
}
 
Example 14
Source File: DefaultLispSignature.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public LispSignature readFrom(ByteBuf byteBuf) throws LispParseError,
                        LispReaderException, DeserializationException {

    // record TTL -> 32 bits
    int recordTtl = byteBuf.readInt();

    // signature expiration -> 32 bits
    int sigExpiration = byteBuf.readInt();

    // signature inception -> 32 bits
    int sigInception = byteBuf.readInt();

    // key tag -> 16 bits
    short keyTag = byteBuf.readShort();

    // signature length -> 16 bits
    short sigLength = byteBuf.readShort();

    // signature algorithm -> 8 bits
    byte sigAlgorithm = byteBuf.readByte();

    byteBuf.skipBytes(RESERVED_SKIP_LENGTH);

    // TODO: the size of signature should be determined by sigAlgorithm
    int signature = byteBuf.readInt();

    return new DefaultSignatureBuilder()
                    .withRecordTtl(recordTtl)
                    .withSigExpiration(sigExpiration)
                    .withSigInception(sigInception)
                    .withKeyTag(keyTag)
                    .withSigLength(sigLength)
                    .withSigAlgorithm(sigAlgorithm)
                    .withSignature(signature)
                    .build();
}
 
Example 15
Source File: MessageSerializer.java    From WeCross with Apache License 2.0 5 votes vote down vote up
private void readHeader(Message message, ByteBuf in) throws UnsupportedEncodingException {
    Integer length = in.readInt();
    Short type = in.readShort();

    byte[] dst = new byte[32];
    in.readBytes(dst);
    String seq = new String(dst, "utf-8");

    Integer result = in.readInt();

    message.setLength(length);
    message.setType(type);
    message.setSeq(seq);
    message.setResult(result);
}
 
Example 16
Source File: PostgresWireProtocol.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Bind Message
 * 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);
}
 
Example 17
Source File: PoolBlock.java    From hasor with Apache License 2.0 5 votes vote down vote up
public void fillFrom(ByteBuf formData) {
    if (formData == null) {
        return;
    }
    //
    short attrPoolSize = (short) (PoolMaxSize & formData.readShort());
    for (int i = 0; i < attrPoolSize; i++) {
        int length = formData.readInt();
        this.poolMap = ArrayUtils.add(this.poolMap, length);
    }
    this.poolData.writeBytes(formData);
}
 
Example 18
Source File: MiddleInventorySetSlot.java    From ProtocolSupport with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
protected void readServerData(ByteBuf serverdata) {
	windowId = serverdata.readByte();
	slot = serverdata.readShort();
	itemstack = ItemStackSerializer.readItemStack(serverdata);
}
 
Example 19
Source File: HeaderTransport.java    From drift with Apache License 2.0 4 votes vote down vote up
/**
 * Decodes the ByteBuf into a HeaderFrame transferring the reference ownership.
 * @param buffer buffer to be decoded; reference count ownership is transferred to this method
 * @return the decoded frame; caller is responsible for releasing this object
 */
public static ThriftFrame decodeFrame(ByteBuf buffer)
{
    ByteBuf messageHeader = null;
    try {
        // frame header
        short magic = buffer.readShort();
        verify(magic == HEADER_MAGIC, "Invalid header magic");
        short flags = buffer.readShort();
        boolean outOfOrderResponse;
        switch (flags) {
            case FLAGS_NONE:
                outOfOrderResponse = false;
                break;
            case FLAG_SUPPORT_OUT_OF_ORDER:
                outOfOrderResponse = true;
                break;
            default:
                throw new IllegalArgumentException("Unsupported header flags: " + flags);
        }
        int frameSequenceId = buffer.readInt();
        int headerSize = buffer.readShort() << 2;
        messageHeader = buffer.readBytes(headerSize);

        // encoding info
        byte protocolId = messageHeader.readByte();
        Protocol protocol = Protocol.getProtocolByHeaderTransportId(protocolId);
        byte numberOfTransforms = messageHeader.readByte();
        if (numberOfTransforms > 0) {
            // currently there are only two transforms, a cryptographic extension which is deprecated, and gzip which is too expensive
            throw new IllegalArgumentException("Unsupported transform");
        }

        // headers
        // todo what about duplicate headers?
        ImmutableMap.Builder<String, String> allHeaders = ImmutableMap.builder();
        allHeaders.putAll(decodeHeaders(NORMAL_HEADERS, messageHeader));
        allHeaders.putAll(decodeHeaders(PERSISTENT_HEADERS, messageHeader));

        // message
        ByteBuf message = buffer.readBytes(buffer.readableBytes());

        // header frame wraps message byte buffer, so message should not be release yet
        return new ThriftFrame(frameSequenceId, message, allHeaders.build(), HEADER, protocol, outOfOrderResponse);
    }
    finally {
        // message header in an independent buffer and must be released
        if (messageHeader != null) {
            messageHeader.release();
        }

        // input buffer has been consumed and transformed into a HeaderFrame, so release it
        buffer.release();
    }
}
 
Example 20
Source File: Chunk1_14Type.java    From ViaVersion with MIT License 4 votes vote down vote up
@Override
public Chunk read(ByteBuf input, ClientWorld world) throws Exception {
    int chunkX = input.readInt();
    int chunkZ = input.readInt();

    boolean fullChunk = input.readBoolean();
    int primaryBitmask = Type.VAR_INT.readPrimitive(input);
    CompoundTag heightMap = Type.NBT.read(input);

    Type.VAR_INT.readPrimitive(input);

    // Read sections
    ChunkSection[] sections = new ChunkSection[16];
    for (int i = 0; i < 16; i++) {
        if ((primaryBitmask & (1 << i)) == 0) continue; // Section not set

        short nonAirBlocksCount = input.readShort();
        ChunkSection section = Types1_13.CHUNK_SECTION.read(input);
        section.setNonAirBlocksCount(nonAirBlocksCount);
        sections[i] = section;
    }

    int[] biomeData = fullChunk ? new int[256] : null;
    if (fullChunk) {
        for (int i = 0; i < 256; i++) {
            biomeData[i] = input.readInt();
        }
    }

    List<CompoundTag> nbtData = new ArrayList<>(Arrays.asList(Type.NBT_ARRAY.read(input)));

    // Read all the remaining bytes (workaround for #681)
    if (input.readableBytes() > 0) {
        byte[] array = Type.REMAINING_BYTES.read(input);
        if (Via.getManager().isDebug()) {
            Via.getPlatform().getLogger().warning("Found " + array.length + " more bytes than expected while reading the chunk: " + chunkX + "/" + chunkZ);
        }
    }

    return new BaseChunk(chunkX, chunkZ, fullChunk, false, primaryBitmask, sections, biomeData, heightMap, nbtData);
}