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.amazonaws.mobileconnectors.kinesis.kinesisrecorder.internal.JSONRecordAdapter.java

/**
 * @param source The JSONObject that was created and stored via translateFromRecord
 * @return The corresponding//from ww w . j  av  a 2  s.co  m
 */
public PutRecordRequest translateToRecord(JSONObject source) {

    PutRecordRequest putRequest = new PutRecordRequest();
    try {
        putRequest.withData(ByteBuffer.wrap(Base64.decode(source.getString(DATA_FIELD_KEY), Base64.DEFAULT)));
        putRequest.withPartitionKey(source.getString(PARTITION_KEY_FIELD));
        putRequest.withStreamName(source.getString(STREAM_NAME_FIELD));
        if (source.has(EXPLICIT_HASH_FIELD)) {
            putRequest.withExplicitHashKey(source.getString(EXPLICIT_HASH_FIELD));
        }
        if (source.has(SEQUENCE_NUMBER_FIELD)) {
            putRequest.withSequenceNumberForOrdering(source.getString(SEQUENCE_NUMBER_FIELD));
        }

        return putRequest;

    } catch (JSONException e) {
        logger.e("Error creating stored request from representation on disk, ignoring request", e);
        return null;
    }

}

From source file:net.phoenix.thrift.hello.ThreadedSelectorTest.java

@Test
public void testBinary() throws Exception {
    LOG.info("Client starting....");
    String name = "Hello";
    // TTransport transport = new TNonblockingSocket("localhost", 9804);
    TTransport transport = new TFramedTransport(new TSocket("localhost", 9804));
    transport.open();//w  w w .j  a  va2  s.  co  m
    // TTransport transport = new TTransport(socket);
    TProtocol protocol = new TBinaryProtocol(transport);
    HelloService.Client client = new HelloService.Client(protocol);
    try {

        ByteBuffer buffer = client.testBinary(ByteBuffer.wrap(name.getBytes("UTF-8")));
        assertEquals(new String(buffer.array(), buffer.position(), buffer.limit() - buffer.position(), "UTF-8"),
                "Hello " + name);
        // System.out.println(message);
    } finally {
        transport.close();
    }
}

From source file:com.facebook.buck.util.zip.ZipScrubberTest.java

@Test
public void modificationTimesExceedShort() throws Exception {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] data = "data1".getBytes(Charsets.UTF_8);
    try (ZipOutputStream out = new ZipOutputStream(byteArrayOutputStream)) {
        for (long i = 0; i < Short.MAX_VALUE + 1; i++) {
            ZipEntry entry = new ZipEntry("file" + i);
            entry.setSize(data.length);/* ww w . java 2s.  c  om*/
            out.putNextEntry(entry);
            out.write(data);
            out.closeEntry();
        }
    }

    byte[] bytes = byteArrayOutputStream.toByteArray();
    ZipScrubber.scrubZipBuffer(bytes.length, ByteBuffer.wrap(bytes));

    // Iterate over each of the entries, expecting to see all zeros in the time fields.
    Date dosEpoch = new Date(ZipUtil.dosToJavaTime(ZipConstants.DOS_FAKE_TIME));
    try (ZipInputStream is = new ZipInputStream(new ByteArrayInputStream(bytes))) {
        for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
            assertThat(entry.getName(), new Date(entry.getTime()), Matchers.equalTo(dosEpoch));
        }
    }
}

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

private static int getServerID() {
    byte[] serverId = null;

    try {//from   ww  w . j  a va2  s  .co m
        serverId = getOpenShiftGearUUID();
    } catch (Exception e) {
        logger.info("Not on an OPENSHIFT machine, acquiring MOCK UUID");
        try {
            serverId = getDefaultServerId();
        } catch (DecoderException e1) {
            e1.printStackTrace();
            logger.info("Error acquiring valid UUID");
        }
    }

    Preconditions.checkNotNull(serverId);
    return ByteBuffer.wrap(serverId).getInt();
}

From source file:com.cnaude.mutemanager.UUIDFetcher.java

public static byte[] toBytes(UUID uuid) {
    ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[16]);
    byteBuffer.putLong(uuid.getMostSignificantBits());
    byteBuffer.putLong(uuid.getLeastSignificantBits());
    return byteBuffer.array();
}

From source file:com.spectralogic.ds3client.helpers.FileObjectPutter_Test.java

@Test
public void testRegularFile() throws IOException {
    final Path tempDir = Files.createTempDirectory("ds3_file_object_putter_");
    final Path tempPath = Files.createTempFile(tempDir, "temp_", ".txt");

    try {/*from   w ww .j ava 2 s  .  c  o m*/
        try (final SeekableByteChannel channel = Files.newByteChannel(tempPath, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(testData));
        }

        getFileWithPutter(tempDir, tempPath);
    } finally {
        Files.deleteIfExists(tempPath);
        Files.deleteIfExists(tempDir);
    }
}

From source file:io.druid.query.aggregation.HyperloglogAggregatorFactory.java

@Override
public Object deserialize(Object object) {
    log.debug("class name: [%s]:value [%s]", object.getClass().getName(), object);

    final String k = (String) object;
    final byte[] ibmapByte = Base64.decodeBase64(k);

    final ByteBuffer buffer = ByteBuffer.wrap(ibmapByte);
    final int keylength = buffer.getInt();
    final int valuelength = buffer.getInt();

    TIntByteHashMap newIbMap;//from   w ww.  j  av a  2  s.c om

    if (keylength == 0) {
        newIbMap = new TIntByteHashMap();
    } else {
        final int[] keys = new int[keylength];
        final byte[] values = new byte[valuelength];

        for (int i = 0; i < keylength; i++) {
            keys[i] = buffer.getInt();
        }
        buffer.get(values);

        newIbMap = new TIntByteHashMap(keys, values);
    }

    return newIbMap;
}

From source file:com.inmobi.messaging.util.AuditUtil.java

public static long getTimestamp(byte[] msg) {
    if (isValidHeaders(msg)) {
        ByteBuffer buffer = ByteBuffer.wrap(msg);
        return buffer.getLong(POSITION_OF_TIMESTAMP);
    } else/*from   www . j av a 2 s  .  co  m*/
        return -1;
}

From source file:gobblin.tunnel.TunnelTest.java

@Test
public void mustHandleClientDisconnectingWithoutClosingTunnel() throws Exception {
    mockExample();//w  ww  .  j a v  a2  s  .  c om
    Tunnel tunnel = Tunnel.build("example.org", 80, "localhost", PORT);

    try {
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

        client.connect(new InetSocketAddress("localhost", tunnelPort));
        client.write(ByteBuffer
                .wrap("GET / HTTP/1.1%nUser-Agent: GobblinTunnel%nConnection:keep - alive %n%n".getBytes()));
        client.close();

        assertNotNull(fetchContent(tunnelPort));
    } finally {
        tunnel.close();
    }
}

From source file:com.linkedin.pinot.core.common.datatable.DataTableImplV2.java

/**
 * Construct data table with results. (Server side)
 *///from www .jav  a  2s . c  om
public DataTableImplV2(int numRows, @Nonnull DataSchema dataSchema,
        @Nonnull Map<String, Map<Integer, String>> dictionaryMap, @Nonnull byte[] fixedSizeDataBytes,
        @Nonnull byte[] variableSizeDataBytes) {
    _numRows = numRows;
    _numColumns = dataSchema.size();
    _dataSchema = dataSchema;
    _columnOffsets = new int[_numColumns];
    _rowSizeInBytes = DataTableUtils.computeColumnOffsets(dataSchema, _columnOffsets);
    _dictionaryMap = dictionaryMap;
    _fixedSizeDataBytes = fixedSizeDataBytes;
    _fixedSizeData = ByteBuffer.wrap(fixedSizeDataBytes);
    _variableSizeDataBytes = variableSizeDataBytes;
    _variableSizeData = ByteBuffer.wrap(variableSizeDataBytes);
    _metadata = new HashMap<>();
}