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

The following examples show how to use io.netty.buffer.ByteBuf#readUnsignedIntLE() . 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: LocalDateTimeCodec.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
@Nullable
private static LocalDateTime decodeBinary(ByteBuf buf) {
    int bytes = buf.readableBytes();
    LocalDate date = LocalDateCodec.readDateBinary(buf, bytes);

    if (date == null) {
        return null;
    }

    if (bytes < DateTimes.DATETIME_SIZE) {
        return LocalDateTime.of(date, LocalTime.MIDNIGHT);
    }

    byte hour = buf.readByte();
    byte minute = buf.readByte();
    byte second = buf.readByte();

    if (bytes < DateTimes.MICRO_DATETIME_SIZE) {
        return LocalDateTime.of(date, LocalTime.of(hour, minute, second));
    }

    int nano = (int) (buf.readUnsignedIntLE() * DateTimes.NANOS_OF_MICRO);
    return LocalDateTime.of(date, LocalTime.of(hour, minute, second, nano));
}
 
Example 2
Source File: DurationCodec.java    From r2dbc-mysql with Apache License 2.0 6 votes vote down vote up
private static Duration decodeBinary(ByteBuf buf) {
    int bytes = buf.readableBytes();

    if (bytes < TIME_SIZE) {
        return Duration.ZERO;
    }

    boolean isNegative = buf.readBoolean();

    long day = buf.readUnsignedIntLE();
    byte hour = buf.readByte();
    byte minute = buf.readByte();
    byte second = buf.readByte();
    long totalSeconds = day * SECONDS_OF_DAY + ((long) hour) * SECONDS_OF_HOUR +
        ((long) minute) * SECONDS_OF_MINUTE + ((long) second);

    if (bytes < MICRO_TIME_SIZE) {
        return Duration.ofSeconds(isNegative ? -totalSeconds : totalSeconds);
    }

    long nanos = buf.readUnsignedIntLE() * NANOS_OF_MICRO;

    return Duration.ofSeconds(isNegative ? -totalSeconds : totalSeconds, isNegative ? -nanos : nanos);
}
 
Example 3
Source File: Crc32Decode.java    From java-Kcp with Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof DatagramPacket) {
        DatagramPacket datagramPacket = (DatagramPacket) msg;
        ByteBuf data = datagramPacket.content();
        long checksum =  data.readUnsignedIntLE();
        ByteBuffer byteBuffer = data.nioBuffer(data.readerIndex(),data.readableBytes());
        crc32.reset();
        crc32.update(byteBuffer);
        if(checksum!=crc32.getValue()){
            Snmp.snmp.getInCsumErrors().increment();
            return;
        }
    }
   ctx.fireChannelRead(msg);
}
 
Example 4
Source File: QueryCommandBaseCodec.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
protected MSSQLRowDesc decodeColmetadataToken(ByteBuf payload) {
  int columnCount = payload.readUnsignedShortLE();

  ColumnData[] columnDatas = new ColumnData[columnCount];

  for (int i = 0; i < columnCount; i++) {
    long userType = payload.readUnsignedIntLE();
    int flags = payload.readUnsignedShortLE();
    MSSQLDataType dataType = decodeDataTypeMetadata(payload);
    String columnName = readByteLenVarchar(payload);
    columnDatas[i] = new ColumnData(userType, flags, dataType, columnName);
  }

  return new MSSQLRowDesc(columnDatas);
}
 
Example 5
Source File: DataTypeCodec.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
private static Duration binaryDecodeTime(ByteBuf buffer) {
  byte length = buffer.readByte();
  if (length == 0) {
    return Duration.ZERO;
  } else {
    boolean isNegative = (buffer.readByte() == 1);
    int days = buffer.readIntLE();
    int hour = buffer.readByte();
    int minute = buffer.readByte();
    int second = buffer.readByte();
    if (isNegative) {
      days = -days;
      hour = -hour;
      minute = -minute;
      second = -second;
    }

    if (length == 8) {
      return Duration.ofDays(days).plusHours(hour).plusMinutes(minute).plusSeconds(second);
    }
    if (length == 12) {
      long microsecond = buffer.readUnsignedIntLE();
      if (isNegative) {
        microsecond = -microsecond;
      }
      return Duration.ofDays(days).plusHours(hour).plusMinutes(minute).plusSeconds(second).plusNanos(microsecond * 1000);
    }
    throw new DecoderException("Invalid time format");
  }
}
 
Example 6
Source File: CommandCodec.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
ColumnDefinition decodeColumnDefinitionPacketPayload(ByteBuf payload) {
  String catalog = BufferUtils.readLengthEncodedString(payload, StandardCharsets.UTF_8);
  String schema = BufferUtils.readLengthEncodedString(payload, StandardCharsets.UTF_8);
  String table = BufferUtils.readLengthEncodedString(payload, StandardCharsets.UTF_8);
  String orgTable = BufferUtils.readLengthEncodedString(payload, StandardCharsets.UTF_8);
  String name = BufferUtils.readLengthEncodedString(payload, StandardCharsets.UTF_8);
  String orgName = BufferUtils.readLengthEncodedString(payload, StandardCharsets.UTF_8);
  long lengthOfFixedLengthFields = BufferUtils.readLengthEncodedInteger(payload);
  int characterSet = payload.readUnsignedShortLE();
  long columnLength = payload.readUnsignedIntLE();
  DataType type = DataType.valueOf(payload.readUnsignedByte());
  int flags = payload.readUnsignedShortLE();
  byte decimals = payload.readByte();
  return new ColumnDefinition(catalog, schema, table, orgTable, name, orgName, characterSet, columnLength, type, flags, decimals);
}
 
Example 7
Source File: FecPacket.java    From java-Kcp with Apache License 2.0 5 votes vote down vote up
public static FecPacket newFecPacket(ByteBuf byteBuf){
    FecPacket pkt = FEC_PACKET_RECYCLER.get();
    pkt.seqid =byteBuf.readUnsignedIntLE();
    pkt.flag = byteBuf.readUnsignedShortLE();
    pkt.data = byteBuf.retainedSlice(byteBuf.readerIndex(),byteBuf.capacity()-byteBuf.readerIndex());
    pkt.data.writerIndex(byteBuf.readableBytes());
    return pkt;
}
 
Example 8
Source File: GeometryWkbFormatCodec.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
private static LineString decodeLineString(ByteBuf buffer, long srid) {
  long numPoints = buffer.readUnsignedIntLE();
  List<Point> points = new ArrayList<>();
  for (long i = 0; i < numPoints; i++) {
    Point point = decodePoint(buffer, srid);
    points.add(point);
  }
  return new LineString(srid, points);
}
 
Example 9
Source File: LongCodec.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private static long decodeBinary(ByteBuf buf, short type, boolean isUnsigned) {
    switch (type) {
        case DataTypes.BIGINT:
            // Note: no check overflow for BIGINT UNSIGNED
            return buf.readLongLE();
        case DataTypes.INT:
            if (isUnsigned) {
                return buf.readUnsignedIntLE();
            } else {
                return buf.readIntLE();
            }
        case DataTypes.MEDIUMINT:
            // Note: MySQL return 32-bits two's complement for 24-bits integer
            return buf.readIntLE();
        case DataTypes.SMALLINT:
            if (isUnsigned) {
                return buf.readUnsignedShortLE();
            } else {
                return buf.readShortLE();
            }
        case DataTypes.YEAR:
            return buf.readShortLE();
        default: // TINYINT
            if (isUnsigned) {
                return buf.readUnsignedByte();
            } else {
                return buf.readByte();
            }
    }
}
 
Example 10
Source File: LocalTimeCodec.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private static LocalTime decodeBinary(ByteBuf buf) {
    int bytes = buf.readableBytes();

    if (bytes < TIME_SIZE) {
        return LocalTime.MIDNIGHT;
    }

    boolean isNegative = buf.readBoolean();

    // Skip day part.
    buf.skipBytes(Integer.BYTES);

    byte hour = buf.readByte();
    byte minute = buf.readByte();
    byte second = buf.readByte();

    if (bytes < MICRO_TIME_SIZE) {
        if (isNegative) {
            return negativeCircle(hour, minute, second);
        } else {
            return LocalTime.of(hour % HOURS_OF_DAY, minute, second);
        }
    }

    long nano = buf.readUnsignedIntLE() * NANOS_OF_MICRO;

    if (isNegative) {
        return negativeCircle(hour, minute, second, nano);
    } else {
        return LocalTime.of(hour % HOURS_OF_DAY, minute, second, (int) nano);
    }
}
 
Example 11
Source File: GeometryWkbFormatCodec.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
private static MultiPoint decodeMultiPoint(ByteBuf buffer, long srid) {
  long numWkbPoints = buffer.readUnsignedIntLE();
  List<Point> wkbPoints = new ArrayList<>();
  for (long i = 0; i < numWkbPoints; i++) {
    buffer.skipBytes(5);
    Point wkbPoint = decodePoint(buffer, srid);
    wkbPoints.add(wkbPoint);
  }
  return new MultiPoint(srid, wkbPoints);
}
 
Example 12
Source File: LongCodec.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private static long decodeBinary(ByteBuf buf, short type, boolean isUnsigned) {
    switch (type) {
        case DataTypes.BIGINT:
            // Note: no check overflow for BIGINT UNSIGNED
            return buf.readLongLE();
        case DataTypes.INT:
            if (isUnsigned) {
                return buf.readUnsignedIntLE();
            } else {
                return buf.readIntLE();
            }
        case DataTypes.MEDIUMINT:
            // Note: MySQL return 32-bits two's complement for 24-bits integer
            return buf.readIntLE();
        case DataTypes.SMALLINT:
            if (isUnsigned) {
                return buf.readUnsignedShortLE();
            } else {
                return buf.readShortLE();
            }
        case DataTypes.YEAR:
            return buf.readShortLE();
        default: // TINYINT
            if (isUnsigned) {
                return buf.readUnsignedByte();
            } else {
                return buf.readByte();
            }
    }
}
 
Example 13
Source File: LocalTimeCodec.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
private static LocalTime decodeBinary(ByteBuf buf) {
    int bytes = buf.readableBytes();

    if (bytes < TIME_SIZE) {
        return LocalTime.MIDNIGHT;
    }

    boolean isNegative = buf.readBoolean();

    // Skip day part.
    buf.skipBytes(Integer.BYTES);

    byte hour = buf.readByte();
    byte minute = buf.readByte();
    byte second = buf.readByte();

    if (bytes < MICRO_TIME_SIZE) {
        if (isNegative) {
            return negativeCircle(hour, minute, second);
        } else {
            return LocalTime.of(hour % HOURS_OF_DAY, minute, second);
        }
    }

    long nano = buf.readUnsignedIntLE() * NANOS_OF_MICRO;

    if (isNegative) {
        return negativeCircle(hour, minute, second, nano);
    } else {
        return LocalTime.of(hour % HOURS_OF_DAY, minute, second, (int) nano);
    }
}
 
Example 14
Source File: MySQLJsonValueDecoder.java    From shardingsphere with Apache License 2.0 4 votes vote down vote up
private static int getIntBasedObjectSize(final ByteBuf byteBuf, final boolean isSmall) {
    return isSmall ? byteBuf.readUnsignedShortLE() : (int) byteBuf.readUnsignedIntLE();
}
 
Example 15
Source File: GeometryWkbFormatCodec.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
public static Object decodeMySQLGeometry(ByteBuf buffer) {
  long srid = buffer.readUnsignedIntLE();
  buffer.readByte(); // byteOrder, always Little-endian for MySQL
  int type = buffer.readIntLE();
  return decodeWkbFormatGeometry(buffer, srid, type);
}
 
Example 16
Source File: VarIntUtils.java    From r2dbc-mysql with Apache License 2.0 4 votes vote down vote up
private static long crossReadLong0(ByteBuf firstPart, ByteBuf secondPart) {
    int readable = firstPart.readableBytes();

    if (readable == 0) {
        return secondPart.readLongLE();
    }

    long low, middle, high;

    switch (readable) {
        case 1:
            low = firstPart.readUnsignedByte();
            middle = (secondPart.readUnsignedIntLE() << Byte.SIZE);
            high = ((long) secondPart.readUnsignedMediumLE()) << (Byte.SIZE + Integer.SIZE);

            return high | middle | low;
        case 2:
            low = firstPart.readUnsignedShortLE();
            middle = secondPart.readUnsignedIntLE() << Short.SIZE;
            high = ((long) secondPart.readUnsignedShortLE()) << (Short.SIZE + Integer.SIZE);

            return high | middle | low;
        case 3:
            low = firstPart.readUnsignedMediumLE();
            middle = secondPart.readUnsignedIntLE() << MEDIUM_SIZE;
            high = ((long) secondPart.readUnsignedByte()) << (MEDIUM_SIZE + Integer.SIZE);

            return high | middle | low;
        case 4:
            low = firstPart.readUnsignedIntLE();
            high = secondPart.readUnsignedIntLE() << Integer.SIZE;

            return high | low;
        case 5:
            low = firstPart.readUnsignedIntLE();
            middle = ((long) firstPart.readUnsignedByte()) << Integer.SIZE;
            high = ((long) secondPart.readUnsignedMediumLE()) << (Integer.SIZE + Byte.SIZE);

            return high | middle | low;
        case 6:
            low = firstPart.readUnsignedIntLE();
            middle = ((long) firstPart.readUnsignedShortLE()) << Integer.SIZE;
            high = ((long) secondPart.readUnsignedShortLE()) << (Integer.SIZE + Short.SIZE);

            return high | middle | low;
        case 7:
            low = firstPart.readUnsignedIntLE();
            middle = ((long) firstPart.readUnsignedMediumLE()) << Integer.SIZE;
            high = ((long) secondPart.readUnsignedByte()) << (Integer.SIZE + MEDIUM_SIZE);

            return high | middle | low;
        default:
            return firstPart.readLongLE();
    }
}
 
Example 17
Source File: RntbdTokenType.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
@Override
public final Object read(final ByteBuf in) {
    final long length = in.readUnsignedIntLE();
    Codec.checkReadableBytes(in, length, Integer.MAX_VALUE);
    return in.readCharSequence((int)length, StandardCharsets.UTF_8).toString();
}
 
Example 18
Source File: RntbdTokenType.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
@Override
public final Object read(final ByteBuf in) {
    return in.readUnsignedIntLE();
}
 
Example 19
Source File: InitialHandshakeCommandCodec.java    From vertx-sql-client with Apache License 2.0 4 votes vote down vote up
private void handleInitialHandshake(ByteBuf payload) {
  encoder.clientCapabilitiesFlag = cmd.initialCapabilitiesFlags();
  encoder.encodingCharset = cmd.charsetEncoding();
  short protocolVersion = payload.readUnsignedByte();

  String serverVersion = BufferUtils.readNullTerminatedString(payload, StandardCharsets.US_ASCII);
  MySQLDatabaseMetadata md = MySQLDatabaseMetadata.parse(serverVersion);
  encoder.socketConnection.metaData = md;
  if (md.majorVersion() == 5 &&
      (md.minorVersion() < 7 || (md.minorVersion() == 7 && md.microVersion() < 5))) {
    // EOF_HEADER has to be enabled for older MySQL version which does not support the CLIENT_DEPRECATE_EOF flag
  } else {
    encoder.clientCapabilitiesFlag |= CLIENT_DEPRECATE_EOF;
  }

  long connectionId = payload.readUnsignedIntLE();

  // read first part of scramble
  this.authPluginData = new byte[NONCE_LENGTH];
  payload.readBytes(authPluginData, 0, AUTH_PLUGIN_DATA_PART1_LENGTH);

  //filler
  payload.readByte();

  // read lower 2 bytes of Capabilities flags
  int lowerServerCapabilitiesFlags = payload.readUnsignedShortLE();

  short characterSet = payload.readUnsignedByte();

  int statusFlags = payload.readUnsignedShortLE();

  // read upper 2 bytes of Capabilities flags
  int capabilityFlagsUpper = payload.readUnsignedShortLE();
  final int serverCapabilitiesFlags = (lowerServerCapabilitiesFlags | (capabilityFlagsUpper << 16));

  // length of the combined auth_plugin_data (scramble)
  short lenOfAuthPluginData;
  boolean isClientPluginAuthSupported = (serverCapabilitiesFlags & CapabilitiesFlag.CLIENT_PLUGIN_AUTH) != 0;
  if (isClientPluginAuthSupported) {
    lenOfAuthPluginData = payload.readUnsignedByte();
  } else {
    payload.readerIndex(payload.readerIndex() + 1);
    lenOfAuthPluginData = 0;
  }

  // 10 bytes reserved
  payload.readerIndex(payload.readerIndex() + 10);

  // Rest of the plugin provided data
  payload.readBytes(authPluginData, AUTH_PLUGIN_DATA_PART1_LENGTH, Math.max(NONCE_LENGTH - AUTH_PLUGIN_DATA_PART1_LENGTH, lenOfAuthPluginData - 9));
  payload.readByte(); // reserved byte

  // we assume the server supports auth plugin
  final String authPluginName = BufferUtils.readNullTerminatedString(payload, StandardCharsets.UTF_8);

  boolean upgradeToSsl;
  SslMode sslMode = cmd.sslMode();
  switch (sslMode) {
    case DISABLED:
      upgradeToSsl = false;
      break;
    case PREFERRED:
      upgradeToSsl = isTlsSupportedByServer(serverCapabilitiesFlags);
      break;
    case REQUIRED:
    case VERIFY_CA:
    case VERIFY_IDENTITY:
      upgradeToSsl = true;
      break;
    default:
      completionHandler.handle(CommandResponse.failure(new IllegalStateException("Unknown SSL mode to handle: " + sslMode)));
      return;
  }

  if (upgradeToSsl) {
    encoder.clientCapabilitiesFlag |= CLIENT_SSL;
    sendSslRequest();

    encoder.socketConnection.upgradeToSsl(upgrade -> {
      if (upgrade.succeeded()) {
        doSendHandshakeResponseMessage(authPluginName, authPluginData, serverCapabilitiesFlags);
      } else {
        completionHandler.handle(CommandResponse.failure(upgrade.cause()));
      }
    });
  } else {
    doSendHandshakeResponseMessage(authPluginName, authPluginData, serverCapabilitiesFlags);
  }
}
 
Example 20
Source File: DefinitionMetadataMessage.java    From r2dbc-mysql with Apache License 2.0 4 votes vote down vote up
private static DefinitionMetadataMessage decode41(ByteBuf buf, ConnectionContext context) {
    buf.skipBytes(4); // "def" which sized by var integer

    CharCollation collation = context.getClientCollation();
    Charset charset = collation.getCharset();
    String database = readVarIntSizedString(buf, charset);
    String table = readVarIntSizedString(buf, charset);
    String originTable = readVarIntSizedString(buf, charset);
    String column = readVarIntSizedString(buf, charset);
    String originColumn = readVarIntSizedString(buf, charset);

    VarIntUtils.readVarInt(buf); // skip constant 0x0c encoded by var integer

    int collationId = buf.readUnsignedShortLE();
    long size = buf.readUnsignedIntLE();
    short type = buf.readUnsignedByte();
    short definitions = buf.readShortLE();

    if (DataTypes.JSON == type && collationId == CharCollation.BINARY_ID) {
        collationId = collation.getId();
    }

    if ((definitions & ColumnDefinitions.SET) != 0) {
        // Maybe need to check if it is a string-like type?
        type = DataTypes.SET;
    } else if ((definitions & ColumnDefinitions.ENUMERABLE) != 0) {
        // Maybe need to check if it is a string-like type?
        type = DataTypes.ENUMERABLE;
    }

    return new DefinitionMetadataMessage(
        database,
        table,
        originTable,
        column,
        originColumn,
        collationId,
        size,
        type,
        definitions,
        buf.readUnsignedByte()
    );
}