Java Code Examples for java.nio.ByteBuffer#putLong()

The following examples show how to use java.nio.ByteBuffer#putLong() . 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: TestMultiByteBuff.java    From hbase with Apache License 2.0 6 votes vote down vote up
@Test
public void testSkipNBytes() {
  ByteBuffer bb1 = ByteBuffer.allocate(15);
  ByteBuffer bb2 = ByteBuffer.allocate(15);
  bb1.putInt(4);
  long l1 = 45L, l2 = 100L, l3 = 12345L;
  bb1.putLong(l1);
  bb1.putShort((short) 2);
  byte[] b = Bytes.toBytes(l2);
  bb1.put(b, 0, 1);
  bb2.put(b, 1, 7);
  bb2.putLong(l3);
  MultiByteBuff multi = new MultiByteBuff(bb1, bb2);
  assertEquals(4, multi.getInt());
  assertEquals(l1, multi.getLong());
  multi.skip(10);
  assertEquals(l3, multi.getLong());
}
 
Example 2
Source File: BinaryCommand.java    From Mycat-JCache with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 待重构
 * @param conn
 * @param opcode
 * @param status
 */
public static void writeResponseError(Connection conn,byte opcode,short status){
	int totallen = BinaryProtocol.memcache_packetHeaderSize;
	ByteBuffer write = ByteBuffer.allocate(totallen);
	write.put(ProtocolMagic.PROTOCOL_BINARY_RES.getByte());
	write.put(opcode);
	write.putShort((short)0x0000);
	write.put((byte)0x00);
	write.put(ProtocolDatatypes.PROTOCOL_BINARY_RAW_BYTES.getByte());
	write.putShort(status);
	write.putInt(0x00);
	write.putInt(0);
	write.putLong(0);
	conn.addWriteQueue(write);
	conn.enableWrite(true);
}
 
Example 3
Source File: Decimal64Element.java    From qpid-proton-j with Apache License 2.0 6 votes vote down vote up
@Override
public int encode(ByteBuffer b)
{
    int size = size();
    if(b.remaining()>=size)
    {
        if(size == 9)
        {
            b.put((byte)0x84);
        }
        b.putLong(_value.getBits());
        return size;
    }
    else
    {
        return 0;
    }
}
 
Example 4
Source File: QLogManagerImpl.java    From ffwd with Apache License 2.0 6 votes vote down vote up
private void flushIndex() throws IOException {
    final Path index = this.path.resolve(INDEX);

    final ByteBuffer writer = ByteBuffer.allocate(12);

    try (final OutputStream output = Files.newOutputStream(index)) {
        for (final Map.Entry<String, Long> e : offsets.entrySet()) {
            writer.rewind();

            final byte[] idBytes = e.getKey().getBytes(UTF8);
            writer.putInt(idBytes.length);
            writer.putLong(e.getValue());
            writer.flip();
            output.write(writer.array(), 0, writer.remaining());
            output.write(idBytes);
        }
    }
}
 
Example 5
Source File: RaftId.java    From incubator-ratis with Apache License 2.0 5 votes vote down vote up
private static ByteString toByteString(UUID uuid) {
  Objects.requireNonNull(uuid, "uuid == null");
  final ByteBuffer buf = ByteBuffer.wrap(new byte[BYTE_LENGTH]);
  buf.putLong(uuid.getMostSignificantBits());
  buf.putLong(uuid.getLeastSignificantBits());
  return ByteString.copyFrom(buf.array());
}
 
Example 6
Source File: BlockVote.java    From nyzoVerifier with The Unlicense 5 votes vote down vote up
@Override
public byte[] getBytes() {

    byte[] array = new byte[getByteSize()];

    ByteBuffer buffer = ByteBuffer.wrap(array);
    buffer.putLong(height);
    buffer.put(hash);
    buffer.putLong(timestamp);

    return array;
}
 
Example 7
Source File: GenericFile.java    From strongbox with Apache License 2.0 5 votes vote down vote up
public byte[] toByteArray() {
    List<Entry> entries = stream().toList();
    Size size = computeLength(entries);

    int headerSize = 1 + 4 + 8;

    ByteBuffer byteBuffer = ByteBuffer.allocate(headerSize + size.totalSize);

    byteBuffer.put((byte)1); // version
    byteBuffer.putLong(entries.size()); // number of entries

    for (Entry entry : entries) {
        byteBuffer.put((byte)1); // version

        for (String fieldName : fieldNames) {
            Object value = getValue(entry, fieldName);
            Class<?> clz = getConvertedType(fieldName);
            int padding = getPadding(fieldName);

            if (isOptional(fieldName)) {
                if (value == null) {
                    byteBuffer.put((byte)0);
                } else {
                    byteBuffer.put((byte)1);
                }
            }

            if (value == null) {
                    writeDummy(clz, byteBuffer, padding);
            } else {
                    write(clz, value, byteBuffer, padding);
            }
        }
    }

    byteBuffer.putInt(size.padding);
    byteBuffer.put(new byte[size.padding]);

    return byteBuffer.array();
}
 
Example 8
Source File: TraceAndSpanIdGeneratorTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Test
public void convertBytesToLong_should_work_correctly_for_known_value() {
    // given: byte[] that maps to known long value
    final long EXPECTED_LONG_VALUE = 4242424242L;
    ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE / 8);
    buffer.putLong(EXPECTED_LONG_VALUE);
    byte[] longAsByteArray = buffer.array();
    assertThat(longAsByteArray.length).isEqualTo(8);

    // when: convertBytesToLong() is called
    long returnVal = TraceAndSpanIdGenerator.convertBytesToLong(longAsByteArray);

    // then: the return value is what we expect
    assertThat(returnVal).isEqualTo(EXPECTED_LONG_VALUE);
}
 
Example 9
Source File: AtomicBufferTest.java    From agrona with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("buffers")
public void shouldGetAndSetLongToNativeBuffer(final AtomicBuffer buffer)
{
    final ByteBuffer duplicateBuffer = byteBuffer(buffer);
    duplicateBuffer.order(ByteOrder.nativeOrder());

    duplicateBuffer.putLong(INDEX, LONG_VALUE);

    final long afterValue = 1;
    final long beforeValue = buffer.getAndSetLong(INDEX, afterValue);

    assertThat(beforeValue, is(LONG_VALUE));
    assertThat(duplicateBuffer.getLong(INDEX), is(afterValue));
}
 
Example 10
Source File: RowKeyUtils.java    From emodb with Apache License 2.0 5 votes vote down vote up
private static ByteBuffer getScanPrefix(int shardId, long tableUuid) {
    checkArgument(shardId >= 0 && shardId < 256);

    // Assemble an array which is "1 byte shard id + 8 byte table uuid".
    ByteBuffer rowKey = ByteBuffer.allocate(9);
    rowKey.put((byte) shardId);
    rowKey.putLong(tableUuid);

    rowKey.flip();
    return rowKey;
}
 
Example 11
Source File: GenericFile.java    From strongbox with Apache License 2.0 5 votes vote down vote up
private void writeDummy(Class<?> type, ByteBuffer byteBuffer, int padding) {
    if (type.equals(String.class)) {
        writeArray(byteBuffer, new byte[0]);
    } else if (type.equals(Byte.class)) {
        byteBuffer.put((byte)0);
    } else if (type.equals(Long.class)) {
        byteBuffer.putLong(0);
    } else if (type.equals(byte[].class)) {
        writeArray(byteBuffer, new byte[0]);
    }
}
 
Example 12
Source File: DATFile.java    From ECG-Viewer with GNU General Public License v2.0 5 votes vote down vote up
private ByteBuffer longArrToBytes(long[] arr) {
	ByteBuffer bb = ByteBuffer.allocate(arr.length * 8);
	for(int i = 0; i < arr.length; i++) {
		bb.putLong(arr[i]);
	}
	return bb;
}
 
Example 13
Source File: TxRecordSerializer.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Writes {@link MvccVersion} to given buffer.
 *
 * @param buf Buffer to write.
 * @param mvccVer Mvcc version.
 */
public void putMvccVersion(ByteBuffer buf, MvccVersion mvccVer) {
    buf.putLong(mvccVer.coordinatorVersion());
    buf.putLong(mvccVer.counter());

    buf.putInt(mvccVer.operationCounter());
}
 
Example 14
Source File: HBaseStore.java    From joyqueue with Apache License 2.0 5 votes vote down vote up
/**
 * 构建 rowkey
 *
 * @param rowKey
 * @return
 * @throws GeneralSecurityException
 * @throws JoyQueueException
 */
private byte[] createRowKey(QueryCondition.RowKey rowKey) throws GeneralSecurityException, JoyQueueException {
    // 4 + 8 + 16 + 16
    ByteBuffer allocate = ByteBuffer.allocate(44);

    int topicId = topicAppMapping.getTopicId(rowKey.getTopic());
    long crateTime = rowKey.getTime();
    String businessId = rowKey.getBusinessId();
    String messageId = rowKey.getMessageId();

    allocate.putInt(topicId);
    if (StringUtils.isNotEmpty(businessId)) {
        allocate.put(Md5.INSTANCE.encrypt(businessId.getBytes(), null));
        allocate.putLong(crateTime);
    } else {
        allocate.putLong(crateTime);
        // 没有businessId填充16个字节
        allocate.put(new byte[16]);
    }
    if (messageId != null) {
        allocate.put(new BigInteger(messageId, 16).toByteArray());
    } else {
        // 没有messageId填充16个字节
        allocate.put(new byte[16]);
    }

    return allocate.array();
}
 
Example 15
Source File: CloudBlobCryptoAgentImpl.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Serialize the {@link EncryptedDataPayload} into an output buffer.
 * @param outputBuffer the {@link ByteBuffer} to write to.  Currently, only HeapByteBuffer is supported.
 * @param encryptedDataPayload the {@link EncryptedDataPayload} to serialize.
 */
static void serialize(ByteBuffer outputBuffer, EncryptedDataPayload encryptedDataPayload) {
  int startOffset = outputBuffer.position();
  outputBuffer.putShort(CURRENT_VERSION);
  int encryptedKeySize = encryptedDataPayload.encryptedKey.array().length;
  int encryptedDataSize = encryptedDataPayload.encryptedData.array().length;
  outputBuffer.putInt(encryptedKeySize);
  outputBuffer.putLong(encryptedDataSize);
  outputBuffer.put(encryptedDataPayload.encryptedKey);
  outputBuffer.put(encryptedDataPayload.encryptedData);
  Crc32 crc = new Crc32();
  crc.update(outputBuffer.array(), startOffset, INITIAL_MESSAGE_LENGTH + encryptedKeySize + encryptedDataSize);
  outputBuffer.putLong(crc.getValue());
}
 
Example 16
Source File: NDArrayMessage.java    From nd4j with Apache License 2.0 5 votes vote down vote up
/**
 * Convert a message to a direct buffer.
 * See {@link NDArrayMessage#fromBuffer(DirectBuffer, int)}
 * for a description of the format for the buffer
 * @param message the message to convert
 * @return a direct byte buffer representing this message.
 */
public static DirectBuffer toBuffer(NDArrayMessage message) {
    ByteBuffer byteBuffer =
                    ByteBuffer.allocateDirect(byteBufferSizeForMessage(message)).order(ByteOrder.nativeOrder());
    //declare message opType
    byteBuffer.putInt(MessageType.WHOLE.ordinal());
    //perform the ndarray put on the
    if (message.getArr().isCompressed()) {
        AeronNDArraySerde.doByteBufferPutCompressed(message.getArr(), byteBuffer, false);
    } else {
        AeronNDArraySerde.doByteBufferPutUnCompressed(message.getArr(), byteBuffer, false);
    }

    long sent = message.getSent();
    long index = message.getIndex();

    byteBuffer.putLong(sent);
    byteBuffer.putLong(index);
    byteBuffer.putInt(message.getDimensions().length);
    for (int i = 0; i < message.getDimensions().length; i++) {
        byteBuffer.putInt(message.getDimensions()[i]);
    }

    //rewind the buffer before putting it in to the unsafe buffer
    //note that we set rewind to false in the do byte buffer put methods
    byteBuffer.rewind();

    return new UnsafeBuffer(byteBuffer);
}
 
Example 17
Source File: BlockRequest.java    From nyzoVerifier with The Unlicense 5 votes vote down vote up
@Override
public byte[] getBytes() {

    byte[] array = new byte[getByteSize()];
    ByteBuffer buffer = ByteBuffer.wrap(array);
    buffer.putLong(startHeight);
    buffer.putLong(endHeight);
    buffer.put(includeBalanceList ? (byte) 1 : (byte) 0);

    return array;
}
 
Example 18
Source File: Int8Datum.java    From incubator-tajo with Apache License 2.0 4 votes vote down vote up
@Override
public byte [] asByteArray() {
	ByteBuffer bb = ByteBuffer.allocate(8);
	bb.putLong(val);
	return bb.array();
}
 
Example 19
Source File: UuidUtil.java    From debezium-incubator with Apache License 2.0 4 votes vote down vote up
public static byte[] asBytes(final UUID uuid) {
    ByteBuffer bb = ByteBuffer.wrap(new byte[BYTE_SIZE]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return bb.array();
}
 
Example 20
Source File: SelectReceiveSendUdpPong.java    From aeron with Apache License 2.0 4 votes vote down vote up
private void run() throws IOException
{
    final InetSocketAddress sendAddress = new InetSocketAddress("localhost", Common.PONG_PORT);

    final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);

    final DatagramChannel receiveChannel = DatagramChannel.open();
    Common.init(receiveChannel);
    receiveChannel.bind(new InetSocketAddress("localhost", Common.PING_PORT));

    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);

    final Selector selector = Selector.open();

    final IntSupplier handler =
        () ->
        {
            try
            {
                buffer.clear();
                receiveChannel.receive(buffer);

                final long receivedSequenceNumber = buffer.getLong(0);
                final long receivedTimestamp = buffer.getLong(SIZE_OF_LONG);

                buffer.clear();
                buffer.putLong(receivedSequenceNumber);
                buffer.putLong(receivedTimestamp);
                buffer.flip();

                sendChannel.send(buffer, sendAddress);
            }
            catch (final IOException ex)
            {
                ex.printStackTrace();
            }

            return 1;
        };

    receiveChannel.register(selector, OP_READ, handler);

    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    while (true)
    {
        while (selector.selectNow() == 0)
        {
            if (!running.get())
            {
                return;
            }
        }

        final Set<SelectionKey> selectedKeys = selector.selectedKeys();
        final Iterator<SelectionKey> iter = selectedKeys.iterator();

        while (iter.hasNext())
        {
            final SelectionKey key = iter.next();
            if (key.isReadable())
            {
                ((IntSupplier)key.attachment()).getAsInt();
            }

            iter.remove();
        }
    }
}