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.linkedin.databus.core.DbusEventV2.java

public static int serializeEvent(DbusEventKey key, ByteBuffer buf, DbusEventInfo dbusEventInfo) {
    // Serialize a DbusEventV2 that has exact same contents as a DbusEventV1.
    final int start = buf.position();
    buf.put(DbusEventFactory.DBUS_EVENT_V2);
    buf.putInt(MAGIC);/*  ww  w. j ava 2  s.c o  m*/
    buf.putInt(0); // Header len placeholder
    buf.putInt(0); // Header crc placeholder
    buf.putInt(0); // Body CRC placeholder
    buf.putInt(0); // total length placeholder

    short attributes = 0;
    attributes = setOpCode(dbusEventInfo.getOpCode(), attributes, dbusEventInfo.getSrcId());
    attributes = setKeyType(key, attributes);
    if (dbusEventInfo.isEnableTracing()) {
        attributes |= FLAG_TRACE_ON;
    }

    if (dbusEventInfo.isReplicated()) {
        attributes |= FLAG_IS_REPLICATED;
    }

    DbusEventPart metadata = dbusEventInfo.getMetadata();
    if (shouldEncodePayloadPart(dbusEventInfo)) {
        attributes |= FLAG_HAS_PAYLOAD_PART;
    }
    if (metadata != null) {
        attributes |= FLAG_HAS_PAYLOAD_METADATA_PART;
    }
    buf.putShort(attributes);
    buf.putLong(dbusEventInfo.getTimeStampInNanos());
    buf.putInt(dbusEventInfo.getSrcId());
    buf.putShort(dbusEventInfo.getpPartitionId());
    buf.putLong(dbusEventInfo.getSequenceId());

    // Fixed part of header is done. Now for the variable header part
    setKey(buf, key);
    final int hdrEndPos = buf.position();

    if (metadata != null) {
        metadata.encode(buf);
    }

    if ((attributes & FLAG_HAS_PAYLOAD_PART) != 0) {
        ByteBuffer bb = dbusEventInfo.getValueByteBuffer();
        if (bb == null) {
            // Special case to encode when there is no data.
            bb = ByteBuffer.allocate(1).order(buf.order());
            bb.limit(0);
        }
        DbusEventPart valuePart = new DbusEventPart(SchemaDigestType.MD5, dbusEventInfo.getSchemaId(),
                dbusEventInfo.getPayloadSchemaVersion(), bb);
        valuePart.encode(buf);
    }
    final int end = buf.position();
    buf.putInt(start + HeaderLenOffset, hdrEndPos - start);
    buf.putInt(start + TotalLenOffset, end - start);

    long bodyCrc = ByteBufferCRC32.getChecksum(buf, hdrEndPos, end - hdrEndPos);
    Utils.putUnsignedInt(buf, start + BodyCrcOffset, bodyCrc);
    // Header CRC
    if (dbusEventInfo.isAutocommit()) {
        // Do the body CRC first, since that is included in the header CRC
        long hdrCrc = ByteBufferCRC32.getChecksum(buf, start + BodyCrcOffset,
                hdrEndPos - start - BodyCrcOffset);
        Utils.putUnsignedInt(buf, start + HeaderCrcOffset, hdrCrc);
    }
    return buf.position() - start;
}

From source file:com.openteach.diamond.network.waverider.command.MasterGreetCommandHandler.java

private Command makeGreetCommand(Session session) {
    String hello = new StringBuilder("Hello slave:").append(session.getSlaveWorker().getIp()).toString();
    ByteBuffer buffer = ByteBuffer.allocate(hello.getBytes().length);
    buffer.put(hello.getBytes());
    buffer.flip();//  www .java2  s .  c  o  m

    Command command = new Command(1L, buffer);

    return command;
}

From source file:com.offbynull.portmapper.natpmp.NatPmpRequest.java

/**
 * Dump this NAT-PMP request in to a byte buffer.
 * @param dst byte buffer to dump to//from   ww  w. ja va2 s.co m
 * @throws NullPointerException if any argument is {@code null}
 * @throws BufferOverflowException if {@code dst} doesn't have enough space to write this option
 * @throws ReadOnlyBufferException if {@code dst} is read-only
 */
public final void dump(ByteBuffer dst) {
    Validate.notNull(dst);

    dst.put((byte) 0);
    dst.put((byte) op);

    dumpOpCodeSpecificInformation(dst);
}

From source file:com.kactech.otj.Utils.java

public static ByteBuffer seal(String msg, String nymID, PublicKey nymKey, SecretKeySpec aesSecret,
        IvParameterSpec vector) throws InvalidKeyException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException {
    ByteBuffer buff = ByteBuffer.allocate(msg.length() + 500);//donno?
    buff.order(ByteOrder.BIG_ENDIAN);
    buff.putShort((short) 1);//asymmetric
    buff.putInt(1);//array size
    buff.putInt(nymID.length() + 1);//from   www  . j av  a2 s .  c o m
    buff.put(bytes(nymID + '\0', US_ASCII));

    // create encoded key and message
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    cipher.init(Cipher.ENCRYPT_MODE, aesSecret, vector);
    byte[] encrypted = cipher.doFinal(bytes(msg + '\0', UTF8));
    try {
        cipher = Cipher.getInstance(WRAP_ALGO);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    cipher.init(Cipher.WRAP_MODE, nymKey);
    byte[] encKeyBytes = cipher.wrap(aesSecret);

    buff.putInt(encKeyBytes.length);
    buff.put(encKeyBytes);
    buff.putInt(vector.getIV().length);
    buff.put(vector.getIV());
    buff.put(encrypted);
    buff.flip();

    return buff;
}

From source file:com.github.neoio.net.message.staging.memory.TestMemoryMessageStaging.java

@Test
public void test_tempRead() {
    ByteBuffer buffer = ByteBuffer.allocate(1024);

    buffer.put("Hello World".getBytes());
    buffer.rewind();/*from ww w.  j  a v a2  s . c  om*/
    staging.writeTempReadBytes(buffer);
    Assert.assertTrue(staging.hasTempReadBytes());

    buffer.clear();
    staging.readTempReadBytes(buffer);
    Assert.assertEquals("Hello World",
            new String(ArrayUtils.subarray(buffer.array(), 0, "Hello World".getBytes().length)));
    staging.resetTempReadBytes();

    Assert.assertFalse(staging.hasTempReadBytes());
}

From source file:com.github.neoio.net.message.staging.memory.TestMemoryMessageStaging.java

@Test
public void test_tempWrite() {
    ByteBuffer buffer = ByteBuffer.allocate(1024);

    buffer.put("Hello World".getBytes());
    buffer.rewind();/* w  w w.  j  a  va2  s.  c  o m*/
    staging.writeTempWriteBytes(buffer);
    Assert.assertTrue(staging.hasTempWriteBytes());

    buffer.clear();
    staging.readTempWriteBytes(buffer);
    Assert.assertEquals("Hello World",
            new String(ArrayUtils.subarray(buffer.array(), 0, "Hello World".getBytes().length)));
    staging.resetTempWriteBytes();

    Assert.assertFalse(staging.hasTempWriteBytes());
}

From source file:net.cellcloud.talk.stuff.PrimitiveSerializer.java

/** ?
 *///w ww .j  a v  a 2 s . c  o m
private static int reviseValue(ByteBuffer buf, byte[] input) {
    int length = 0;
    int inputLength = input.length;

    for (int i = 0; i < inputLength; ++i) {
        byte b = input[i];
        if (b == TOKEN_OPEN_BRACE || b == TOKEN_CLOSE_BRACE || b == TOKEN_OPERATE_ASSIGN
                || b == TOKEN_OPERATE_DECLARE) {
            buf.put((byte) '\\');
            ++length;
        }

        buf.put(b);
        ++length;
    }

    return length;
}

From source file:com.eventsourcing.layout.binary.ByteArrayBinarySerializer.java

@Override
public void serialize(Object value, ByteBuffer buffer) {
    byte[] bytes = getPrimitiveArray(value);
    buffer.putInt(bytes.length);//from www .j a  v  a2s . c  o  m
    buffer.put(bytes);
}

From source file:com.talis.storage.s3.ExternalizableS3ObjectTest.java

@Test
public void roundTripS3ObjectSerialization() throws Exception {
    ByteArrayOutputStream tmp = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(tmp);

    byte[] bytes = ("When replying to any emails you have prior to migration "
            + "(ie any in your inbox before you have been migrated) "
            + "you will need to change the way you reply to them").getBytes();

    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
    buffer.put(bytes);

    S3ObjectFactory factory = new S3ObjectFactory("bucket");
    S3Object original = factory.newObject("foo", 0, MediaType.TEXT_PLAIN_TYPE, buffer);

    out.writeObject(original);/*from   www  .j  av a2  s .c o m*/
    out.flush();
    out.close();

    byte[] serialized = tmp.toByteArray();

    ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(serialized));
    S3Object clone = (S3Object) in.readObject();

    assertObjectsEqual(original, clone);
}

From source file:org.cloudfoundry.caldecott.server.controller.TunnelController.java

@RequestMapping(value = "/{id}/out/{seq}", method = RequestMethod.GET)
@ResponseBody//from www.ja v  a2  s  . c o  m
public ByteBuffer read(@PathVariable TunnelId id, @PathVariable int seq) {
    // FIXME async
    // Tunnel tunnel = this.tunnels.get(id);
    // BlockingCallback<ByteBuffer> callback = BlockingCallback.forClass(ByteBuffer.class);
    // tunnel.read(seq, callback);
    // return callback.get();
    ByteBuffer buffer = ByteBuffer.allocateDirect(100);
    buffer.put("hello".getBytes());
    buffer.flip();
    return buffer;
}