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.github.ambry.commons.BlobId.java

/**
 * Re-constructs existing blobId by deserializing from BlobId "string"
 *
 * @param id of Blob as output by BlobId.getID()
 * @param clusterMap of the cluster that the blob id belongs to
 * @throws IOException//from w  w w  .j a  v  a2 s  .  c  o  m
 */
public BlobId(String id, ClusterMap clusterMap) throws IOException {
    this(new DataInputStream(new ByteBufferInputStream(ByteBuffer.wrap(Base64.decodeBase64(id)))), clusterMap);
}

From source file:StreamUtility.java

/**
 * Converts little endian bytes to a long
 * @param value byte array to read//www  . j ava  2  s .  com
 * @return long value of the byte array
 */
public static long littleEndianToLong(byte[] value) {
    return ByteBuffer.wrap(value).order(ByteOrder.LITTLE_ENDIAN).getLong();
}

From source file:com.tc.simple.apn.factories.FeedbackFactory.java

public List<Feedback> createFeedback(InputStream in) {
    List<Feedback> list = new ArrayList<Feedback>();
    try {/* ww w .j a va2 s .co m*/

        byte[] byteMe = IOUtils.toByteArray(in);

        int startRange = 0;

        int endRange = 38; //38 byte chunks per feedback item.

        while (startRange < byteMe.length) {

            //init the value object to hold the feedback data.
            Feedback feedback = new Feedback();

            //build the item based on range
            byte[] item = Arrays.copyOfRange(byteMe, startRange, endRange);//38 byte chunks.

            byte[] date = Arrays.copyOfRange(item, 0, 4);

            byte[] size = Arrays.copyOfRange(item, 4, 6);

            byte[] token = Arrays.copyOfRange(item, 6, item.length);

            ByteBuffer dateWrap = ByteBuffer.wrap(date);

            ByteBuffer javaSize = ByteBuffer.wrap(size);

            //set the date (returns number of seconds from unix epoch date)
            feedback.setDate(new Date(dateWrap.getInt() * 1000L));

            //get the size of the token (should always be 32)
            feedback.setSize(javaSize.getShort());

            //drop in our encoded token (will be used as our key for marking the user's token doc as failed)
            feedback.setToken(String.valueOf(Hex.encodeHex(token)));

            //add it to our collection
            list.add(feedback);

            //increment the start range
            startRange = startRange + 38;

            //increment the end range.
            endRange = endRange + 38;

        }

    } catch (Exception e) {
        logger.log(Level.SEVERE, null, e);

    }

    return list;

}

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

@Override
public Map<String, ByteBuffer> getAllFiles() throws IOException {
    Map<String, ByteBuffer> allFiles = new HashMap<>();
    for (File file : new File(pathToTemplateDirectory).listFiles()) {
        byte[] byteArray = IOUtils.toByteArray(new FileInputStream(file));
        String filePath = file.getAbsolutePath().replace(pathToTemplateDirectory, "");
        allFiles.put(filePath, ByteBuffer.wrap(byteArray));
    }/* w  ww  .  ja  v a2 s.  co  m*/
    return allFiles;
}

From source file:de.dentrassi.pm.npm.aspect.NpmExtractor.java

private void perform(final Path file, final Map<String, String> metadata) throws IOException {
    try (final GZIPInputStream gis = new GZIPInputStream(new FileInputStream(file.toFile()));
            final TarArchiveInputStream tis = new TarArchiveInputStream(gis)) {
        TarArchiveEntry entry;/*from  w  w  w.j a  v  a  2s . co m*/
        while ((entry = tis.getNextTarEntry()) != null) {
            if (entry.getName().equals("package/package.json")) {
                final byte[] data = new byte[(int) entry.getSize()];
                ByteStreams.read(tis, data, 0, data.length);

                final String str = StandardCharsets.UTF_8.decode(ByteBuffer.wrap(data)).toString();

                try {
                    // test parse
                    new JsonParser().parse(str);
                    // store
                    metadata.put("package.json", str);
                } catch (final JsonParseException e) {
                    // ignore
                }

                break; // stop parsing the archive
            }
        }

    }
}

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

@Test
public void modificationTimes() throws Exception {

    // Create a dummy ZIP file.
    ByteArrayOutputStream bytesOutputStream = new ByteArrayOutputStream();
    try (ZipOutputStream out = new ZipOutputStream(bytesOutputStream)) {
        ZipEntry entry = new ZipEntry("file1");
        byte[] data = "data1".getBytes(Charsets.UTF_8);
        entry.setSize(data.length);//from  w w w.j  a va 2 s  .  c  o m
        out.putNextEntry(entry);
        out.write(data);
        out.closeEntry();

        entry = new ZipEntry("file2");
        data = "data2".getBytes(Charsets.UTF_8);
        entry.setSize(data.length);
        out.putNextEntry(entry);
        out.write(data);
        out.closeEntry();
    }

    byte[] bytes = bytesOutputStream.toByteArray();
    // Execute the zip scrubber step.
    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:net.sf.yal10n.analyzer.ExploratoryEncodingTest.java

/**
 * Test how malformed input is reported.
 * @throws Exception any error/* w  ww .jav a  2  s.c o m*/
 */
@Test(expected = MalformedInputException.class)
public void testMalformedEncoding() throws Exception {
    ByteBuffer buffer = ByteBuffer.wrap(data);

    utf8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT)
            .decode(buffer);
}

From source file:com.cloudera.branchreduce.impl.thrift.VassalProxy.java

@Override
public synchronized void startTasks(List<T> tasks, G globalState) {
    StartTasksRequest req = new StartTasksRequest();
    req.setGlobalState(WritableUtils.toByteArray(globalState));
    for (T task : tasks) {
        req.addToTasks(ByteBuffer.wrap(WritableUtils.toByteArray(task)));
    }//w  ww.j  a  v  a2 s.c om
    try {
        client.startTasks(req);
    } catch (TException e) {
        LOG.error("Transport exception starting tasks", e);
    }
}

From source file:ch.ledcom.jpreseed.cli.JPreseed.java

public final void create(JPreseedArguments arguments) throws IOException {
    try (InputImage image = getSourceImage(arguments);
            GZIPOutputStream newImage = new GZIPOutputStream(
                    Files.newOutputStream(arguments.getTargetImage()))) {
        ByteBuffer sysConfigCfg = ByteBuffer.wrap(Files.readAllBytes(arguments.getSysConfigFile()));
        usbCreator.create(image.getContent(), newImage, sysConfigCfg, arguments.getPreseeds());
    }/*from   w ww .  ja v  a 2s .c  om*/
}

From source file:com.knewton.mapreduce.SSTableColumnMapperTest.java

/**
 * Test to see if cassandra columns go through the mapper correctly.
 * //from  www .  j ava  2 s  . c  o m
 * @throws IOException
 * @throws InterruptedException
 */
@Test
public void testMap() throws IOException, InterruptedException {

    ByteBuffer key = ByteBuffer.wrap(keyVal.getBytes());
    IColumn column = new Column(ByteBuffer.wrap(columnNameVal.getBytes()),
            ByteBuffer.wrap(columnValue.getBytes()));
    concreteMapper.map(key, column, null);
    // Key
    byte[] verifyByteArr = new byte[keyVal.length()];
    concreteMapper.getCurrentKey().get(verifyByteArr);
    assertEquals(keyVal, new String(verifyByteArr));
    // Column name
    verifyByteArr = new byte[columnNameVal.length()];
    concreteMapper.getCurrentColumn().name().get(verifyByteArr);
    assertEquals(columnNameVal, new String(verifyByteArr));
    // Column value
    verifyByteArr = new byte[columnValue.length()];
    concreteMapper.getCurrentColumn().value().get(verifyByteArr);
    assertEquals(columnValue, new String(verifyByteArr));
    concreteMapper.clearKeyVal();
}