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

The following examples show how to use io.netty.buffer.ByteBuf#writeIntLE() . 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: CommandBlockUpdateSerializer_v361.java    From Protocol with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(ByteBuf buffer, CommandBlockUpdatePacket packet) {
    buffer.writeBoolean(packet.isBlock());

    if (packet.isBlock()) {
        BedrockUtils.writeBlockPosition(buffer, packet.getBlockPosition());
        VarInts.writeUnsignedInt(buffer, packet.getCommandBlockMode());
        buffer.writeBoolean(packet.isRedstoneMode());
        buffer.writeBoolean(packet.isConditional());
    } else {
        VarInts.writeUnsignedLong(buffer, packet.getMinecartRuntimeEntityId());
    }

    BedrockUtils.writeString(buffer, packet.getCommand());
    BedrockUtils.writeString(buffer, packet.getLastOutput());
    BedrockUtils.writeString(buffer, packet.getName());
    buffer.writeBoolean(packet.isOutputTracked());
    buffer.writeIntLE((int) packet.getTickDelay());
    buffer.writeBoolean(packet.isExecutingOnFirstTick());
}
 
Example 2
Source File: GeometryWkbFormatCodec.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
private static void encodeWkbMultiPolygon(ByteBuf buffer, MultiPolygon multiPolygon) {
  buffer.writeByte(WKB_BYTE_ORDER_LITTLE_ENDIAN);
  buffer.writeIntLE(WKB_GEOMETRY_TYPE_MULTIPOLYGON);
  buffer.writeIntLE(multiPolygon.getPolygons().size());
  for (Polygon wkbPolygon : multiPolygon.getPolygons()) {
    encodeWkbPolygon(buffer, wkbPolygon);
  }
}
 
Example 3
Source File: AltsTsiFrameProtectorTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void parseFrame_oneFrameNoFragment() throws GeneralSecurityException {
  int payloadBytes = 1024;
  ByteBufAllocator alloc = ByteBufAllocator.DEFAULT;
  List<Object> out = new ArrayList<>();
  FakeChannelCrypter crypter = new FakeChannelCrypter();
  AltsTsiFrameProtector.Unprotector unprotector =
      new AltsTsiFrameProtector.Unprotector(crypter, alloc);
  ByteBuf plain = getRandom(payloadBytes, ref);
  ByteBuf outFrame =
      getDirectBuffer(
          AltsTsiFrameProtector.getHeaderBytes()
              + payloadBytes
              + FakeChannelCrypter.getTagBytes(),
          ref);

  outFrame.writeIntLE(
      AltsTsiFrameProtector.getHeaderTypeFieldBytes()
          + payloadBytes
          + FakeChannelCrypter.getTagBytes());
  outFrame.writeIntLE(6);
  List<ByteBuf> framePlain = Collections.singletonList(plain);
  ByteBuf frameOut = writeSlice(outFrame, payloadBytes + FakeChannelCrypter.getTagBytes());
  crypter.encrypt(frameOut, framePlain);
  plain.readerIndex(0);

  unprotector.unprotect(outFrame, out, alloc);
  assertThat(outFrame.readableBytes()).isEqualTo(0);
  assertThat(out.size()).isEqualTo(1);
  ByteBuf out1 = ref((ByteBuf) out.get(0));
  assertThat(out1).isEqualTo(plain);

  unprotector.destroy();
}
 
Example 4
Source File: GeometryWkbFormatCodec.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
private static void encodeWkbPolygon(ByteBuf buffer, Polygon polygon) {
  buffer.writeByte(WKB_BYTE_ORDER_LITTLE_ENDIAN);
  buffer.writeIntLE(WKB_GEOMETRY_TYPE_POLYGON);
  buffer.writeIntLE(polygon.getLineStrings().size());
  for (LineString lineString : polygon.getLineStrings()) {
    buffer.writeIntLE(lineString.getPoints().size());
    for (Point point : lineString.getPoints()) {
      buffer.writeDoubleLE(point.getX());
      buffer.writeDoubleLE(point.getY());
    }
  }
}
 
Example 5
Source File: ResourcePackDataInfoSerializer_v354.java    From Protocol with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(ByteBuf buffer, ResourcePackDataInfoPacket packet) {
    String packInfo = packet.getPackId().toString() + (packet.getPackVersion() == null ? "" : '_' + packet.getPackVersion());
    BedrockUtils.writeString(buffer, packInfo);
    buffer.writeIntLE((int) packet.getMaxChunkSize());
    buffer.writeIntLE((int) packet.getChunkCount());
    buffer.writeLongLE(packet.getCompressedPackSize());
    BedrockUtils.writeByteArray(buffer, packet.getHash());
}
 
Example 6
Source File: LocalTimeCodec.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
static ByteBuf encodeBinary(ByteBufAllocator alloc, LocalTime time) {
    if (LocalTime.MIDNIGHT.equals(time)) {
        // It is zero of var int, not terminal.
        return alloc.buffer(Byte.BYTES).writeByte(0);
    }

    int nanos = time.getNano();
    int size = nanos > 0 ? MICRO_TIME_SIZE : TIME_SIZE;

    ByteBuf buf = alloc.buffer(Byte.BYTES + size);

    try {
        buf.writeByte(size)
            .writeBoolean(false)
            .writeIntLE(0)
            .writeByte(time.getHour())
            .writeByte(time.getMinute())
            .writeByte(time.getSecond());

        if (nanos > 0) {
            return buf.writeIntLE(nanos / NANOS_OF_MICRO);
        }

        return buf;
    } catch (Throwable e) {
        buf.release();
        throw e;
    }
}
 
Example 7
Source File: LocalTimeCodec.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
static ByteBuf encodeBinary(ByteBufAllocator alloc, LocalTime time) {
    if (LocalTime.MIDNIGHT.equals(time)) {
        // It is zero of var int, not terminal.
        return alloc.buffer(Byte.BYTES).writeByte(0);
    }

    int nanos = time.getNano();
    int size = nanos > 0 ? MICRO_TIME_SIZE : TIME_SIZE;

    ByteBuf buf = alloc.buffer(Byte.BYTES + size);

    try {
        buf.writeByte(size)
            .writeBoolean(false)
            .writeIntLE(0)
            .writeByte(time.getHour())
            .writeByte(time.getMinute())
            .writeByte(time.getSecond());

        if (nanos > 0) {
            return buf.writeIntLE(nanos / NANOS_OF_MICRO);
        }

        return buf;
    } catch (Throwable e) {
        buf.release();
        throw e;
    }
}
 
Example 8
Source File: AltsTsiFrameProtectorTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Test
public void parseHeader_frameFailFragment() throws GeneralSecurityException {
  ByteBufAllocator alloc = ByteBufAllocator.DEFAULT;
  List<Object> out = new ArrayList<>();
  FakeChannelCrypter crypter = new FakeChannelCrypter();
  AltsTsiFrameProtector.Unprotector unprotector =
      new AltsTsiFrameProtector.Unprotector(crypter, alloc);
  ByteBuf in =
      getDirectBuffer(
          AltsTsiFrameProtector.getHeaderBytes() + FakeChannelCrypter.getTagBytes(), ref);
  in.writeIntLE(FRAME_MIN_SIZE - 1);
  in.writeIntLE(6);
  ByteBuf in1 = in.readSlice(AltsTsiFrameProtector.getHeaderBytes() - 1);
  ByteBuf in2 = in.readSlice(1);

  unprotector.unprotect(in1, out, alloc);
  assertThat(in1.readableBytes()).isEqualTo(0);

  try {
    unprotector.unprotect(in2, out, alloc);
    fail("Exception expected");
  } catch (IllegalArgumentException ex) {
    assertThat(ex).hasMessageThat().contains("Invalid header field: frame size too small");
  }

  assertThat(in2.readableBytes()).isEqualTo(0);

  unprotector.destroy();
}
 
Example 9
Source File: LocalDateTimeCodec.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
static ByteBuf encodeBinary(ByteBufAllocator alloc, LocalDateTime value) {
    LocalTime time = value.toLocalTime();

    if (LocalTime.MIDNIGHT.equals(time)) {
        return LocalDateCodec.encodeDate(alloc, value.toLocalDate());
    }

    int nano = time.getNano();
    int bytes = nano > 0 ? DateTimes.MICRO_DATETIME_SIZE : DateTimes.DATETIME_SIZE;
    ByteBuf buf = alloc.buffer(Byte.BYTES + bytes);

    try {
        buf.writeByte(bytes)
            .writeShortLE(value.getYear())
            .writeByte(value.getMonthValue())
            .writeByte(value.getDayOfMonth())
            .writeByte(time.getHour())
            .writeByte(time.getMinute())
            .writeByte(time.getSecond());

        if (nano > 0) {
            return buf.writeIntLE(nano / DateTimes.NANOS_OF_MICRO);
        }

        return buf;
    } catch (Throwable e) {
        buf.release();
        throw e;
    }
}
 
Example 10
Source File: ResourcePackChunkDataSerializer_v340.java    From Protocol with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(ByteBuf buffer, ResourcePackChunkDataPacket packet) {
    String packInfo = packet.getPackId().toString() + (packet.getPackVersion() == null ? "" : '_' + packet.getPackVersion());
    BedrockUtils.writeString(buffer, packInfo);
    buffer.writeIntLE(packet.getChunkIndex());
    buffer.writeLongLE(packet.getProgress());
    byte[] data = packet.getData();
    buffer.writeIntLE(data.length);
    buffer.writeBytes(data);
}
 
Example 11
Source File: ResourcePackDataInfoSerializer_v291.java    From Protocol with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(ByteBuf buffer, ResourcePackDataInfoPacket packet) {
    String packInfo = packet.getPackId().toString() + (packet.getPackVersion() == null ? "" : '_' + packet.getPackVersion());
    BedrockUtils.writeString(buffer, packInfo);
    buffer.writeIntLE((int) packet.getMaxChunkSize());
    buffer.writeIntLE((int) packet.getChunkCount());
    buffer.writeLongLE(packet.getCompressedPackSize());
    BedrockUtils.writeByteArray(buffer, packet.getHash());
}
 
Example 12
Source File: AltsTsiFrameProtectorTest.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@Test
public void parseFrame_twoFramesNoFragment() throws GeneralSecurityException {
  int payloadBytes = 1536;
  int payloadBytes1 = 1024;
  int payloadBytes2 = payloadBytes - payloadBytes1;
  ByteBufAllocator alloc = ByteBufAllocator.DEFAULT;
  List<Object> out = new ArrayList<>();
  FakeChannelCrypter crypter = new FakeChannelCrypter();
  AltsTsiFrameProtector.Unprotector unprotector =
      new AltsTsiFrameProtector.Unprotector(crypter, alloc);

  ByteBuf plain = getRandom(payloadBytes, ref);
  ByteBuf outFrame =
      getDirectBuffer(
          2 * (AltsTsiFrameProtector.getHeaderBytes() + FakeChannelCrypter.getTagBytes())
              + payloadBytes,
          ref);

  outFrame.writeIntLE(
      AltsTsiFrameProtector.getHeaderTypeFieldBytes()
          + payloadBytes1
          + FakeChannelCrypter.getTagBytes());
  outFrame.writeIntLE(6);
  List<ByteBuf> framePlain1 = Collections.singletonList(plain.readSlice(payloadBytes1));
  ByteBuf frameOut1 = writeSlice(outFrame, payloadBytes1 + FakeChannelCrypter.getTagBytes());

  outFrame.writeIntLE(
      AltsTsiFrameProtector.getHeaderTypeFieldBytes()
          + payloadBytes2
          + FakeChannelCrypter.getTagBytes());
  outFrame.writeIntLE(6);
  List<ByteBuf> framePlain2 = Collections.singletonList(plain);
  ByteBuf frameOut2 = writeSlice(outFrame, payloadBytes2 + FakeChannelCrypter.getTagBytes());

  crypter.encrypt(frameOut1, framePlain1);
  crypter.encrypt(frameOut2, framePlain2);
  plain.readerIndex(0);

  unprotector.unprotect(outFrame, out, alloc);
  assertThat(out.size()).isEqualTo(1);
  ByteBuf out1 = ref((ByteBuf) out.get(0));
  assertThat(out1).isEqualTo(plain);
  assertThat(outFrame.refCnt()).isEqualTo(1);
  assertThat(outFrame.readableBytes()).isEqualTo(0);

  unprotector.destroy();
}
 
Example 13
Source File: ResourcePackChunkRequestSerializer_v388.java    From Protocol with Apache License 2.0 4 votes vote down vote up
@Override
public void serialize(ByteBuf buffer, ResourcePackChunkRequestPacket packet) {
    String packInfo = packet.getPackId().toString() + (packet.getPackVersion() == null ? "" : '_' + packet.getPackVersion());
    BedrockUtils.writeString(buffer, packInfo);
    buffer.writeIntLE(packet.getChunkIndex());
}
 
Example 14
Source File: AltsTsiFrameProtector.java    From grpc-nebula-java with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("BetaApi") // verify is stable in Guava
private ByteBuf handleUnprotected(List<ByteBuf> unprotectedBufs, ByteBufAllocator alloc)
    throws GeneralSecurityException {
  long unprotectedBytes = 0;
  for (ByteBuf buf : unprotectedBufs) {
    unprotectedBytes += buf.readableBytes();
  }
  // Empty plaintext not allowed since this should be handled as no-op in layer above.
  checkArgument(unprotectedBytes > 0);

  // Compute number of frames and allocate a single buffer for all frames.
  long frameNum = unprotectedBytes / maxUnprotectedBytesPerFrame + 1;
  int lastFrameUnprotectedBytes = (int) (unprotectedBytes % maxUnprotectedBytesPerFrame);
  if (lastFrameUnprotectedBytes == 0) {
    frameNum--;
    lastFrameUnprotectedBytes = maxUnprotectedBytesPerFrame;
  }
  long protectedBytes = frameNum * (HEADER_BYTES + suffixBytes) + unprotectedBytes;

  ByteBuf protectedBuf = alloc.directBuffer(Ints.checkedCast(protectedBytes));
  try {
    int bufferIdx = 0;
    for (int frameIdx = 0; frameIdx < frameNum; ++frameIdx) {
      int unprotectedBytesLeft =
          (frameIdx == frameNum - 1) ? lastFrameUnprotectedBytes : maxUnprotectedBytesPerFrame;
      // Write header (at most LIMIT_MAX_ALLOWED_FRAME_BYTES).
      protectedBuf.writeIntLE(unprotectedBytesLeft + HEADER_TYPE_FIELD_BYTES + suffixBytes);
      protectedBuf.writeIntLE(HEADER_TYPE_DEFAULT);

      // Ownership of the backing buffer remains with protectedBuf.
      ByteBuf frameOut = writeSlice(protectedBuf, unprotectedBytesLeft + suffixBytes);
      List<ByteBuf> framePlain = new ArrayList<>();
      while (unprotectedBytesLeft > 0) {
        // Ownership of the buffer backing in remains with unprotectedBufs.
        ByteBuf in = unprotectedBufs.get(bufferIdx);
        if (in.readableBytes() <= unprotectedBytesLeft) {
          // The complete buffer belongs to this frame.
          framePlain.add(in);
          unprotectedBytesLeft -= in.readableBytes();
          bufferIdx++;
        } else {
          // The remainder of in will be part of the next frame.
          framePlain.add(in.readSlice(unprotectedBytesLeft));
          unprotectedBytesLeft = 0;
        }
      }
      crypter.encrypt(frameOut, framePlain);
      verify(!frameOut.isWritable());
    }
    protectedBuf.readerIndex(0);
    protectedBuf.writerIndex(protectedBuf.capacity());
    return protectedBuf.retain();
  } finally {
    protectedBuf.release();
  }
}
 
Example 15
Source File: ResourcePackChunkRequestSerializer_v361.java    From Protocol with Apache License 2.0 4 votes vote down vote up
@Override
public void serialize(ByteBuf buffer, ResourcePackChunkRequestPacket packet) {
    String packInfo = packet.getPackId().toString() + (packet.getPackVersion() == null ? "" : '_' + packet.getPackVersion());
    BedrockUtils.writeString(buffer, packInfo);
    buffer.writeIntLE(packet.getChunkIndex());
}
 
Example 16
Source File: GuiDataPickItemSerializer_v291.java    From Protocol with Apache License 2.0 4 votes vote down vote up
@Override
public void serialize(ByteBuf buffer, GuiDataPickItemPacket packet) {
    BedrockUtils.writeString(buffer, packet.getDescription());
    BedrockUtils.writeString(buffer, packet.getItemEffects());
    buffer.writeIntLE(packet.getHotbarSlot());
}
 
Example 17
Source File: CompletedUsingItemSerializer_v388.java    From Protocol with Apache License 2.0 4 votes vote down vote up
@Override
public void serialize(ByteBuf buffer, CompletedUsingItemPacket packet) {
    buffer.writeShortLE(packet.getItemId());
    buffer.writeIntLE(packet.getAction().ordinal() - 1); // Enum starts at -1
}
 
Example 18
Source File: GuiDataPickItemSerializer_v313.java    From Protocol with Apache License 2.0 4 votes vote down vote up
@Override
public void serialize(ByteBuf buffer, GuiDataPickItemPacket packet) {
    BedrockUtils.writeString(buffer, packet.getDescription());
    BedrockUtils.writeString(buffer, packet.getItemEffects());
    buffer.writeIntLE(packet.getHotbarSlot());
}
 
Example 19
Source File: ExtendedQueryCommandCodec.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
private void sendStatementExecuteCommand(MySQLPreparedStatement statement, boolean sendTypesToServer, Tuple params, byte cursorType) {
  ByteBuf packet = allocateBuffer();
  // encode packet header
  int packetStartIdx = packet.writerIndex();
  packet.writeMediumLE(0); // will set payload length later by calculation
  packet.writeByte(sequenceId);

  // encode packet payload
  packet.writeByte(CommandType.COM_STMT_EXECUTE);
  packet.writeIntLE((int) statement.statementId);
  packet.writeByte(cursorType);
  // iteration count, always 1
  packet.writeIntLE(1);

  int numOfParams = statement.bindingTypes().length;
  int bitmapLength = (numOfParams + 7) / 8;
  byte[] nullBitmap = new byte[bitmapLength];

  int pos = packet.writerIndex();

  if (numOfParams > 0) {
    // write a dummy bitmap first
    packet.writeBytes(nullBitmap);
    packet.writeBoolean(sendTypesToServer);

    if (sendTypesToServer) {
      for (DataType bindingType : statement.bindingTypes()) {
        packet.writeByte(bindingType.id);
        packet.writeByte(0); // parameter flag: signed
      }
    }

    for (int i = 0; i < numOfParams; i++) {
      Object value = params.getValue(i);
      if (value != null) {
        DataTypeCodec.encodeBinary(statement.bindingTypes()[i], value, encoder.encodingCharset, packet);
      } else {
        nullBitmap[i / 8] |= (1 << (i & 7));
      }
    }

    // padding null-bitmap content
    packet.setBytes(pos, nullBitmap);
  }

  // set payload length
  int payloadLength = packet.writerIndex() - packetStartIdx - 4;
  packet.setMediumLE(packetStartIdx, payloadLength);

  sendPacket(packet, payloadLength);
}
 
Example 20
Source File: StartGameSerializer_v361.java    From Protocol with Apache License 2.0 4 votes vote down vote up
@Override
public void serialize(ByteBuf buffer, StartGamePacket packet) {
    VarInts.writeLong(buffer, packet.getUniqueEntityId());
    VarInts.writeUnsignedLong(buffer, packet.getRuntimeEntityId());
    VarInts.writeInt(buffer, packet.getPlayerGamemode());
    BedrockUtils.writeVector3f(buffer, packet.getPlayerPosition());
    BedrockUtils.writeVector2f(buffer, packet.getRotation());
    // Level settings start
    VarInts.writeInt(buffer, packet.getSeed());
    VarInts.writeInt(buffer, packet.getDimensionId());
    VarInts.writeInt(buffer, packet.getGeneratorId());
    VarInts.writeInt(buffer, packet.getLevelGamemode());
    VarInts.writeInt(buffer, packet.getDifficulty());
    BedrockUtils.writeBlockPosition(buffer, packet.getDefaultSpawn());
    buffer.writeBoolean(packet.isAchievementsDisabled());
    VarInts.writeInt(buffer, packet.getTime());
    buffer.writeBoolean(packet.getEduEditionOffers() != 0);
    buffer.writeBoolean(packet.isEduFeaturesEnabled());
    buffer.writeFloatLE(packet.getRainLevel());
    buffer.writeFloatLE(packet.getLightningLevel());
    buffer.writeBoolean(packet.isPlatformLockedContentConfirmed());
    buffer.writeBoolean(packet.isMultiplayerGame());
    buffer.writeBoolean(packet.isBroadcastingToLan());
    VarInts.writeInt(buffer, packet.getXblBroadcastMode().ordinal());
    VarInts.writeInt(buffer, packet.getPlatformBroadcastMode().ordinal());
    buffer.writeBoolean(packet.isCommandsEnabled());
    buffer.writeBoolean(packet.isTexturePacksRequired());
    BedrockUtils.writeArray(buffer, packet.getGamerules(), BedrockUtils::writeGameRule);
    buffer.writeBoolean(packet.isBonusChestEnabled());
    buffer.writeBoolean(packet.isStartingWithMap());
    VarInts.writeInt(buffer, packet.getDefaultPlayerPermission().ordinal());
    buffer.writeIntLE(packet.getServerChunkTickRange());
    buffer.writeBoolean(packet.isBehaviorPackLocked());
    buffer.writeBoolean(packet.isResourcePackLocked());
    buffer.writeBoolean(packet.isFromLockedWorldTemplate());
    buffer.writeBoolean(packet.isUsingMsaGamertagsOnly());
    buffer.writeBoolean(packet.isFromWorldTemplate());
    buffer.writeBoolean(packet.isWorldTemplateOptionLocked());
    buffer.writeBoolean(packet.isOnlySpawningV1Villagers());

    // Level settings end
    BedrockUtils.writeString(buffer, packet.getLevelId());
    BedrockUtils.writeString(buffer, packet.getWorldName());
    BedrockUtils.writeString(buffer, packet.getPremiumWorldTemplateId());
    buffer.writeBoolean(packet.isTrial());
    buffer.writeLongLE(packet.getCurrentTick());
    VarInts.writeInt(buffer, packet.getEnchantmentSeed());

    List<CompoundTag> palette = packet.getBlockPalette().getValue();
    VarInts.writeUnsignedInt(buffer, palette.size());
    for (CompoundTag entry : palette) {
        CompoundTag blockTag = entry.getCompound("block");
        BedrockUtils.writeString(buffer, blockTag.getString("name"));
        buffer.writeShortLE(entry.getShort("meta"));
        buffer.writeShortLE(entry.getShort("id"));
    }

    BedrockUtils.writeArray(buffer, packet.getItemEntries(), (buf, entry) -> {
        BedrockUtils.writeString(buf, entry.getIdentifier());
        buf.writeShortLE(entry.getId());
    });

    BedrockUtils.writeString(buffer, packet.getMultiplayerCorrelationId());

}