Java Code Examples for io.netty.buffer.ByteBuf

The following are top voted examples for showing how to use io.netty.buffer.ByteBuf. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: angel   File: ServerDenseIntRowTest.java   View source code 7 votes vote down vote up
@Test
public void testDeserialize() throws Exception {
  ByteBuf buf = Unpooled.buffer(16);
  buf.writeInt(0);
  buf.writeInt(1);
  buf.writeLong(2);
  buf.writeLong(3);
  buf.writeInt(4);
  buf.writeInt(3);
  buf.writeInt(-1);
  buf.writeInt(-2);
  buf.writeInt(-3);
  serverDenseIntRow.deserialize(buf);
  assertEquals(serverDenseIntRow.getRowId(), 0);
  assertEquals(serverDenseIntRow.getClock(), 1);
  assertEquals(serverDenseIntRow.getStartCol(), 2);
  assertEquals(serverDenseIntRow.getEndCol(), 3);
  assertEquals(serverDenseIntRow.getRowVersion(), 4);
  assertEquals(serverDenseIntRow.getData().get(0), -1, 0.0);
  assertEquals(serverDenseIntRow.getData().get(1), -2, 0.0);
  assertEquals(serverDenseIntRow.getData().get(2), -3, 0.0);
}
 
Example 2
Project: NioImapClient   File: ResponseDecoder.java   View source code 6 votes vote down vote up
@Timed
void startBodyParse(ByteBuf in) throws UnknownFetchItemTypeException, IOException {
  skipControlCharacters(in);

  char c = ((char) in.readUnsignedByte());

  //String bodySection = ""; At some point we will need to actually store the body section that is being parsed below
  if (c != '[') {
    // This is effectively BODYSTRUCTURE which is not yet supported
    lineParser.parse(in);
    checkpoint(State.RESET);
    throw new UnknownFetchItemTypeException("BODYSTRUCTURE");
  } else {
    c = ((char) in.readUnsignedByte());
    while (c != ']') { // Skip characters within "[]"
      c = ((char) in.readUnsignedByte());
    }
  }

  checkpoint(State.FETCH_BODY);
}
 
Example 3
Project: wechat-mall   File: RemotingCommand.java   View source code 6 votes vote down vote up
/**
 * <b>一定要 {@link ByteBuf#release()}
 */
public static ByteBuf encode(RemotingCommand cmd) {
    int reqId = cmd.getOpaque();
    byte[] body = cmd.getBody();
    HashMap<String, String> msgs = cmd.getExtFields();
    byte[] append = JsonUtil.toBytes(msgs);
    int initialCapacity = 4 + 4 // total size+reqId
            + 4 + body.length // body
            + 4 + append.length;// apend
    ByteBuf buf = PooledByteBufAllocator.DEFAULT.buffer(initialCapacity);
    buf.writeInt(initialCapacity);
    buf.writeInt(reqId);
    buf.writeInt(body.length);
    buf.writeBytes(body);
    buf.writeInt(append.length);
    buf.writeBytes(append);

    return buf;
}
 
Example 4
Project: DankNull   File: PacketConfigSync.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void fromBytes(ByteBuf buf) {
	short len = buf.readShort();
	byte[] compressedBody = new byte[len];

	for (short i = 0; i < len; i++) {
		compressedBody[i] = buf.readByte();
	}

	try {
		ObjectInputStream obj = new ObjectInputStream(new GZIPInputStream(new ByteArrayInputStream(compressedBody)));
		values = (Map<String, Object>) obj.readObject();
		obj.close();
	}
	catch (Exception e) {
		Throwables.propagate(e);
	}
}
 
Example 5
Project: happylifeplat-transaction   File: SocketUtils.java   View source code 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 6
Project: xrpc   File: XrpcRequest.java   View source code 5 votes vote down vote up
public void setData(ByteBuf buff) {
  if (data == null) {
    data = getByteBuf();
  }

  data.writeBytes(buff);
}
 
Example 7
Project: neoscada   File: MeasuredValueShortFloatingPointSequence.java   View source code 5 votes vote down vote up
@Override
public void encode ( final ProtocolOptions options, final ByteBuf out )
{
    EncodeHelper.encodeHeader ( this, options, this.values.size (), this.header, out );

    this.startAddress.encode ( options, out );

    for ( final Value<Float> value : this.values )
    {
        TypeHelper.encodeFloatValue ( options, out, value, false );
    }
}
 
Example 8
Project: customstuff4   File: PacketSyncContainerFluid.java   View source code 5 votes vote down vote up
@Override
public void toBytes(ByteBuf buf)
{
    buf.writeByte(windowId);
    buf.writeByte(tank);
    NBTTagCompound fluidNbt = fluid == null ? null : fluid.writeToNBT(new NBTTagCompound());
    ByteBufUtils.writeTag(buf, fluidNbt);
}
 
Example 9
Project: tx-lcn   File: SocketUtils.java   View source code 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 10
Project: kcp-netty   File: TcpRttDecoder.java   View source code 5 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    if (in.readableBytes() < 8) {
        return;
    }

    short dataLen = in.getShort(in.readerIndex() + 6);
    if (in.readableBytes() < dataLen) {
        return;
    }

    ByteBuf msg = in.readRetainedSlice(8 + dataLen);
    out.add(msg);
}
 
Example 11
Project: nearenough   File: RtMessageBuilder.java   View source code 5 votes vote down vote up
public RtMessageBuilder add(RtTag tag, RtMessage msg) {
  checkNotNull(tag, "tag must be non-null");
  checkNotNull(msg, "msg must be non-null");

  ByteBuf encoded = RtWire.toWire(msg, allocator);
  return add(tag, encoded);
}
 
Example 12
Project: ClusterDeviceControlPlatform   File: CanFrameChannelInboundHandler.java   View source code 5 votes vote down vote up
/**
 * 缓存可读数据中的非完整帧,拼接为完整帧后,执行正常操作
 *
 * @param msg 可读数据
 * @return 缓存为完整帧
 */
private boolean cacheRemainByte(ByteBuf msg) {
    while (msg.isReadable()) {
        bytes[index] = msg.readByte();
        index++;
        if (index >= 13) {
            index = 0;
            return true;
        }
    }
    return false;
}
 
Example 13
Project: reactive-pg-client   File: Execute.java   View source code 5 votes vote down vote up
private static void encode(String portal, int rowCount, ByteBuf out) {
  int pos = out.writerIndex();
  out.writeByte(EXECUTE);
  out.writeInt(0);
  if (portal != null) {
    out.writeCharSequence(portal, StandardCharsets.UTF_8);
  }
  out.writeByte(0);
  out.writeInt(rowCount); // Zero denotes "no limit" maybe for ReadStream<Row>
  out.setInt(pos + 1, out.writerIndex() - pos - 1);
}
 
Example 14
Project: sstable-adaptor   File: CBUtil.java   View source code 5 votes vote down vote up
public static void writeValue(ByteBuffer bytes, ByteBuf cb)
{
    if (bytes == null)
    {
        cb.writeInt(-1);
        return;
    }

    int remaining = bytes.remaining();
    cb.writeInt(remaining);

    if (remaining > 0)
        cb.writeBytes(bytes.duplicate());
}
 
Example 15
Project: dremio-oss   File: TestBackwardsCompatibilityEncoder.java   View source code 5 votes vote down vote up
private void testBuffers(ByteBuf[] buffers, SerializedField.Builder[] fields) {
  int i = 0;
  for (SerializedField.Builder field : fields) {
    i += fieldBuffersCount(field, buffers, i, buffers.length);
  }
  while (i < buffers.length && buffers[i].readableBytes() == 0) {
    ++ i;
  }
  assertEquals(buffers.length, i);
  for (ByteBuf byteBuf : buffers) {
    byteBuf.release();
  }
}
 
Example 16
Project: ClusterDeviceControlPlatform   File: ParsedMessageInBoundHandler.java   View source code 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, FrameMajor msg) throws Exception {
    FrameMajorHeader head = msg.getHead();
    ByteBuf byteBuf = msg.getData();
    while (byteBuf.readableBytes() >= FrameSetting.SUB_FRAME_HEAD_LENGTH) {
        int subMsgId = byteBuf.readByte() & 0xFF;
        byte[] data = new byte[byteBuf.readShort()];
        byteBuf.readBytes(data);
        server.decodeAndHuntMessage(head, subMsgId, data, ctx.channel());
    }
}
 
Example 17
Project: angel   File: RowUpdater.java   View source code 5 votes vote down vote up
private void updateFloatSparse(RowType updateRowType, int size, ByteBuf dataBuf,
    ServerSparseFloatRow row) {
  switch (updateRowType) {
    case T_FLOAT_DENSE:
      updateFloatDenseToFloatSparse(size, dataBuf, row);
      break;
    case T_FLOAT_SPARSE:
      updateFloatSparseToFloatSparse(size, dataBuf, row);
      break;

    default:
      break;
  }
}
 
Example 18
Project: angel   File: GetRowsSplitRequest.java   View source code 5 votes vote down vote up
@Override public void serialize(ByteBuf buf) {
  super.serialize(buf);
  if (rowIndexes != null) {
    int size = rowIndexes.size();
    buf.writeInt(size);
    for (int i = 0; i < size; i++) {
      buf.writeInt(rowIndexes.get(i));
    }
  }
}
 
Example 19
Project: SimpleTubes   File: PacketTubeSync.java   View source code 5 votes vote down vote up
@Override
public void toBytes(ByteBuf buf) {
	buf.writeInt(this.tile.getWorld().provider.getDimension());
	buf.writeLong(this.tile.getPos().toLong());

	buf.writeInt(this.color);
}
 
Example 20
Project: FlexMC   File: MessageS03SpawnMob.java   View source code 5 votes vote down vote up
@Override
public void write( ByteBuf buf ) throws IOException {
    writeVarInt( entityId, buf );
    writeUUID( uuid, buf );
    writeVarInt( type, buf );
    writeDoubles( buf, x, y, z );
    writeBytes( buf, toAngle( yaw ), toAngle( pitch ), toAngle( headPitch ) );
    writeShorts( buf, velX, velY, velZ );
    entityMetaData.write( buf );
}
 
Example 21
Project: DovakinMQ   File: MqttEncoder.java   View source code 5 votes vote down vote up
private static ByteBuf encodePublishMessage(
        ByteBufAllocator byteBufAllocator,
        MqttPublishMessage message) {
    MqttFixedHeader mqttFixedHeader = message.fixedHeader();
    MqttPublishVariableHeader variableHeader = message.variableHeader();
    ByteBuf payload = message.payload().duplicate();

    String topicName = variableHeader.topicName();
    byte[] topicNameBytes = encodeStringUtf8(topicName);

    int variableHeaderBufferSize = 2 + topicNameBytes.length +
            (mqttFixedHeader.qosLevel().value() > 0 ? 2 : 0);
    int payloadBufferSize = payload.readableBytes();
    int variablePartSize = variableHeaderBufferSize + payloadBufferSize;
    int fixedHeaderBufferSize = 1 + getVariableLengthInt(variablePartSize);

    ByteBuf buf = byteBufAllocator.buffer(fixedHeaderBufferSize + variablePartSize);
    buf.writeByte(getFixedHeaderByte1(mqttFixedHeader));
    writeVariableLengthInt(buf, variablePartSize);
    buf.writeShort(topicNameBytes.length);
    buf.writeBytes(topicNameBytes);
    if (mqttFixedHeader.qosLevel().value() > 0) {
        buf.writeShort(variableHeader.messageId());
    }
    buf.writeBytes(payload);

    return buf;
}
 
Example 22
Project: fastdfs-spring-boot   File: FileIdOperationEncoder.java   View source code 5 votes vote down vote up
@Override
public List<Object> encode(ByteBufAllocator alloc) {
    byte cmd = cmd();
    int length = FastdfsConstants.FDFS_GROUP_LEN + fileId.pathBytes().length;
    ByteBuf buf = alloc.buffer(length + FastdfsConstants.FDFS_HEAD_LEN);
    buf.writeLong(length);
    buf.writeByte(cmd);
    buf.writeByte(FastdfsConstants.ERRNO_OK);
    FastdfsUtils.writeFixLength(buf, fileId.group(), FastdfsConstants.FDFS_GROUP_LEN);
    ByteBufUtil.writeUtf8(buf, fileId.path());
    return Collections.singletonList(buf);
}
 
Example 23
Project: angel   File: GetRowSplitResponse.java   View source code 5 votes vote down vote up
@Override
public void serialize(ByteBuf buf) {
  super.serialize(buf);
  if (rowSplit != null) {
    buf.writeInt(rowSplit.getRowType().getNumber());
    rowSplit.serialize(buf);
  }
}
 
Example 24
Project: DecompiledMinecraft   File: NettyCompressionEncoder.java   View source code 5 votes vote down vote up
protected void encode(ChannelHandlerContext p_encode_1_, ByteBuf p_encode_2_, ByteBuf p_encode_3_) throws Exception
{
    int i = p_encode_2_.readableBytes();
    PacketBuffer packetbuffer = new PacketBuffer(p_encode_3_);

    if (i < this.treshold)
    {
        packetbuffer.writeVarIntToBuffer(0);
        packetbuffer.writeBytes(p_encode_2_);
    }
    else
    {
        byte[] abyte = new byte[i];
        p_encode_2_.readBytes(abyte);
        packetbuffer.writeVarIntToBuffer(abyte.length);
        this.deflater.setInput(abyte, 0, i);
        this.deflater.finish();

        while (!this.deflater.finished())
        {
            int j = this.deflater.deflate(this.buffer);
            packetbuffer.writeBytes((byte[])this.buffer, 0, j);
        }

        this.deflater.reset();
    }
}
 
Example 25
Project: QDrill   File: QueryManager.java   View source code 5 votes vote down vote up
@Override
public void success(final Ack ack, final ByteBuf buf) {
  if (!ack.getOk()) {
    logger.warn("Remote node {} responded negative on {} request for fragment {} with {}.", endpoint, signal, value,
      ack);
  }
}
 
Example 26
Project: JungleTree   File: ResourcePackClientResponseCodec.java   View source code 5 votes vote down vote up
@Override
public ResourcePackClientResponsePacket decode(ByteBuf buf) {
    ResourcePackClientResponsePacket packet = new ResourcePackClientResponsePacket();
    packet.setResponse(buf.readByte());

    int length = buf.readUnsignedShortLE();
    String[] downloading = new String[length];
    for (int i=0; i<downloading.length; i++) {
        downloading[0] = ByteBufUtils.readString(buf);
    }
    packet.setDownloading(downloading);

    return packet;
}
 
Example 27
Project: FlexMC   File: MessageS2EPlayerList.java   View source code 5 votes vote down vote up
@Override
public void write( ByteBuf buf ) throws IOException {
    writeVarInt( action.ordinal(), buf );
    writeVarInt( players.size(), buf );
    for ( PlayerItem player : players ) {
        writeUUID( player.uuid, buf );
        switch ( action ) {
            case ADD_PLAYER:
                writeString( player.name, buf );
                writeVarInt( 0, buf );
                writeVarInt( player.gameMode.getValue(), buf );
                writeVarInt( player.ping, buf );
                buf.writeBoolean( player.displayName != null );
                if ( player.displayName != null ) {
                    writeString( Flex.getGson().toJson( player.displayName ), buf );
                }
                break;
            case UPDATE_GAMEMODE:
                writeVarInt( player.gameMode.getValue(), buf );
                break;
            case UPDATE_PING:
                writeVarInt( player.ping, buf );
                break;
            case UPDATE_DISPLAY_NAME:
                buf.writeBoolean( player.displayName != null );
                if ( player.displayName != null ) {
                    writeString( Flex.getGson().toJson( player.displayName ), buf );
                }
                break;
            case REMOVE_PLAYER:
                // nothing here, but intellij fucks me off when I dont handle this case so here is a pretty useful comment
                break;
        }
    }
}
 
Example 28
Project: ProjectAres   File: PacketTracer.java   View source code 5 votes vote down vote up
private ByteBuf list(ByteBuf bytes, int start, int length) {
    final String[] raw = new String[length];
    for(int i = 0; i < length; i++) {
        raw[i] = Byte.toString(bytes.getByte(start + i));
    }
    list("byte", raw);
    return bytes;
}
 
Example 29
Project: angel   File: SparseIntVector.java   View source code 5 votes vote down vote up
@Override
public void deserialize(ByteBuf buf) {
  int dim = buf.readInt();
  int length = buf.readInt();
  Int2IntOpenHashMap data = new Int2IntOpenHashMap(length);
  IntStream.range(0,length).forEach(i-> data.put(buf.readInt(), buf.readInt()));
  this.dim = dim;
  this.hashMap = data;
}
 
Example 30
Project: neto   File: NetoByteToMessageDecoder.java   View source code 5 votes vote down vote up
/**
 * 채널로부터 수신된 버퍼에서 data를 발신측에서 보낸 순서대로 Decode하고 <br>
 * MessageHandler로(pipeline에서 다음 핸들러) 전달할 {@link NetoInboundByteMessage}를 {@link NetoInboundByteMessageBuilder} 를 통해 생성하여 반환한다.
 *
 * @param commandCode 커맨드코드
 * @param buff 채널로부터 수신되는 버퍼
 * @param charset 캐릭터셋
 * @return MessageHandler로 전달 시킬 NetoInboundByteMessage
 */
protected NetoInboundByteMessage decodeData(int commandCode, ByteBuf buff, Charset charset) {
    NetoInboundByteMessage decodeMessage = null;
    try {
        decodeMessage = inboundByteMessageBuilder.create(commandCode, buff);
        decodeMessage.buildMessage(charset);
    } catch (Exception e) {
        decodeMessage = new NetoUnknownInboundByteMessage(e.getMessage(), buff);
    }
    return decodeMessage;
}
 
Example 31
Project: neoscada   File: AbstractMeasuredValueScaled.java   View source code 5 votes vote down vote up
protected static List<InformationEntry<Short>> parseEntries ( final ProtocolOptions options, final byte length, final ByteBuf data, final boolean withTimestamp )
{
    final List<InformationEntry<Short>> values = new ArrayList<> ( length );
    for ( int i = 0; i < length; i++ )
    {
        final InformationObjectAddress address = InformationObjectAddress.parse ( options, data );
        final Value<Short> value = TypeHelper.parseScaledValue ( options, data, withTimestamp );
        values.add ( new InformationEntry<> ( address, value ) );
    }
    return values;
}
 
Example 32
Project: BaseClient   File: NettyEncryptionTranslator.java   View source code 5 votes vote down vote up
protected void cipher(ByteBuf p_150504_1_, ByteBuf p_150504_2_) throws ShortBufferException
{
    int i = p_150504_1_.readableBytes();
    byte[] abyte = this.func_150502_a(p_150504_1_);
    int j = this.cipher.getOutputSize(i);

    if (this.field_150506_c.length < j)
    {
        this.field_150506_c = new byte[j];
    }

    p_150504_2_.writeBytes((byte[])this.field_150506_c, 0, this.cipher.update(abyte, 0, i, this.field_150506_c));
}
 
Example 33
Project: angel   File: PartitionUpdateParam.java   View source code 5 votes vote down vote up
@Override
public void serialize(ByteBuf buf) {
  buf.writeInt(matrixId);
  buf.writeBoolean(updateClock);
  if (partKey != null) {
    partKey.serialize(buf);
  }
}
 
Example 34
Project: Mods   File: TF2Message.java   View source code 5 votes vote down vote up
@Override
public void toBytes(ByteBuf buf) {
	buf.writeShort(value);
	buf.writeBoolean(reload);
	buf.writeShort(newAmmo);
	buf.writeBoolean(hand == EnumHand.MAIN_HAND);
}
 
Example 35
Project: minecraft-quiverbow   File: FlintDust.java   View source code 5 votes vote down vote up
@Override
public void readSpawnData(ByteBuf additionalData) 	// read it on the client
{ 
	this.ownerX = additionalData.readDouble();
	this.ownerY = additionalData.readDouble();
	this.ownerZ = additionalData.readDouble();
}
 
Example 36
Project: util4j   File: WebSocketBinaryFrameByteBufAdapter.java   View source code 5 votes vote down vote up
/**
 * 对于业务层直接发送的bytebuf实例将其转换为websocket消息
 */
@Override
protected void encode(ChannelHandlerContext paramChannelHandlerContext,
		ByteBuf paramOUTBOUND_IN, List<Object> paramList) throws Exception {
	paramList.add(new BinaryWebSocketFrame(paramOUTBOUND_IN));
	paramOUTBOUND_IN.retain();
}
 
Example 37
Project: DovakinMQ   File: MqttDecoder.java   View source code 5 votes vote down vote up
private static Result<MqttSubAckPayload> decodeSubackPayload(
        ByteBuf buffer,
        int bytesRemainingInVariablePart) {
    final List<Integer> grantedQos = new ArrayList<Integer>();
    int numberOfBytesConsumed = 0;
    while (numberOfBytesConsumed < bytesRemainingInVariablePart) {
        int qos = buffer.readUnsignedByte() & 0x03;
        numberOfBytesConsumed++;
        grantedQos.add(qos);
    }
    return new Result<MqttSubAckPayload>(new MqttSubAckPayload(grantedQos), numberOfBytesConsumed);
}
 
Example 38
Project: minecraft-quiverbow   File: TurretStateMessage.java   View source code 5 votes vote down vote up
@Override
public void toBytes(ByteBuf buf)
{		
	buf.writeInt(this.entityID);
	buf.writeBoolean(this.hasArmorUpgrade);
	buf.writeBoolean(this.hasWeaponUpgrade);
	buf.writeBoolean(this.hasRidingUpgrade);
	buf.writeBoolean(this.hasPlatingUpgrade);
	buf.writeBoolean(this.hasCommunicationUpgrade);
}
 
Example 39
Project: drift   File: HeaderMessageEncoding.java   View source code 5 votes vote down vote up
@Override
public OptionalInt extractResponseSequenceId(ByteBuf buffer)
{
    if (buffer.readableBytes() < HEADER_SEQUENCE_ID_OFFSET + Integer.BYTES) {
        return OptionalInt.empty();
    }
    return OptionalInt.of(buffer.getInt(buffer.readerIndex() + HEADER_SEQUENCE_ID_OFFSET));
}
 
Example 40
Project: Machines-and-Stuff   File: MessageGenerator.java   View source code 5 votes vote down vote up
@Override
public void toBytes(ByteBuf buf) {
    
    buf.writeInt(this.x);
    buf.writeInt(this.y);
    buf.writeInt(this.z);
    
    buf.writeInt(generationTimer);
    buf.writeInt(generationTimerDefault);
    buf.writeLong(energy);
}