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.knewton.mapreduce.util.RandomStudentEventGenerator.java

/**
 * Helper method for generating decorated increasing student ids. Used by
 * {@link WriteSampleSSTable} for writing a sorted SSTable.
 *
 * @return A list of byte buffers with student IDs
 */// w  ww  .  j av a 2  s  . c  o m
public static List<ByteBuffer> getStudentIds(int numberOfStudents) {
    long studentId = 1000000L;
    List<ByteBuffer> studentIds = Lists.newArrayListWithCapacity(numberOfStudents);

    for (int i = 0; i < numberOfStudents; i++) {
        ByteBuffer bb = ByteBuffer.wrap(new byte[8]);
        bb.putLong(studentId++);
        bb.rewind();
        studentIds.add(bb);
    }

    Collections.sort(studentIds, new Comparator<ByteBuffer>() {
        @Override
        public int compare(ByteBuffer o1, ByteBuffer o2) {
            DecoratedKey dk1 = StorageService.getPartitioner().decorateKey(o1);
            DecoratedKey dk2 = StorageService.getPartitioner().decorateKey(o2);
            return dk1.compareTo(dk2);
        }
    });

    return studentIds;
}

From source file:com.inmobi.messaging.consumer.databus.mapred.TestDatabusBytesWritableInputFormat.java

/**
 * read the the given input split./*from  w ww .ja v  a  2 s.co  m*/
 * @return List : List of read messages
 */
private List<Message> readSplit(DatabusBytesWritableInputFormat format, InputSplit split, JobConf job,
        Reporter reporter) throws IOException {
    List<Message> result = new ArrayList<Message>();
    RecordReader<LongWritable, BytesWritable> reader = format.getRecordReader(split, job, reporter);
    LongWritable key = ((DatabusBytesWritableRecordReader) reader).createKey();
    BytesWritable value = ((DatabusBytesWritableRecordReader) reader).createValue();

    while (((DatabusBytesWritableRecordReader) reader).next(key, value)) {
        byte[] data = new byte[value.getLength()];
        System.arraycopy(value.getBytes(), 0, data, 0, value.getLength());
        result.add(new Message(ByteBuffer.wrap(data)));
        value = (BytesWritable) ((DatabusBytesWritableRecordReader) reader).createValue();
    }
    reader.close();
    return result;
}

From source file:de.zalando.spring.cloud.config.aws.kms.KmsTextEncryptor.java

@Override
public String decrypt(final String encryptedText) {
    if (encryptedText == null || encryptedText.isEmpty()) {
        return EMPTY_STRING;
    } else {/*from  ww  w.j a v a2  s  . co  m*/

        // Assuming the encryptedText is encoded in Base64
        final ByteBuffer encryptedBytes = ByteBuffer.wrap(Base64.decode(encryptedText.getBytes()));

        final DecryptRequest decryptRequest = new DecryptRequest().withCiphertextBlob(encryptedBytes);

        return extractString(kms.decrypt(decryptRequest).getPlaintext());
    }
}

From source file:io.druid.segment.data.VSizeColumnarIntsSerializerTest.java

private void checkSerializedSizeAndData() throws Exception {
    int maxValue = vals.length == 0 ? 0 : Ints.max(vals);
    VSizeColumnarIntsSerializer writer = new VSizeColumnarIntsSerializer(segmentWriteOutMedium, maxValue);

    VSizeColumnarInts intsFromList = VSizeColumnarInts.fromIndexedInts(new ArrayBasedIndexedInts(vals),
            maxValue);/*from w  ww. jav  a 2s .c o m*/
    writer.open();
    for (int val : vals) {
        writer.addValue(val);
    }
    long writtenLength = writer.getSerializedSize();
    WriteOutBytes writeOutBytes = segmentWriteOutMedium.makeWriteOutBytes();
    writer.writeTo(writeOutBytes, null);

    assertEquals(writtenLength, intsFromList.getSerializedSize());

    // read from ByteBuffer and check values
    VSizeColumnarInts intsFromByteBuffer = VSizeColumnarInts
            .readFromByteBuffer(ByteBuffer.wrap(IOUtils.toByteArray(writeOutBytes.asInputStream())));
    assertEquals(vals.length, intsFromByteBuffer.size());
    for (int i = 0; i < vals.length; ++i) {
        assertEquals(vals[i], intsFromByteBuffer.get(i));
    }
}

From source file:com.joyent.manta.http.entity.ExposedStringEntity.java

@Override
public ByteBuffer getBackingBuffer() {
    return ByteBuffer.wrap(super.content);
}

From source file:com.capitalone.dashboard.util.ClientUtil.java

/**
 * Utility method used to sanitize / canonicalize a String-based response
 * artifact from a source system. This will return a valid UTF-8 strings, or
 * a "" (blank) response for any of the following cases:
 * "NULL";"Null";"null";null;""/*from  w w w . java 2 s .  c  o m*/
 * 
 * @param inNativeRs
 *            The string response artifact retrieved from the source system
 *            to be sanitized
 * @return A UTF-8 sanitized response
 */
public String sanitizeResponse(Object inNativeRs) {
    if (inNativeRs == null) {
        return "";
    }
    String nativeRs = inNativeRs.toString();

    byte[] utf8Bytes;
    CharsetDecoder cs = StandardCharsets.UTF_8.newDecoder();
    try {
        if ("null".equalsIgnoreCase(nativeRs)) {
            return "";
        }
        if (nativeRs.isEmpty()) {
            return "";
        }
        utf8Bytes = nativeRs.getBytes(StandardCharsets.UTF_8);
        cs.decode(ByteBuffer.wrap(utf8Bytes));
        return new String(utf8Bytes, StandardCharsets.UTF_8);
    } catch (Exception e) {
        return "[INVALID NON UTF-8 ENCODING]";
    }
}

From source file:com.rackspacecloud.blueflood.io.serializers.astyanax.TimerSerializationTest.java

@Test
public void testV2RoundTrip() throws IOException {
    // build up a Timer
    BluefloodTimerRollup r0 = new BluefloodTimerRollup().withSum(Double.valueOf(42)).withCountPS(23.32d)
            .withAverage(56).withVariance(853.3245d).withMinValue(2).withMaxValue(987).withCount(345);
    r0.setPercentile("foo", 741.32d);
    r0.setPercentile("bar", 0.0323d);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    baos.write(Base64.encodeBase64(Serializers.timerRollupInstance.toByteBuffer(r0).array()));
    baos.write("\n".getBytes());
    baos.close();/*from   w  w w. j  ava 2 s.  co  m*/

    BufferedReader reader = new BufferedReader(
            new InputStreamReader(new ByteArrayInputStream(baos.toByteArray())));
    ByteBuffer bb = ByteBuffer.wrap(Base64.decodeBase64(reader.readLine().getBytes()));
    BluefloodTimerRollup r1 = Serializers.timerRollupInstance.fromByteBuffer(bb);
    Assert.assertEquals(r0, r1);
}

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

@Override
public ByteBuffer testBinary(ByteBuffer name) throws TException {
    try {/*from   ww  w  . j ava2  s .  com*/

        String result = new String(name.array(), name.position(), name.limit() - name.position(), "UTF-8");
        result = "Hello " + result;
        return ByteBuffer.wrap(result.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new TException(e);
    }
}

From source file:com.bendb.thrifty.testing.ThriftTestHandler.java

@Override
public ByteBuffer testBinary(ByteBuffer thing) throws TException {
    int count = thing.remaining();
    byte[] data = new byte[count];
    thing.get(data);//from  w  w  w  . j ava2  s.  c om

    out.printf("testBinary(\"%s\")\n", Hex.encodeHexString(data));

    return ByteBuffer.wrap(data);
}