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.sebhoss.identifier.service.SuppliedIdentifiers.java

private String convertUuidToBase64(final UUID uuid) {
    final ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return removePadding(encoder.encodeToString(bb.array()));
}

From source file:it.uniroma2.sag.kelp.wordspace.Wordspace.java

private long md5Encode(String str) {
    try {//www .  ja  va 2 s  .  c  o m
        byte[] bytesOfMessage = str.getBytes("UTF-8");
        byte[] digest = wordEncoder.digest(bytesOfMessage);
        return ByteBuffer.wrap(digest).getLong();
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}

From source file:com.pinterest.terrapin.storage.HFileReaderTest.java

@BeforeClass
public static void setUp() throws Exception {
    int randomNum = (int) (Math.random() * Integer.MAX_VALUE);
    hfilePath = "/tmp/hfile-" + randomNum;
    Configuration conf = new Configuration();
    FileSystem fs = FileSystem.get(conf);
    keyValueMap = Maps.newHashMapWithExpectedSize(10000);
    errorKeys = Sets.newHashSetWithExpectedSize(2000);
    StoreFile.Writer writer = new StoreFile.WriterBuilder(conf, new CacheConfig(conf), fs, 4096)
            .withFilePath(new Path(hfilePath)).withCompression(Compression.Algorithm.NONE).build();
    // Add upto 10K values.
    for (int i = 0; i < 10000; i++) {
        byte[] key = String.format("%04d", i).getBytes();
        byte[] value = null;
        // Add a couple of empty values for testing and making sure we return them.
        if (i <= 1) {
            value = "".getBytes();
        } else {//from   ww  w .  j  a  v  a2s.  co  m
            value = ("v" + (i + 1)).getBytes();
        }
        KeyValue kv = new KeyValue(key, Bytes.toBytes("cf"), Bytes.toBytes(""), value);
        writer.append(kv);
        keyValueMap.put(ByteBuffer.wrap(key), ByteBuffer.wrap(value));
        if (i >= 4000 && i < 6000) {
            errorKeys.add(ByteBuffer.wrap(key));
        }
    }
    writer.close();
    hfileReader = new TestHFileReader(fs, hfilePath, new CacheConfig(conf),
            new ExecutorServiceFuturePool(Executors.newFixedThreadPool(1)), errorKeys);
}

From source file:com.taobao.common.tfs.impl.LocalKey.java

public void load(byte[] data) throws TfsException {
    rawData = ByteBuffer.wrap(data);
    loadHead();//www. j av a2s.c om
    if (data.length < segmentHead.getSegmentCount() * SegmentInfo.size() + SegmentHead.size()) {
        throw new TfsException("data length not enough to hold head recording segment count: " + data.length
                + " < " + segmentHead.getSegmentCount() * SegmentInfo.size() + SegmentHead.size());
    }

    loadSegment();
}

From source file:org.brekka.phalanx.core.services.impl.AbstractCryptoService.java

private InternalSecretKeyToken decodeSecretKey(byte[] encoded, UUID idOfData) {
    ByteBuffer buffer = ByteBuffer.wrap(encoded);
    byte[] marker = new byte[SK_MAGIC_MARKER.length];
    buffer.get(marker);/*from w  w w . java  2  s .  c o  m*/
    if (!Arrays.equals(SK_MAGIC_MARKER, marker)) {
        throw new PhalanxException(PhalanxErrorCode.CP213,
                "CryptoData item '%s' does not appear to contain a secret key", idOfData);
    }
    int profileId = buffer.getInt();
    byte[] keyId = new byte[16];
    buffer.get(keyId);
    UUID symCryptoDataId = toUUID(keyId);
    CryptoProfile cryptoProfile = cryptoProfileService.retrieveProfile(profileId);
    byte[] data = new byte[encoded.length - (SK_MAGIC_MARKER.length + 20)];
    buffer.get(data);

    SecretKey secretKey = phoenixSymmetric.toSecretKey(data, cryptoProfile);
    SymedCryptoData symedCryptoData = new SymedCryptoData();
    symedCryptoData.setId(symCryptoDataId);
    symedCryptoData.setProfile(profileId);
    return new InternalSecretKeyToken(secretKey, symedCryptoData);
}

From source file:io.gomint.server.network.packet.PacketLogin.java

@Override
public void deserialize(PacketBuffer buffer) {
    this.protocol = buffer.readInt();

    // Decompress inner data (i don't know why you compress inside of a Batched Packet but hey)
    byte[] compressed = new byte[buffer.readInt()];
    buffer.readBytes(compressed);/*from www  . ja  va 2 s. c  o m*/

    Inflater inflater = new Inflater();
    inflater.setInput(compressed);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    try {
        byte[] comBuffer = new byte[1024];
        while (!inflater.finished()) {
            int read = inflater.inflate(comBuffer);
            bout.write(comBuffer, 0, read);
        }
    } catch (DataFormatException e) {
        System.out.println("Failed to decompress batch packet" + e);
        return;
    }

    // More data please
    ByteBuffer byteBuffer = ByteBuffer.wrap(bout.toByteArray());
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    byte[] stringBuffer = new byte[byteBuffer.getInt()];
    byteBuffer.get(stringBuffer);

    // Decode the json stuff
    try {
        JSONObject jsonObject = (JSONObject) new JSONParser().parse(new String(stringBuffer));
        JSONArray chainArray = (JSONArray) jsonObject.get("chain");
        if (chainArray != null) {
            this.validationKey = parseBae64JSON((String) chainArray.get(chainArray.size() - 1)); // First key in chain is last response in chain #brainfuck :D
            for (Object chainObj : chainArray) {
                decodeBase64JSON((String) chainObj);
            }
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    // Skin comes next
    this.skin = new byte[byteBuffer.getInt()];
    byteBuffer.get(this.skin);
}

From source file:eu.scape_project.arc2warc.PayloadContent.java

public InputStream getPayloadContentAsInputStream() throws IOException {
    if (length >= buffer.length) {
        File tempDir = org.apache.commons.io.FileUtils.getTempDirectory();
        final File tmp = File.createTempFile(RandomStringUtils.randomAlphabetic(10), "tmp", tempDir);
        tmp.deleteOnExit();/*w  w  w  . j  av a2 s .co  m*/
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(tmp);
            copyAndCheck(outputStream);
        } finally {
            IOUtils.closeQuietly(outputStream);
        }
        return new FileInputStream(tmp);
    } else {
        final ByteBuffer wrap = ByteBuffer.wrap(buffer);
        wrap.clear();
        OutputStream outStream = StreamUtils.newOutputStream(wrap);
        copyAndCheck(outStream);
        wrap.flip();
        return StreamUtils.newInputStream(wrap);
    }
}

From source file:com.datamountaineer.streamreactor.connect.json.SimpleJsonConverterTest.java

@Test
public void bytesToJson() throws IOException {
    JsonNode converted = converter.fromConnectData(Schema.BYTES_SCHEMA, "test-string".getBytes());
    assertEquals(ByteBuffer.wrap("test-string".getBytes()), ByteBuffer.wrap(converted.binaryValue()));
}

From source file:com.intellectualcrafters.plot.uuid.UUIDFetcher.java

@SuppressWarnings("unused")
public static UUID fromBytes(final byte[] array) {
    if (array.length != 16) {
        throw new IllegalArgumentException("Illegal byte array length: " + array.length);
    }//from w  ww  .ja va2 s  .c  om
    final ByteBuffer byteBuffer = ByteBuffer.wrap(array);
    final long mostSignificant = byteBuffer.getLong();
    final long leastSignificant = byteBuffer.getLong();
    return new UUID(mostSignificant, leastSignificant);
}

From source file:joshelser.as2015.parser.AmazonReviewParser.java

/**
 * Compute the next review from the reader.
 * /* w  w w  .  j a v  a2s .  c  o  m*/
 * @return The next review or null if there is none
 */
AmazonReview getNextReview() {
    if (readerExhausted) {
        return null;
    }

    try {
        String line;
        AmazonReview nextReview = null;
        do {
            line = reader.readLine();
            if (null == line) {
                readerExhausted = true;
                return nextReview;
            }

            // Empty line is message separator
            if (StringUtils.isBlank(line)) {
                // If we have a review return it
                if (null != nextReview) {
                    return nextReview;
                }
                // otherwise, just try to read the next message
            } else {
                if (null == nextReview) {
                    nextReview = new AmazonReview();
                }
                int index = line.indexOf(':');
                if (-1 == index) {
                    throw new IllegalArgumentException("Cannot parse line '" + line + "'");
                }
                String key = StringUtils.strip(line.substring(0, index));
                String value = StringUtils.strip(line.substring(index + 1));

                index = key.indexOf('/');
                if (-1 == index) {
                    throw new IllegalArgumentException("Cannot parse key '" + key + "'");
                }
                AmazonReviewField field = new AmazonReviewField(key.substring(0, index),
                        key.substring(index + 1));
                nextReview.addReviewField(field, ByteBuffer.wrap(value.getBytes(StandardCharsets.UTF_8)));
            }
        } while (!readerExhausted);
        return nextReview;
    } catch (IOException e) {
        throw new RuntimeException("Failed to read file", e);
    }
}