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.nearinfinity.honeycomb.hbase.bulkload.FieldParser.java

private static ByteBuffer extractDate(String val, String dateFormat, String... parseFormats)
        throws ParseException {
    Date d = DateUtils.parseDateStrictly(val, parseFormats);
    SimpleDateFormat format = new SimpleDateFormat(dateFormat);
    return ByteBuffer.wrap(format.format(d).getBytes());
}

From source file:com.thoughtworks.go.server.websocket.ConsoleLogSenderTest.java

@Test
public void shouldSendConsoleLog() throws Exception {
    String expected = "Expected output for this test";
    File console = makeConsoleFile(expected);

    when(jobInstanceDao.isJobCompleted(jobIdentifier)).thenReturn(true);
    when(consoleService.doesLogExist(jobIdentifier)).thenReturn(true);
    when(consoleService.getStreamer(0L, jobIdentifier)).thenReturn(new ConsoleStreamer(console.toPath(), 0L));
    when(consoleService.getStreamer(1L, jobIdentifier)).thenReturn(new ConsoleStreamer(console.toPath(), 1L));

    consoleLogSender.process(socket, jobIdentifier, 0L);

    verify(socket)/*  w  w w . j  av a2s .  co m*/
            .send(ByteBuffer.wrap(consoleLogSender.maybeGzipIfLargeEnough((expected + '\n').getBytes(UTF_8))));
}

From source file:org.mcplissken.repository.models.content.Content.java

public void writeAsImage(File result) throws IOException {

    BufferedImage originalImage = ImageIO.read(result);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    ImageIO.write(originalImage, getExtension(), baos);

    baos.flush();/*w w  w.  ja  va  2s.c  om*/

    byte[] imageInByte = baos.toByteArray();

    data = ByteBuffer.wrap(imageInByte);

    baos.close();
}

From source file:tachyon.master.JsonObject.java

/** Deserializes a list of base64-encoded Strings as a list of ByteBuffers. */
public List<ByteBuffer> getByteBufferList(String name) {
    List<String> byteStrings = get(name, new TypeReference<List<String>>() {
    });/* w  ww.  j  a v a  2  s. co  m*/
    if (byteStrings == null) {
        return null;
    }

    List<ByteBuffer> buffers = Lists.newArrayListWithCapacity(byteStrings.size());
    for (String byteString : byteStrings) {
        buffers.add(ByteBuffer.wrap(Base64.decodeBase64(byteString)));
    }
    return buffers;
}

From source file:com.easemob.dataexport.utils.JsonUtils.java

public static ByteBuffer toByteBuffer(Object obj) {
    if (obj == null) {
        return null;
    }/*from www .  j ava  2s.c o  m*/

    byte[] bytes = null;
    try {
        bytes = smileMapper.writeValueAsBytes(obj);
    } catch (Exception e) {
        LOG.error("Error getting SMILE bytes", e);
    }
    if (bytes != null) {
        return ByteBuffer.wrap(bytes);
    }
    return null;
}

From source file:com.offbynull.portmapper.pcp.PcpOption.java

/**
 * Constructs a {@link PcpOption} object by parsing a buffer.
 * @param buffer buffer containing PCP option data
 * @throws NullPointerException if any argument is {@code null}
 * @throws BufferUnderflowException if not enough data is available in {@code buffer}
 *//*from  w  w  w  .  ja  v  a2  s  .  co  m*/
public PcpOption(ByteBuffer buffer) {
    Validate.notNull(buffer);

    code = buffer.get() & 0xFF;

    buffer.get(); // skip over reserved

    length = buffer.getShort() & 0xFFFF;

    byte[] dataArr = new byte[length];
    buffer.get(dataArr);

    data = ByteBuffer.wrap(dataArr).asReadOnlyBuffer();

    // skip over padding
    int remainder = length % 4;
    for (int i = 0; i < remainder; i++) {
        buffer.get();
    }
}

From source file:com.rackspacecloud.blueflood.io.SerializationTest.java

@Test(expected = SerializationException.class)
public void testVersion2FullDeserializeBadType() throws Throwable {
    byte[] buf = new byte[] { 0, 2 };
    try {//from  w  w  w. j  ava  2  s. c  om
        NumericSerializer.get(Granularity.FULL).fromByteBuffer(ByteBuffer.wrap(buf));
    } catch (RuntimeException e) {
        throw e.getCause();
    }
}

From source file:$.DeviceTypeServiceImpl.java

private static String shortUUID() {
        UUID uuid = UUID.randomUUID();
        long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
        return Long.toString(l, Character.MAX_RADIX);
    }//from   w w  w  . jav a 2 s  .  c  om

From source file:io.confluent.kafkarest.converters.AvroConverter.java

/**
 * Converts Avro data (including primitive types) to their equivalent JsonNode representation.
 *
 * @param value the value to convert//from   ww w .  j a  v a2 s  .c o m
 * @return an object containing the root JsonNode representing the converted object and the size
 *     in bytes of the data when serialized
 */
public static JsonNodeAndSize toJson(Object value) {
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Schema schema = getSchema(value);
        JsonEncoder encoder = encoderFactory.jsonEncoder(schema, out);
        DatumWriter<Object> writer = new GenericDatumWriter<Object>(schema);
        // Some types require wrapping/conversion
        Object wrappedValue = value;
        if (value instanceof byte[]) {
            wrappedValue = ByteBuffer.wrap((byte[]) value);
        }
        writer.write(wrappedValue, encoder);
        encoder.flush();
        byte[] bytes = out.toByteArray();
        out.close();
        return new JsonNodeAndSize(jsonMapper.readTree(bytes), bytes.length);
    } catch (IOException e) {
        // These can be generated by Avro's JSON encoder, the output stream operations, and the
        // Jackson ObjectMapper.readTree() call.
        log.error("Jackson failed to deserialize JSON generated by Avro's JSON encoder: ", e);
        throw new ConversionException("Failed to convert Avro to JSON: " + e.getMessage());
    } catch (RuntimeException e) {
        // Catch-all since it's possible for, e.g., Avro to throw many different RuntimeExceptions
        log.error("Unexpected exception convertion Avro to JSON: ", e);
        throw new ConversionException("Failed to convert Avro to JSON: " + e.getMessage());
    }
}

From source file:ee.ioc.phon.android.speak.Utils.java

/**
 * <p>Returns a bitmap that visualizes the given waveform (byte array),
 * i.e. a sequence of 16-bit integers.</p>
 *
 * TODO: show to high/low points in other color
 * TODO: show end pause data with another color
 *///  w  ww.j  a v  a2  s . c  o m
public static Bitmap drawWaveform(byte[] waveBuffer, int w, int h, int start, int end) {
    final Bitmap b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
    final Canvas c = new Canvas(b);
    final Paint paint = new Paint();
    paint.setColor(0xFFFFFFFF); // 0xRRGGBBAA
    paint.setAntiAlias(true);
    paint.setStrokeWidth(0);

    final Paint redPaint = new Paint();
    redPaint.setColor(0xFF000080);
    redPaint.setAntiAlias(true);
    redPaint.setStrokeWidth(0);

    final ShortBuffer buf = ByteBuffer.wrap(waveBuffer).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
    buf.position(0);

    final int numSamples = waveBuffer.length / 2;
    //final int delay = (SAMPLING_RATE * 100 / 1000);
    final int delay = 0;
    int endIndex = end / 2 + delay;
    if (end == 0 || endIndex >= numSamples) {
        endIndex = numSamples;
    }
    int index = start / 2 - delay;
    if (index < 0) {
        index = 0;
    }
    final int size = endIndex - index;
    int numSamplePerPixel = 32;
    int delta = size / (numSamplePerPixel * w);
    if (delta == 0) {
        numSamplePerPixel = size / w;
        delta = 1;
    }

    final float scale = 3.5f / 65536.0f;
    // do one less column to make sure we won't read past
    // the buffer.
    try {
        for (int i = 0; i < w - 1; i++) {
            final float x = i;
            for (int j = 0; j < numSamplePerPixel; j++) {
                final short s = buf.get(index);
                final float y = (h / 2) - (s * h * scale);
                if (s > Short.MAX_VALUE - 10 || s < Short.MIN_VALUE + 10) {
                    // TODO: make it work
                    c.drawPoint(x, y, redPaint);
                } else {
                    c.drawPoint(x, y, paint);
                }
                index += delta;
            }
        }
    } catch (IndexOutOfBoundsException e) {
        // this can happen, but we don't care
    }

    return b;
}