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

The following examples show how to use io.netty.buffer.ByteBuf#resetReaderIndex() . 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: 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 2
Source File: AbstractPacketDecoder.java    From spring-boot-protocol with Apache License 2.0 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
	if (in.isReadable(4)) {
		in.markReaderIndex();
		int packetSize = in.readUnsignedMediumLE();
		if (packetSize > maxPacketSize) {
			throw new TooLongFrameException("Received a packet of size " + packetSize + " but the maximum packet size is " + maxPacketSize);
		}
		int sequenceId = in.readByte();
		if (!in.isReadable(packetSize)) {
			in.resetReaderIndex();
			return;
		}
		ByteBuf packet = in.readSlice(packetSize);

		decodePacket(ctx, sequenceId, packet, out);
	}
}
 
Example 3
Source File: PostgreSQLPacketCodecEngine.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@Override
public void decode(final ChannelHandlerContext context, final ByteBuf in, final List<Object> out, final int readableBytes) {
    int messageTypeLength = 0;
    if ('\0' == in.markReaderIndex().readByte()) {
        in.resetReaderIndex();
    } else {
        messageTypeLength = PostgreSQLPacket.MESSAGE_TYPE_LENGTH;
    }
    int payloadLength = in.readInt();
    int realPacketLength = payloadLength + messageTypeLength;
    if (readableBytes < realPacketLength) {
        in.resetReaderIndex();
        return;
    }
    in.resetReaderIndex();
    out.add(in.readRetainedSlice(payloadLength + messageTypeLength));
}
 
Example 4
Source File: CommandDecoder.java    From simple-rpc-framework with Apache License 2.0 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) {
    if (!byteBuf.isReadable(LENGTH_FIELD_LENGTH)) {
        return;
    }
    byteBuf.markReaderIndex();
    int length = byteBuf.readInt() - LENGTH_FIELD_LENGTH;

    if (byteBuf.readableBytes() < length) {
        byteBuf.resetReaderIndex();
        return;
    }

    Header header = decodeHeader(channelHandlerContext, byteBuf);
    int payloadLength  = length - header.length();
    byte [] payload = new byte[payloadLength];
    byteBuf.readBytes(payload);
    list.add(new Command(header, payload));
}
 
Example 5
Source File: AgentDecoder.java    From bistoury with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
    if (msg.readableBytes() < RemotingHeader.MIN_TOTAL_SIZE) {
        return;
    }

    int magicCode = msg.getInt(msg.readerIndex() + RemotingHeader.LENGTH_FIELD);
    if (magicCode != RemotingHeader.DEFAULT_MAGIC_CODE) {
        throw new IOException("非法数据,MagicCode=" + Integer.toHexString(magicCode));
    }

    msg.markReaderIndex();
    int total = msg.readInt();
    if (msg.readableBytes() < total) {
        msg.resetReaderIndex();
        return;
    }

    short headerSize = msg.readShort();
    RemotingHeader header = decodeHeader(msg);

    int bodyLength = total - headerSize - RemotingHeader.HEADER_SIZE_LEN;
    ByteBuf bodyData = Unpooled.buffer(bodyLength, bodyLength);
    msg.readBytes(bodyData, bodyLength);

    Datagram datagram = new Datagram();
    datagram.setHeader(header);
    datagram.setBody(bodyData);

    out.add(datagram);

}
 
Example 6
Source File: EntityRewrite.java    From ProtocolSupportBungee with GNU Affero General Public License v3.0 5 votes vote down vote up
public PacketWrapper rewrite(PacketWrapper packet, IntUnaryOperator rewritefunc) {
	ByteBuf buf = packet.buf;
	buf.markReaderIndex();
	int packetId = readPacketId(buf);
	EntityRewriteCommand[] chain = rewritechains[packetId];
	if (chain == null) {
		buf.resetReaderIndex();
		return packet;
	}
	ByteBuf tmpBuffer = Allocator.allocateBuffer();
	try {
		writePacketId(tmpBuffer, packetId);
		for (EntityRewriteCommand command : chain) {
			command.rewrite(buf, tmpBuffer, rewritefunc);
		}
		buf.clear();
		if (buf.maxWritableBytes() < tmpBuffer.readableBytes()) {
			packet.trySingleRelease();
			return new PacketWrapper(packet.packet, tmpBuffer);
		} else {
			buf.writeBytes(tmpBuffer);
			tmpBuffer.release();
			return packet;
		}
	} catch (Exception e) {
		tmpBuffer.release();
		throw new RuntimeException("Entity remap error in packet ID " + packetId, e);
	}
}
 
Example 7
Source File: AmqpCodec.java    From qpid-jms with Apache License 2.0 5 votes vote down vote up
/**
 * Given an encoded AMQP Section, decode the value previously written there.
 *
 * @param encoded
 *      the AMQP Section value to decode.
 *
 * @return a Section object read from its encoded form.
 */
public static Section decode(ByteBuf encoded) {
    if (encoded == null || !encoded.isReadable()) {
        return null;
    }

    DecoderImpl decoder = TLS_CODEC.get().decoder;
    decoder.setByteBuffer(encoded.nioBuffer());
    Section result = (Section) decoder.readObject();
    decoder.setByteBuffer(null);
    encoded.resetReaderIndex();

    return result;
}
 
Example 8
Source File: AuthMetadataFlyweightTest.java    From rsocket-java with Apache License 2.0 5 votes vote down vote up
@Test
void shouldEncodeBearerMetadata() {
  String testToken = TEST_BEARER_TOKEN;

  ByteBuf byteBuf =
      AuthMetadataFlyweight.encodeBearerMetadata(
          ByteBufAllocator.DEFAULT, testToken.toCharArray());

  byteBuf.markReaderIndex();
  checkBearerAuthMetadataEncoding(testToken, byteBuf);
  byteBuf.resetReaderIndex();
  checkBearerAuthMetadataEncodingUsingDecoders(testToken, byteBuf);
}
 
Example 9
Source File: TypedPropertiesTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test(expected = IndexOutOfBoundsException.class)
public void testSearchPartiallyEncodedBuffer() {
   final int expectedLength = Integer.BYTES + Byte.BYTES;
   ByteBuf buf = Unpooled.buffer(expectedLength, expectedLength);
   buf.writeByte(DataConstants.NOT_NULL);
   buf.writeInt(1);
   buf.resetReaderIndex();
   searchProperty(SimpleString.toSimpleString(" "), buf, 0);
}
 
Example 10
Source File: UtilsTest.java    From bgpcep with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testLabelUtil() {
    final byte[] expected = { (byte) 0x81, 0x04, 0x01, 0x02, 0x03, 0x04 };
    final ByteBuf out = Unpooled.buffer();
    final ByteBuf body = Unpooled.copiedBuffer(new byte[] { 1, 2, 3, 4 });
    LabelUtil.formatLabel(4, true, true, body, out);
    assertArrayEquals(expected, ByteArray.readAllBytes(out));

    final byte[] ex = { 0, 0x05, 0x01, 0x02, 0x03, 0x04 };
    body.resetReaderIndex();
    LabelUtil.formatLabel(5, null, null, body, out);
    assertArrayEquals(ex, ByteArray.getAllBytes(out));
}
 
Example 11
Source File: RpcNettyDecoder.java    From hasting with MIT License 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in,
		List<Object> out) throws Exception {
	int readableBytes = in.readableBytes();
	if(readableBytes>=NioUtils.RPC_PROTOCOL_HEAD_LEN){
		in.markReaderIndex();
		int type = in.readInt();//type
		long threadId = in.readLong();//threadId
		int index = in.readInt();//index
		int length = in.readInt();// data length
		if(length>RpcUtils.MEM_1M){
			throw new RpcException("rpc data too long "+ length);
		}
		if(in.readableBytes()>=length){
			byte[] buf = new byte[length];
			if(length>0){
				in.readBytes(buf);
			}
			RpcObject rpc = new RpcObject();
			rpc.setType(RpcType.getByType(type));
			rpc.setThreadId(threadId);
			rpc.setIndex(index);
			rpc.setLength(length);
			rpc.setData(buf);
			out.add(rpc);
		}else{
			in.resetReaderIndex();
		}
	}
}
 
Example 12
Source File: NetworkPrepender.java    From The-5zig-Mod with MIT License 5 votes vote down vote up
protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> objects) {
	buffer.markReaderIndex();
	byte[] var4 = new byte[3];

	for (int var5 = 0; var5 < var4.length; ++var5) {
		if (!buffer.isReadable()) {
			buffer.resetReaderIndex();
			return;
		}

		var4[var5] = buffer.readByte();

		if (var4[var5] >= 0) {
			ByteBuf var6 = Unpooled.wrappedBuffer(var4);

			try {
				int var7 = PacketBuffer.readVarIntFromBuffer(var6);

				if (buffer.readableBytes() < var7) {
					buffer.resetReaderIndex();
					return;
				}

				objects.add(buffer.readBytes(var7));
			} finally {
				var6.release();
			}

			return;
		}
	}

	throw new CorruptedFrameException("length wider than 21-bit");
}
 
Example 13
Source File: KryonettyDecoder.java    From kryonetty with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected void decode (ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out)
		throws Exception {
	//Netty 4.1 apparently does not like ByteBuf's "array()" being used for direct buffers,
	//   so a workaround is necessary to extract the byte array needed by the Input class
	byte[] byteArray = new byte[buffer.readableBytes()];
	buffer.readBytes(byteArray);
	buffer.resetReaderIndex();
	
	input.setBuffer(byteArray, buffer.readerIndex(), buffer.readableBytes());
	if (length == -1) {
		// Read length.
		if (buffer.readableBytes() < 4) return;
		length = input.readInt();
		buffer.readerIndex(input.position());
	}
	if (buffer.readableBytes() < length) return;
	length = -1;
	Object object = kryo.readClassAndObject(input);
	// Dumps out bytes for JMeter's TCP Sampler (BinaryTCPClientImpl classname):
	// System.out.println("--");
	// for (int i = buffer.readerIndex() - 4; i < input.position(); i++) {
	// String hex = Integer.toHexString(input.getBuffer()[i] & 0xff);
	// if (hex.length() == 1) hex = "0" + hex;
	// System.out.print(hex.toUpperCase());
	// }
	// System.out.println("\n--");
	buffer.readerIndex(input.position());
	out.add(object);
}
 
Example 14
Source File: Snappy.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * Reads a compressed reference offset and length from the supplied input
 * buffer, seeks back to the appropriate place in the input buffer and
 * writes the found data to the supplied output stream.
 *
 * @param tag The tag used to identify this as a copy is also used to encode
 *     the length and part of the offset
 * @param in The input buffer to read from
 * @param out The output buffer to write to
 * @return The number of bytes appended to the output buffer, or -1 to indicate
 *     "try again later"
 * @throws DecompressionException If the read offset is invalid
 * 从提供的输入缓冲区读取压缩的引用偏移量和长度,返回到输入缓冲区中的适当位置,并将发现的数据写入提供的输出流。
 */
private static int decodeCopyWith4ByteOffset(byte tag, ByteBuf in, ByteBuf out, int writtenSoFar) {
    if (in.readableBytes() < 4) {
        return NOT_ENOUGH_INPUT;
    }

    int initialIndex = out.writerIndex();
    int length = 1 + (tag >> 2 & 0x03F);
    int offset = in.readIntLE();

    validateOffset(offset, writtenSoFar);

    out.markReaderIndex();
    if (offset < length) {
        int copies = length / offset;
        for (; copies > 0; copies--) {
            out.readerIndex(initialIndex - offset);
            out.readBytes(out, offset);
        }
        if (length % offset != 0) {
            out.readerIndex(initialIndex - offset);
            out.readBytes(out, length % offset);
        }
    } else {
        out.readerIndex(initialIndex - offset);
        out.readBytes(out, length);
    }
    out.resetReaderIndex();

    return length;
}
 
Example 15
Source File: PingReqDecoder.java    From vertx-mqtt-broker with Apache License 2.0 5 votes vote down vote up
@Override
void decode(ByteBuf in, List<Object> out) throws Exception {
    //Common decoding part
    in.resetReaderIndex();
    PingReqMessage message = new PingReqMessage();
    if (!decodeCommonHeader(message, 0x00, in)) {
        in.resetReaderIndex();
        return;
    }
    out.add(message);
}
 
Example 16
Source File: PacketCodec.java    From bitchat with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> out) throws Exception {
    // leastPacketLen = 1byte(magic) + 1byte(serialize algorithm) + 1byte(packet type) + 4bytes(content length)
    int leastPacketLen = 7;
    // until we can read at least 7 bytes
    if (in.readableBytes() < leastPacketLen) {
        return;
    }
    // mark reader index at here
    // if no enough bytes arrived
    // we should wait and reset the
    // reader index to here
    in.markReaderIndex();
    // do common check before decode
    byte magic = in.readByte();
    Assert.state(magic == Packet.PACKET_MAGIC, "magic number is invalid");

    byte algorithm = in.readByte();
    Serializer serializer = chooser.choose(algorithm);
    Assert.notNull(serializer, "No serializer is chosen cause the algorithm of packet is invalid");
    byte type = in.readByte();
    int len = in.readInt();
    // until we have the entire packet received
    if (in.readableBytes() < len) {
        // after read some bytes: magic/algorithm/type/len
        // the left readable bytes length is less than len
        // so we need to wait until enough bytes received
        // but we must reset the reader index to we marked
        // before we return
        in.resetReaderIndex();
        return;
    }
    // read content
    byte[] content = new byte[len];
    in.readBytes(content);

    Packet packet = serializer.deserialize(content, DefaultPacket.class);
    out.add(packet);
}
 
Example 17
Source File: TypedPropertiesTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Test
public void testSearchAllProperties() {
   TypedProperties props = new TypedProperties();
   props.putByteProperty(RandomUtil.randomSimpleString(), RandomUtil.randomByte());
   props.putBytesProperty(RandomUtil.randomSimpleString(), RandomUtil.randomBytes());
   props.putBytesProperty(RandomUtil.randomSimpleString(), null);
   props.putBooleanProperty(RandomUtil.randomSimpleString(), RandomUtil.randomBoolean());
   props.putShortProperty(RandomUtil.randomSimpleString(), RandomUtil.randomShort());
   props.putIntProperty(RandomUtil.randomSimpleString(), RandomUtil.randomInt());
   props.putLongProperty(RandomUtil.randomSimpleString(), RandomUtil.randomLong());
   props.putFloatProperty(RandomUtil.randomSimpleString(), RandomUtil.randomFloat());
   props.putDoubleProperty(RandomUtil.randomSimpleString(), RandomUtil.randomDouble());
   props.putCharProperty(RandomUtil.randomSimpleString(), RandomUtil.randomChar());
   props.putSimpleStringProperty(RandomUtil.randomSimpleString(), RandomUtil.randomSimpleString());
   props.putSimpleStringProperty(RandomUtil.randomSimpleString(), null);
   final SimpleString value = RandomUtil.randomSimpleString();
   props.putSimpleStringProperty(RandomUtil.randomSimpleString(), value);
   ByteBuf buf = Unpooled.buffer();
   props.encode(buf);
   buf.resetReaderIndex();
   Assert.assertFalse(searchProperty(value, buf, 0));
   props.forEachKey(key -> {
      Assert.assertTrue(searchProperty(key, buf, 0));
      Assert.assertTrue(searchProperty(SimpleString.toSimpleString(key.toString()), buf, 0));
      // concat a string just to check if the search won't perform an eager search to find the string pattern
      Assert.assertFalse(searchProperty(key.concat(" "), buf, 0));
   });
}
 
Example 18
Source File: CompositeMetadataCodec.java    From rsocket-java with Apache License 2.0 4 votes vote down vote up
/**
 * Decode the next metadata entry (a mime header + content pair of {@link ByteBuf}) from a {@link
 * ByteBuf} that contains at least enough bytes for one more such entry. These buffers are
 * actually slices of the full metadata buffer, and this method doesn't move the full metadata
 * buffer's {@link ByteBuf#readerIndex()}. As such, it requires the user to provide an {@code
 * index} to read from. The next index is computed by calling {@link #computeNextEntryIndex(int,
 * ByteBuf, ByteBuf)}. Size of the first buffer (the "header buffer") drives which decoding method
 * should be further applied to it.
 *
 * <p>The header buffer is either:
 *
 * <ul>
 *   <li>made up of a single byte: this represents an encoded mime id, which can be further
 *       decoded using {@link #decodeMimeIdFromMimeBuffer(ByteBuf)}
 *   <li>made up of 2 or more bytes: this represents an encoded mime String + its length, which
 *       can be further decoded using {@link #decodeMimeTypeFromMimeBuffer(ByteBuf)}. Note the
 *       encoded length, in the first byte, is skipped by this decoding method because the
 *       remaining length of the buffer is that of the mime string.
 * </ul>
 *
 * @param compositeMetadata the source {@link ByteBuf} that originally contains one or more
 *     metadata entries
 * @param entryIndex the {@link ByteBuf#readerIndex()} to start decoding from. original reader
 *     index is kept on the source buffer
 * @param retainSlices should produced metadata entry buffers {@link ByteBuf#slice() slices} be
 *     {@link ByteBuf#retainedSlice() retained}?
 * @return a {@link ByteBuf} array of length 2 containing the mime header buffer
 *     <strong>slice</strong> and the content buffer <strong>slice</strong>, or one of the
 *     zero-length error constant arrays
 */
public static ByteBuf[] decodeMimeAndContentBuffersSlices(
    ByteBuf compositeMetadata, int entryIndex, boolean retainSlices) {
  compositeMetadata.markReaderIndex();
  compositeMetadata.readerIndex(entryIndex);

  if (compositeMetadata.isReadable()) {
    ByteBuf mime;
    int ridx = compositeMetadata.readerIndex();
    byte mimeIdOrLength = compositeMetadata.readByte();
    if ((mimeIdOrLength & STREAM_METADATA_KNOWN_MASK) == STREAM_METADATA_KNOWN_MASK) {
      mime =
          retainSlices
              ? compositeMetadata.retainedSlice(ridx, 1)
              : compositeMetadata.slice(ridx, 1);
    } else {
      // M flag unset, remaining 7 bits are the length of the mime
      int mimeLength = Byte.toUnsignedInt(mimeIdOrLength) + 1;

      if (compositeMetadata.isReadable(
          mimeLength)) { // need to be able to read an extra mimeLength bytes
        // here we need a way for the returned ByteBuf to differentiate between a
        // 1-byte length mime type and a 1 byte encoded mime id, preferably without
        // re-applying the byte mask. The easiest way is to include the initial byte
        // and have further decoding ignore the first byte. 1 byte buffer == id, 2+ byte
        // buffer == full mime string.
        mime =
            retainSlices
                ?
                // we accommodate that we don't read from current readerIndex, but
                // readerIndex - 1 ("0"), for a total slice size of mimeLength + 1
                compositeMetadata.retainedSlice(ridx, mimeLength + 1)
                : compositeMetadata.slice(ridx, mimeLength + 1);
        // we thus need to skip the bytes we just sliced, but not the flag/length byte
        // which was already skipped in initial read
        compositeMetadata.skipBytes(mimeLength);
      } else {
        compositeMetadata.resetReaderIndex();
        throw new IllegalStateException("metadata is malformed");
      }
    }

    if (compositeMetadata.isReadable(3)) {
      // ensures the length medium can be read
      final int metadataLength = compositeMetadata.readUnsignedMedium();
      if (compositeMetadata.isReadable(metadataLength)) {
        ByteBuf metadata =
            retainSlices
                ? compositeMetadata.readRetainedSlice(metadataLength)
                : compositeMetadata.readSlice(metadataLength);
        compositeMetadata.resetReaderIndex();
        return new ByteBuf[] {mime, metadata};
      } else {
        compositeMetadata.resetReaderIndex();
        throw new IllegalStateException("metadata is malformed");
      }
    } else {
      compositeMetadata.resetReaderIndex();
      throw new IllegalStateException("metadata is malformed");
    }
  }
  compositeMetadata.resetReaderIndex();
  throw new IllegalArgumentException(
      String.format("entry index %d is larger than buffer size", entryIndex));
}
 
Example 19
Source File: RntbdContext.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
public static RntbdContext decode(final ByteBuf in) {

        in.markReaderIndex();

        final RntbdResponseStatus responseStatus = RntbdResponseStatus.decode(in);
        final int statusCode = responseStatus.getStatusCode();
        final int headersLength = responseStatus.getHeadersLength();

        if (statusCode < 200 || statusCode >= 400) {
            if (!RntbdFramer.canDecodePayload(in, in.readerIndex() + headersLength)) {
                in.resetReaderIndex();
                return null;
            }
        }

        final Headers headers = Headers.decode(in.readSlice(headersLength));

        if (statusCode < 200 || statusCode >= 400) {

            final ObjectNode details = RntbdObjectMapper.readTree(in.readSlice(in.readIntLE()));
            final HashMap<String, Object> map = new HashMap<>(4);

            if (headers.clientVersion.isPresent()) {
                map.put("requiredClientVersion", headers.clientVersion.getValue());
            }

            if (headers.protocolVersion.isPresent()) {
                map.put("requiredProtocolVersion", headers.protocolVersion.getValue());
            }

            if (headers.serverAgent.isPresent()) {
                map.put("serverAgent", headers.serverAgent.getValue());
            }

            if (headers.serverVersion.isPresent()) {
                map.put("serverVersion", headers.serverVersion.getValue());
            }

            throw new RntbdContextException(responseStatus.getStatus(), details, Collections.unmodifiableMap(map));
        }

        return new RntbdContext(responseStatus, headers);
    }
 
Example 20
Source File: Utf8Utils.java    From hivemq-community-edition with Apache License 2.0 3 votes vote down vote up
/**
 * ByteBuf implementation of guavas Utf8.isWellFormed(final byte[] bytes)
 */
public static boolean isWellFormed(final ByteBuf byteBuf, final int utf8StringLength) {

    Preconditions.checkNotNull(byteBuf);

    byteBuf.markReaderIndex();

    final boolean wellFormed = isSliceWellFormed(byteBuf.slice(byteBuf.readerIndex(), utf8StringLength), utf8StringLength);

    byteBuf.resetReaderIndex();

    return wellFormed;

}