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

The following examples show how to use io.netty.buffer.ByteBuf#readBytes() . 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: SocketEchoTest.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead0(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
    byte[] actual = new byte[in.readableBytes()];
    in.readBytes(actual);

    int lastIdx = counter;
    for (int i = 0; i < actual.length; i ++) {
        assertEquals(data[i + lastIdx], actual[i]);
    }

    if (channel.parent() != null) {
        channel.write(Unpooled.wrappedBuffer(actual));
    }

    counter += actual.length;
}
 
Example 2
Source File: DefaultServerPushProtocol.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
public SPBody decodeBodyByteBuf(ByteBuf bodyByteBuf) {
    try {
        int readableBytes = bodyByteBuf.readableBytes();
        byte[] bodyBytes = new byte[readableBytes];
        bodyByteBuf.readBytes(bodyBytes);
        Schema<SPBody> schema = RuntimeSchema.getSchema(SPBody.class);
        SPBody spBody = new SPBody();
        ProtobufIOUtil.mergeFrom(bodyBytes, spBody, schema);
        return spBody;
    } catch (Exception e) {
        throw new RpcException(e);
    } finally {
        if (bodyByteBuf != null) {
            bodyByteBuf.release();
        }
    }
}
 
Example 3
Source File: NetworkCompressionDecoder.java    From The-5zig-Mod with GNU General Public License v3.0 6 votes vote down vote up
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws DataFormatException {
	if (in.readableBytes() != 0) {
		int packetLength = PacketBuffer.readVarIntFromBuffer(in);

		if (packetLength == 0) {
			out.add(in.readBytes(in.readableBytes()));
		} else {
			if (packetLength < this.threshold) {
				throw new DecoderException("Badly compressed packet - size of " + packetLength + " is below server threshold of " + this.threshold);
			}

			if (packetLength > 2097152) {
				throw new DecoderException("Badly compressed packet - size of " + packetLength + " is larger than protocol maximum of " + 2097152);
			}

			byte[] compressedData = new byte[in.readableBytes()];
			in.readBytes(compressedData);
			this.inflater.setInput(compressedData);
			byte[] decompressedData = new byte[packetLength];
			this.inflater.inflate(decompressedData);
			out.add(Unpooled.wrappedBuffer(decompressedData));
			this.inflater.reset();
		}
	}
}
 
Example 4
Source File: AMOPVerifyUtil.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public String parseDataFromPush(Integer length, byte[] data) {
    ByteBuf byteBuf = PooledByteBufAllocator.DEFAULT.buffer(length);
    byteBuf.writeBytes(data);
    int topicLen = byteBuf.readUnsignedByte() - 1;
    logger.info("topic length:{}", topicLen);
    byte[] topicBytes = new byte[topicLen];
    byteBuf.readBytes(topicBytes, 0, topicLen);
    String topic = new String(topicBytes);
    logger.info("topic len:{} topic:{}", topicLen, topic);

    int contentLen = (byteBuf.readShort());
    logger.info("read unsigned contentlen:{}", contentLen);
    byte[] contentBytes = new byte[contentLen];
    byteBuf.readBytes(contentBytes, 0, contentLen);
    String content = new String(contentBytes);
    logger.info("content len:{} topic:{}", contentLen, content);
    return content;
}
 
Example 5
Source File: H2HSignatureFactory.java    From Hive2Hive with MIT License 6 votes vote down vote up
@Override
public PublicKey decodePublicKey(ByteBuf buf) {
	if (buf.readableBytes() < 2) {
		return null;
	}
	int len = buf.getUnsignedShort(buf.readerIndex());

	if (buf.readableBytes() - 2 < len) {
		return null;
	}
	buf.skipBytes(2);

	if (len <= 0) {
		return PeerBuilder.EMPTY_PUBLIC_KEY;
	}

	byte[] me = new byte[len];
	buf.readBytes(me);
	return decodePublicKey(me);
}
 
Example 6
Source File: KafkaBufferUtils.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
public static List<RawTaggedField> readRawTaggedFields(ByteBuf buffer) {
    int size = readUnsignedVarint(buffer);
    if (size == 0) {
        return Collections.emptyList();
    }
    List<RawTaggedField> result = Lists.newLinkedList();
    for (int i = 0; i < size; i++) {
        int tag = readUnsignedVarint(buffer);
        int length = readUnsignedVarint(buffer);
        byte[] data = new byte[length];
        buffer.readBytes(length);
        result.add(new RawTaggedField(tag, data));
    }
    return result;
}
 
Example 7
Source File: VncAuthDecoder.java    From jfxvnc with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
  if (!in.isReadable(16)) {
    return;
  }
  byte[] challenge = new byte[16];
  in.readBytes(challenge);
  out.add(new VncAuthSecurityMessage(challenge));
}
 
Example 8
Source File: LispAppDataLcafAddress.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public LispAppDataLcafAddress readFrom(ByteBuf byteBuf) throws LispParseError, LispReaderException {

    LispLcafAddress.deserializeCommon(byteBuf);

    byte[] ipTosByte = new byte[3];
    byteBuf.readBytes(ipTosByte);

    byte protocol = (byte) byteBuf.readUnsignedByte();
    int ipTos = getPartialInt(ipTosByte);
    short localPortLow = (short) byteBuf.readUnsignedShort();
    short localPortHigh = (short) byteBuf.readUnsignedShort();
    short remotePortLow = (short) byteBuf.readUnsignedShort();
    short remotePortHigh = (short) byteBuf.readUnsignedShort();

    LispAfiAddress address = new LispAfiAddress.AfiAddressReader().readFrom(byteBuf);

    return new AppDataAddressBuilder()
            .withProtocol(protocol)
            .withIpTos(ipTos)
            .withLocalPortLow(localPortLow)
            .withLocalPortHigh(localPortHigh)
            .withRemotePortLow(remotePortLow)
            .withRemotePortHigh(remotePortHigh)
            .withAddress(address)
            .build();
}
 
Example 9
Source File: GetAllMetadataResponseCodec.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
@Override
public GetAllMetadataResponse decode(Header header, ByteBuf buffer) throws Exception {
    int length = buffer.readInt();
    byte[] json = new byte[length];
    buffer.readBytes(json);

    GetAllMetadataResponse allMetadataResponse = new GetAllMetadataResponse();
    allMetadataResponse.setMetadata((AllMetadata) parseJson(json, AllMetadata.class));
    return allMetadataResponse;
}
 
Example 10
Source File: IMMessageManager.java    From werewolf_server with Apache License 2.0 5 votes vote down vote up
/**
 * 群聊文字消息转发
 * @param body 消息体
 */
public static void sendGroupTextReq(ByteBuf body){
    int fromId = body.readInt();
    byte[] contentByte = new byte[body.readableBytes()];  
    //4、复制内容到字节数组b  
    body.readBytes(contentByte);  
    Map<Integer, UserChannel> userChannels = IMChannelGroup.instance().getChannels();
    userChannels.forEach((userId,userChannel)->{
    	Channel toChannel = userChannel.getChannel();
    	if(toChannel==null){
    	    return;
        }
    	byte[] fromName = userChannels.get(fromId).getUsername().getBytes();
    	
    	ByteBuf msg = toChannel.alloc().buffer(contentByte.length + fromName.length + 12);
    	
        msg.writeInt(fromId);
        
        msg.writeInt(fromName.length);

        msg.writeBytes(fromName);
        
        msg.writeInt(contentByte.length);
        msg.writeBytes(contentByte);
        Packet packet = new Packet(msg.readableBytes()+12, ProtocolConstant.SID_MSG,ProtocolConstant.CID_MSG_TEXT_RESP,
                msg);


        toChannel.writeAndFlush(packet);
        System.out.println("send to  username: %s, msg: %s"+body);
    });
}
 
Example 11
Source File: BigIntegerDecoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
    // Wait until the length prefix is available.
    if (in.readableBytes() < 5) {
        return;
    }

    in.markReaderIndex();

    // Check the magic number.
    int magicNumber = in.readUnsignedByte();
    if (magicNumber != 'F') {
        in.resetReaderIndex();
        throw new CorruptedFrameException("Invalid magic number: " + magicNumber);
    }

    // Wait until the whole data is available.
    int dataLength = in.readInt();
    if (in.readableBytes() < dataLength) {
        in.resetReaderIndex();
        return;
    }

    // Convert the received data into a new BigInteger.
    byte[] decoded = new byte[dataLength];
    in.readBytes(decoded);

    out.add(new BigInteger(decoded));
}
 
Example 12
Source File: FrontendDecode.java    From NettyReverseProxy with Apache License 2.0 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    // 防止不发报文就关闭连接出现的错误
    if (!in.isReadable()) {
        return;
    }
    LOGGER.info(String.format("[%s]收到数据:%s",  (ctx.channel().remoteAddress()).toString(), ByteBufUtil.hexDump(in)));
    byte[] ss = new byte[in.readableBytes()];

    in.readBytes(ss);

    out.add(ss);
}
 
Example 13
Source File: ByteBufferAsyncWritableChannelTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
@Test
public void commonCaseTestForNettyByteBuf() throws Exception {
  for (boolean useCompositeByteBuf : Arrays.asList(false, true)) {
    ByteBufferAsyncWritableChannel channel = new ByteBufferAsyncWritableChannel();
    assertTrue("Channel is not open", channel.isOpen());
    assertNull("There should have been no chunk returned", channel.getNextChunk(0));
    ChannelWriter channelWriter = new ChannelWriter(channel, true, useCompositeByteBuf);
    channelWriter.writeToChannel(10);

    int chunkCount = 0;
    ByteBuf chunk = channel.getNextByteBuf();
    while (chunk != null) {
      WriteData writeData = channelWriter.writes.get(chunkCount);
      int chunkSize = chunk.readableBytes();
      byte[] writtenChunk = writeData.writtenChunk;
      byte[] readChunk = new byte[writtenChunk.length];
      chunk.readBytes(readChunk);
      assertArrayEquals("Data unequal", writtenChunk, readChunk);
      channel.resolveOldestChunk(null);
      assertEquals("Unexpected write size (future)", chunkSize, writeData.future.get().longValue());
      assertEquals("Unexpected write size (callback)", chunkSize, writeData.writeCallback.bytesWritten);
      chunkCount++;
      chunk = channel.getNextByteBuf(0);
    }
    assertEquals("Mismatch in number of ByteBufs", channelWriter.writes.size(), chunkCount);
    channel.close();
    assertFalse("Channel is still open", channel.isOpen());
    assertNull("There should have been no ByteBuf returned", channel.getNextByteBuf());
    assertNull("There should have been no ByteBuf returned", channel.getNextByteBuf(0));
  }
}
 
Example 14
Source File: SocketUtils.java    From tx-lcn with Apache License 2.0 5 votes vote down vote up
public static String getJson(Object msg) {
    String json;
    try {
        ByteBuf buf = (ByteBuf) msg;
        byte[] bytes = new byte[buf.readableBytes()];
        buf.readBytes(bytes);
        json = new String(bytes);
    } finally {
        ReferenceCountUtil.release(msg);
    }
    return json;

}
 
Example 15
Source File: DataTypeCodec.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
private static Numeric binaryDecodeUnsignedInt8(ByteBuf buffer) {
  byte[] bigIntValue = new byte[8];
  buffer.readBytes(bigIntValue); // little endian
  for (int i = 0; i < 4; i++) {
    // swap to big endian order
    byte tmp = bigIntValue[i];
    bigIntValue[i] = bigIntValue[7-i];
    bigIntValue[7-i] = tmp;
  }
  BigInteger value = new BigInteger(1, bigIntValue);
  return Numeric.create(value);
}
 
Example 16
Source File: BedrockUtils.java    From Protocol with Apache License 2.0 5 votes vote down vote up
public static AsciiString readLEAsciiString(ByteBuf buffer) {
    Preconditions.checkNotNull(buffer, "buffer");

    int length = buffer.readIntLE();
    byte[] bytes = new byte[length];
    buffer.readBytes(bytes);
    return new AsciiString(bytes);
}
 
Example 17
Source File: NioUdtByteConnectorChannel.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
@Override
protected int doWriteBytes(final ByteBuf byteBuf) throws Exception {
    final int expectedWrittenBytes = byteBuf.readableBytes();
    return byteBuf.readBytes(javaChannel(), expectedWrittenBytes);
}
 
Example 18
Source File: TypedProperties.java    From activemq-artemis with Apache License 2.0 4 votes vote down vote up
private BytesValue(final ByteBuf buffer) {
   int len = buffer.readInt();
   val = new byte[len];
   buffer.readBytes(val);
}
 
Example 19
Source File: Message.java    From web3sdk with Apache License 2.0 4 votes vote down vote up
public void readExtra(ByteBuf in) {
    data = new byte[length - HEADER_LENGTH];
    in.readBytes(data, 0, length - HEADER_LENGTH);
}
 
Example 20
Source File: ServerHardDeleteTest.java    From ambry with Apache License 2.0 4 votes vote down vote up
/**
 * Fetches the Blob(for all MessageFormatFlags) and verifies the content
 * @param channel the {@link BlockingChannel} to use to send and receive data
 * @param blobsCount the total number of blobs that needs to be verified against
 * @throws Exception
 */
void getAndVerify(ConnectedChannel channel, int blobsCount) throws Exception {
  ArrayList<PartitionRequestInfo> partitionRequestInfoList = new ArrayList<>();
  ArrayList<BlobId> ids = new ArrayList<>();
  for (int i = 0; i < blobsCount; i++) {
    ids.add(blobIdList.get(i));
  }

  PartitionRequestInfo partitionRequestInfo = new PartitionRequestInfo(blobIdList.get(0).getPartition(), ids);
  partitionRequestInfoList.add(partitionRequestInfo);

  ArrayList<MessageFormatFlags> flags = new ArrayList<>();
  flags.add(MessageFormatFlags.BlobProperties);
  flags.add(MessageFormatFlags.BlobUserMetadata);
  flags.add(MessageFormatFlags.Blob);
  for (MessageFormatFlags flag : flags) {
    GetRequest getRequest = new GetRequest(1, "clientid2", flag, partitionRequestInfoList, GetOption.Include_All);
    channel.send(getRequest);
    InputStream stream = channel.receive().getInputStream();
    GetResponse resp = GetResponse.readFrom(new DataInputStream(stream), mockClusterMap);
    if (flag == MessageFormatFlags.BlobProperties) {
      for (int i = 0; i < blobsCount; i++) {
        BlobProperties propertyOutput = MessageFormatRecord.deserializeBlobProperties(resp.getInputStream());
        Assert.assertEquals(properties.get(i).getBlobSize(), propertyOutput.getBlobSize());
        Assert.assertEquals("serviceid1", propertyOutput.getServiceId());
        Assert.assertEquals("AccountId mismatch", properties.get(i).getAccountId(), propertyOutput.getAccountId());
        Assert.assertEquals("ContainerId mismatch", properties.get(i).getContainerId(),
            propertyOutput.getContainerId());
      }
    } else if (flag == MessageFormatFlags.BlobUserMetadata) {
      for (int i = 0; i < blobsCount; i++) {
        ByteBuffer userMetadataOutput = MessageFormatRecord.deserializeUserMetadata(resp.getInputStream());
        Assert.assertArrayEquals(userMetadataOutput.array(), usermetadata.get(i));
      }
    } else if (flag == MessageFormatFlags.Blob) {
      for (int i = 0; i < blobsCount; i++) {
        BlobData blobData = MessageFormatRecord.deserializeBlob(resp.getInputStream());
        Assert.assertEquals(properties.get(i).getBlobSize(), blobData.getSize());
        byte[] dataOutput = new byte[(int) blobData.getSize()];
        ByteBuf buffer = blobData.content();
        try {
          buffer.readBytes(dataOutput);
        } finally {
          buffer.release();
        }
        Assert.assertArrayEquals(dataOutput, data.get(i));
      }
    } else {
      throw new IllegalArgumentException("Unrecognized message format flags " + flags);
    }
  }
}