Example usage for java.nio ByteBuffer wrap

List of usage examples for java.nio ByteBuffer wrap

Introduction

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

Prototype

public static ByteBuffer wrap(byte[] array) 

Source Link

Document

Creates a new byte buffer by wrapping the given byte array.

Usage

From source file:com.icloud.framework.core.nio.ByteBufferUtil.java

public static ByteBuffer clone(ByteBuffer o) {
    assert o != null;

    if (o.remaining() == 0)
        return ByteBuffer.wrap(ArrayUtils.EMPTY_BYTE_ARRAY);

    ByteBuffer clone = ByteBuffer.allocate(o.remaining());

    if (o.isDirect()) {
        for (int i = o.position(); i < o.limit(); i++) {
            clone.put(o.get(i));//from   w w  w.j  ava  2  s.  co m
        }
        clone.flip();
    } else {
        System.arraycopy(o.array(), o.arrayOffset() + o.position(), clone.array(), 0, o.remaining());
    }

    return clone;
}

From source file:io.druid.segment.writeout.WriteOutBytesTest.java

@Test
public void testWriteOutBytes() throws IOException {
    WriteOutBytes writeOutBytes = segmentWriteOutMedium.makeWriteOutBytes();

    writeOutBytes.write('1');
    verifyContents(writeOutBytes, "1");

    writeOutBytes.writeInt(Ints.fromBytes((byte) '2', (byte) '3', (byte) '4', (byte) '5'));
    verifyContents(writeOutBytes, "12345");

    writeOutBytes.write(new byte[] { 'a' });
    verifyContents(writeOutBytes, "12345a");

    writeOutBytes.write(new byte[] { 'a', 'b', 'c' }, 1, 1);
    verifyContents(writeOutBytes, "12345ab");

    ByteBuffer bb = ByteBuffer.wrap(new byte[] { 'a', 'b', 'c' });
    bb.position(2);//w ww  .  j  a  va  2s  .  c o  m
    writeOutBytes.write(bb);
    Assert.assertEquals(3, bb.position());
    verifyContents(writeOutBytes, "12345abc");
}

From source file:ezbake.services.graph.archive.TransactionIdGenerator.java

public TransactionIdGenerator(String interfaceName) {
    ByteBuffer buf = ByteBuffer.wrap(getMacAddress(interfaceName));
    serverId = buf.getInt();
    lastTime = -1L;
    sequence = 0;
}

From source file:com.pushtechnology.diffusion.examples.runnable.RandomData.java

/**
 * Deserialize a {@link Binary} value as a {@link RandomData} value.
 * @param binary The {@link Binary} value
 * @return The {@link RandomData} value//from   w ww .  j  av a2s .  co m
 */
static RandomData fromBinary(Binary binary) {
    final ByteBuffer buffer = ByteBuffer.wrap(binary.toByteArray());
    final int id = buffer.getInt();
    final long timestamp = buffer.getLong();
    final int randomInt = buffer.getInt();
    return new RandomData(id, timestamp, randomInt);
}

From source file:com.silverpeas.ical.StringUtils.java

static char[] decodeToArray(byte[] bytes, Charset encoding) {
    if (CharEncoding.US_ASCII.equals(encoding.name())) {
        char[] array = new char[bytes.length];
        for (int i = 0; i < array.length; i++) {
            array[i] = (char) bytes[i];
        }//from  ww w . j a v a2  s  . co m
        return array;
    }
    try {
        CharBuffer buffer = encoding.newDecoder().decode(ByteBuffer.wrap(bytes));
        char[] array = new char[buffer.limit()];
        System.arraycopy(buffer.array(), 0, array, 0, array.length);
        return array;
    } catch (Exception nioException) {
        return (new String(bytes, encoding)).toCharArray();
    }
}

From source file:rx.apache.http.consumers.ResponseConsumerChunked.java

@Override
protected final void onContentReceived(final ContentDecoder decoder, final IOControl ioctrl)
        throws IOException {
    if (parentSubscription.isUnsubscribed()) {
        ioctrl.shutdown();/*from  ww  w.  j a  v a  2  s. c o  m*/
    }

    byte[] data;
    data = new byte[BUFFER_SIZE];

    final int bytesRead;
    bytesRead = decoder.read(ByteBuffer.wrap(data));

    if (bytesRead > 0) {
        if (bytesRead == data.length) {
            contentSubject.onNext(data);

        } else {
            byte[] subset;
            subset = new byte[bytesRead];
            System.arraycopy(data, 0, subset, 0, bytesRead);

            contentSubject.onNext(subset);

        }

    }

    if (decoder.isCompleted()) {
        contentSubject.onCompleted();
    }
}

From source file:net.sf.jml.message.p2p.MsnP2PMessage.java

@Override
protected void parseMessage(byte[] message) {
    ByteBuffer split = Charset.encode(JmlConstants.LINE_SEPARATOR + JmlConstants.LINE_SEPARATOR);
    int pos = ByteBufferUtils.indexOf(ByteBuffer.wrap(message), split);

    // header// w ww.j a v a 2  s  .co m
    String header = pos == -1 ? Charset.decode(message) : Charset.decode(message, 0, pos);
    headers.parseString(header);

    // binaryHeader
    pos += split.remaining();
    binaryHeader.put(message, pos, BINARY_HEADER_LEN);
    binaryHeader.flip();

    // body
    pos += BINARY_HEADER_LEN;
    parseP2PBody(ByteBuffer.wrap(message, pos, message.length - pos - BINARY_FOOTER_LEN));

    // binaryFoot
    binaryFooter.put(message, message.length - BINARY_FOOTER_LEN, BINARY_FOOTER_LEN);
    binaryFooter.flip();
}

From source file:com.rackspacecloud.blueflood.io.serializers.HistogramSerializationTest.java

@Test
public void testSerializationDeserializationVersion1() throws Exception {
    if (System.getProperty("GENERATE_HIST_SERIALIZATION") != null) {
        OutputStream os = new FileOutputStream(
                "src/test/resources/serializations/histogram_version_" + Constants.VERSION_1_HISTOGRAM + ".bin",
                false);/*from ww  w. j av a 2 s.c  om*/

        os.write(Base64.encodeBase64(HistogramSerializer.get().toByteBuffer(histogramRollup).array()));
        os.write("\n".getBytes());
        os.close();
    }

    Assert.assertTrue(new File("src/test/resources/serializations").exists());

    // ensure we can read historical serializations.
    int version = 0;
    int maxVersion = Constants.VERSION_1_HISTOGRAM;
    while (version <= maxVersion) {
        BufferedReader reader = new BufferedReader(
                new FileReader("src/test/resources/serializations/histogram_version_" + version + ".bin"));
        ByteBuffer bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
        HistogramRollup histogramRollupDes = HistogramSerializer.get().fromByteBuffer(bb);
        Assert.assertTrue(areHistogramsEqual(histogramRollup, histogramRollupDes));
        version++;
    }
}

From source file:com.tongbanjie.tarzan.rpc.protocol.RpcCommand.java

public static RpcCommand decode(final byte[] array) {
    ByteBuffer byteBuffer = ByteBuffer.wrap(array);
    return decode(byteBuffer);
}

From source file:de.brendamour.jpasskit.signing.PKPassTemplateInMemory.java

@Override
public Map<String, ByteBuffer> getAllFiles() throws IOException {
    Map<String, ByteBuffer> allFiles = new HashMap<>();
    for (Entry<String, InputStream> entry : files.entrySet()) {
        byte[] byteArray = IOUtils.toByteArray(entry.getValue());
        String filePath = entry.getKey();
        allFiles.put(filePath, ByteBuffer.wrap(byteArray));
    }/*ww w .  j  av a  2s  . c om*/
    return allFiles;
}