Example usage for java.nio ByteBuffer put

List of usage examples for java.nio ByteBuffer put

Introduction

In this page you can find the example usage for java.nio ByteBuffer put.

Prototype

public ByteBuffer put(ByteBuffer src) 

Source Link

Document

Writes all the remaining bytes of the src byte buffer to this buffer's current position, and increases both buffers' position by the number of bytes copied.

Usage

From source file:com.spotify.heroic.metric.datastax.schema.legacy.MapSerializer.java

@Override
public ByteBuffer serialize(final Map<A, B> value) throws IOException {
    final List<Pair<ByteBuffer, ByteBuffer>> buffers = new ArrayList<>();

    short size = 0;

    for (final Map.Entry<A, B> e : value.entrySet()) {
        final ByteBuffer key = a.serialize(e.getKey());
        final ByteBuffer val = b.serialize(e.getValue());

        size += key.limit() + val.limit();

        buffers.add(Pair.of(key, val));
    }/*  w w w .j  a  v  a  2  s  .c o m*/

    final ByteBuffer buffer = ByteBuffer.allocate(4 + 8 * value.size() + size);
    buffer.putShort((short) buffers.size());

    for (final Pair<ByteBuffer, ByteBuffer> p : buffers) {
        buffer.putShort((short) p.getLeft().remaining());
        buffer.put(p.getLeft());
        buffer.putShort((short) p.getRight().remaining());
        buffer.put(p.getRight());
    }

    buffer.flip();
    return buffer;
}

From source file:com.freshplanet.ane.GoogleCloudStorageUpload.tasks.UploadToGoogleCloudStorageAsyncTask.java

private byte[] createHeaderByteArrayImage(byte[] prefix, byte[] suffix, byte[] image) {
    Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] Entering createHeaderByteArrayImage()");

    int size = image.length + prefix.length + suffix.length;
    ByteBuffer bytes = ByteBuffer.allocate(size);
    bytes.put(prefix);
    bytes.put(image);/*from w  ww .j a v  a  2 s.  c o m*/
    bytes.put(suffix);

    Log.d(TAG, "[UploadToGoogleCloudStorageAsyncTask] Exiting createHeaderByteArrayImage()");
    return bytes.array();
}

From source file:com.digium.respokesdk.RespokeDirectConnection.java

/**
 *  Send a message to the remote client through the direct connection.
 *
 *  @param message             The message to send
 *  @param completionListener  A listener to receive a notification on the success of the asynchronous operation
 *//*  w  w w  .  ja v a2 s.  c o m*/
public void sendMessage(String message, final Respoke.TaskCompletionListener completionListener) {
    if (isActive()) {
        JSONObject jsonMessage = new JSONObject();
        try {
            jsonMessage.put("message", message);
            byte[] rawMessage = jsonMessage.toString().getBytes(Charset.forName("UTF-8"));
            ByteBuffer directData = ByteBuffer.allocateDirect(rawMessage.length);
            directData.put(rawMessage);
            directData.flip();
            DataChannel.Buffer data = new DataChannel.Buffer(directData, false);

            if (dataChannel.send(data)) {
                Respoke.postTaskSuccess(completionListener);
            } else {
                Respoke.postTaskError(completionListener, "Error sending message");
            }
        } catch (JSONException e) {
            Respoke.postTaskError(completionListener, "Unable to encode message to JSON");
        }
    } else {
        Respoke.postTaskError(completionListener, "DataChannel not in an open state");
    }
}

From source file:ed.net.lb.LBCall.java

protected ByteStream fillInRequest(ByteBuffer buf) {
    buf.put(generateRequestHeader().getBytes());
    if (_request.getPostData() != null)
        return _request.getPostData().getByteStream();
    return null;// w w w . j  a v  a  2  s. co m
}

From source file:edu.umass.cs.gigapaxos.paxospackets.AcceptReplyPacket.java

public ByteBuffer toBytes(ByteBuffer bbuf) throws UnsupportedEncodingException {
    super.toBytes(bbuf);
    assert (bbuf.position() == SIZEOF_PAXOSPACKET_FIXED + this.getPaxosID().getBytes(CHARSET).length);
    bbuf.putInt(this.acceptor).putInt(this.ballot.ballotNumber).putInt(this.ballot.coordinatorID)
            .putInt(this.slotNumber).putInt(this.maxCheckpointedSlot).putLong(this.requestID)
            .put(this.isUndigestRequest() ? (byte) 1 : (byte) 0);
    return bbuf;//from  ww  w  .j a  v a 2  s .  com
}

From source file:com.google.cloud.bigtable.hbase.TestIncrement.java

/**
 * Requirement 6.6/*from   www  .jav  a2s .com*/
 */
@Test
public void testIncrementEightBytes() throws IOException {
    // Initialize
    Table table = getConnection().getTable(TABLE_NAME);
    byte[] rowKey = dataHelper.randomData("testrow-");
    byte[] qual = dataHelper.randomData("qual-");
    byte[] value = new byte[8];
    new Random().nextBytes(value);
    ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE);
    buffer.put(value);
    buffer.flip();
    long equivalentValue = buffer.getLong();

    // Put the bytes in
    Put put = new Put(rowKey).addColumn(COLUMN_FAMILY, qual, value);
    table.put(put);

    // Increment
    Increment increment = new Increment(rowKey).addColumn(COLUMN_FAMILY, qual, 1L);
    Result result = table.increment(increment);
    Assert.assertEquals("Should have incremented the bytes like a long", equivalentValue + 1L,
            Bytes.toLong(CellUtil.cloneValue(result.getColumnLatestCell(COLUMN_FAMILY, qual))));
}

From source file:com.cellngine.crypto.RSACipher.java

private byte[] encode(final BigInteger modulus, final BigInteger exponent) {
    final byte[] modulusEnc = modulus.toByteArray();
    final byte[] exponentEnc = exponent.toByteArray();
    final ByteBuffer buffer = ByteBuffer.allocate(2 * 4 + modulusEnc.length + exponentEnc.length);
    buffer.putInt(modulusEnc.length);//from w w w . ja va2 s  .co m
    buffer.put(modulusEnc);
    buffer.putInt(exponentEnc.length);
    buffer.put(exponentEnc);
    return buffer.array();
}

From source file:com.alibaba.jstorm.utils.JStormUtils.java

public static long bytesToLong(byte[] bytes) {
    ByteBuffer buffer = ByteBuffer.allocate(Long.SIZE);
    buffer.put(bytes);
    buffer.flip();// need flip
    return buffer.getLong();
}

From source file:com.sm.connector.server.ServerStore.java

private void writeIndexBlock(CacheBlock<byte[]> block, long keyOffset2Len, FileChannel channel)
        throws IOException {
    long pos = OFFSET + (long) block.getRecordNo() * RECORD_SIZE;
    checkFileSize(pos, RECORD_SIZE);//from www.j av a  2s .  c om
    ByteBuffer buf = ByteBuffer.allocate(RECORD_SIZE);
    buf.put(block.getStatus());
    buf.putLong(keyOffset2Len);
    buf.putLong(block.getDataOffset2Len());
    buf.putLong(block.getBlock2Version());
    buf.putShort(block.getNode());
    buf.flip();
    channel.write(buf, pos);
}

From source file:io.warp10.quasar.encoder.QuasarTokenEncoder.java

public String cypherToken(TBase<?, ?> token, KeyStore keyStore) throws TException {
    byte[] tokenAesKey = keyStore.getKey(KeyStore.AES_TOKEN);
    byte[] tokenSipHashkey = keyStore.getKey(KeyStore.SIPHASH_TOKEN);

    // Serialize the  thrift token into byte array
    byte[] serialized = serializer.serialize(token);

    // Calculate the SIP
    long sip = SipHashInline.hash24_palindromic(tokenSipHashkey, serialized);

    //Create the token byte buffer
    ByteBuffer buffer = ByteBuffer.allocate(8 + serialized.length);
    // adds the sip
    buffer.putLong(sip);//w w w  .j ava  2 s .co  m
    // adds the thrift token
    buffer.put(serialized);

    // Wrap the TOKEN
    byte[] wrappedData = CryptoUtils.wrap(tokenAesKey, buffer.array());

    String accessToken = new String(OrderPreservingBase64.encode(wrappedData));

    return accessToken;
}