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.woodcomputing.bobbin.format.JEFFormat.java

@Override
public Design load(File file) {

    byte[] bytes = null;
    try (InputStream is = new FileInputStream(file)) {
        bytes = IOUtils.toByteArray(is);
    } catch (IOException ex) {
        log.catching(ex);//from  www.ja  v a2s . c  om
    }
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    JEF jef = new JEF();
    jef.setFirstStitchLocation(bb.getInt(0));
    log.debug("First Stitch Location: {}", jef.getFirstStitchLocation());
    jef.setThreadChangeCount(bb.getInt(24));
    log.debug("Threads Changes: {}", jef.getThreadChangeCount());
    jef.setHoop(Hoop.id2Hoop(bb.getInt(32)));
    log.debug("Hoop: {}", jef.getHoop());
    jef.setStitchCount(bb.getInt(28));
    log.debug("Stitch Count: {}", jef.getStitchCount());

    bb.position(116);
    JEFColor[] colors = new JEFColor[jef.getThreadChangeCount()];
    for (int i = 0; i < jef.getThreadChangeCount(); i++) {
        colors[i] = jefColorMap.get(bb.getInt());
    }
    jef.setThreadColors(colors);
    for (int i = 0; i < jef.getThreadChangeCount(); i++) {
        log.debug("ThreadType{}: {}", i, bb.getInt());
    }

    int dx = 0;
    int dy = 0;
    int cx = 0;
    int cy = 0;
    int nx = 0;
    int ny = 0;

    int change = 1;
    int stitches = 0;
    boolean isMove = false;
    bb.position(jef.getFirstStitchLocation());
    JEFColor color = jef.getThreadColors()[change - 1];
    Design design = new Design();
    StitchGroup stitchGroup = new StitchGroup();
    stitchGroup.setColor(color.getRgb());

    for (int stitch = 1; stitch < jef.getStitchCount(); stitch++) {
        dx = bb.get();
        dy = bb.get();
        if (dx == -128) {
            switch (dy) {
            case 1:
                log.debug("change: {}", bb.position());
                change++;
                color = jef.getThreadColors()[change - 1];
                design.getStitchGroups().add(stitchGroup);
                stitchGroup = new StitchGroup();
                stitchGroup.setColor(color.getRgb());
                //                        bb.get();
                //                        bb.get();
                continue;
            case 2:
                //                        log.debug("move");
                isMove = true;
                break;
            case 16:
                log.debug("last");
                isMove = true;
                break;
            }
        } else {
            nx = cx + dx;
            ny = cy + dy;
            if (isMove) {
                isMove = false;
            }
            //                } else {
            //                    log.debug("stitch");
            stitches++;
            Stitch designStitch = new Stitch(cx, -cy, nx, -ny);
            stitchGroup.getStitches().add(designStitch);
            //                }
            cx = nx;
            cy = ny;
        }
    }
    log.debug("Changes: {} Stitches {} End: {}", change, stitches, bb.position());
    return design;
}

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

@Test(expected = UnexpectedStringSerializationException.class)
public void testStringFullSerializationShouldFail() throws Throwable {
    ByteArrayOutputStream baos = serializeString(TEST_STRING);
    ByteBuffer byteBuffer = ByteBuffer.wrap(baos.toByteArray());
    try {/*from   w  w w.j a v  a2s  . c  o  m*/
        Serializers.serializerFor(Object.class).fromByteBuffer(byteBuffer);
    } catch (RuntimeException re) {
        throw re.getCause();
    }
}

From source file:com.navercorp.pinpoint.common.server.bo.SpanFactoryAssert.java

public void assertSpan(TSpan tSpan, SpanBo spanBo) {
    Assert.assertEquals(tSpan.getAgentId(), spanBo.getAgentId());
    Assert.assertEquals(tSpan.getApplicationName(), spanBo.getApplicationId());
    Assert.assertEquals(tSpan.getAgentStartTime(), spanBo.getAgentStartTime());

    TransactionId transactionId = spanBo.getTransactionId();
    ByteBuffer byteBuffer = TransactionIdUtils.formatByteBuffer(transactionId.getAgentId(),
            transactionId.getAgentStartTime(), transactionId.getTransactionSequence());
    Assert.assertEquals(ByteBuffer.wrap(tSpan.getTransactionId()), byteBuffer);

    Assert.assertEquals(tSpan.getSpanId(), spanBo.getSpanId());
    Assert.assertEquals(tSpan.getParentSpanId(), spanBo.getParentSpanId());
    Assert.assertEquals(tSpan.getStartTime(), spanBo.getStartTime());
    Assert.assertEquals(tSpan.getElapsed(), spanBo.getElapsed());
    Assert.assertEquals(tSpan.getElapsed(), spanBo.getElapsed());
    Assert.assertEquals(tSpan.getRpc(), spanBo.getRpc());

    Assert.assertEquals(tSpan.getServiceType(), spanBo.getServiceType());
    Assert.assertEquals(tSpan.getEndPoint(), spanBo.getEndPoint());
    Assert.assertEquals(tSpan.getRemoteAddr(), spanBo.getRemoteAddr());

    assertAnnotation(tSpan.getAnnotations(), spanBo.getAnnotationBoList());

    Assert.assertEquals(tSpan.getFlag(), spanBo.getFlag());
    Assert.assertEquals(tSpan.getErr(), spanBo.getErrCode());

    Assert.assertEquals(tSpan.getParentApplicationName(), spanBo.getParentApplicationId());
    Assert.assertEquals(tSpan.getParentApplicationType(), spanBo.getParentApplicationServiceType());
    Assert.assertEquals(tSpan.getAcceptorHost(), spanBo.getAcceptorHost());

    Assert.assertEquals(tSpan.getApiId(), spanBo.getApiId());
    Assert.assertEquals(tSpan.getApplicationServiceType(), spanBo.getApplicationServiceType());

    List<SpanEventBo> spanEventBoList = spanBo.getSpanEventBoList();
    List<TSpanEvent> spanEventList = tSpan.getSpanEventList();
    assertSpanEventList(spanEventBoList, spanEventList);

    boolean hasException = tSpan.getExceptionInfo() != null;
    Assert.assertEquals(hasException, spanBo.hasException());
    if (hasException) {
        Assert.assertEquals(tSpan.getExceptionInfo().getIntValue(), spanBo.getExceptionId());
        Assert.assertEquals(tSpan.getExceptionInfo().getStringValue(), spanBo.getExceptionMessage());
    }/*from www.ja v  a 2 s . c om*/

    Assert.assertEquals(tSpan.getLoggingTransactionInfo(), spanBo.getLoggingTransactionInfo());

}

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

@Test
public void testV1RoundTrip() 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();
    //The V1 serialization is artificially constructed for the purposes of this test and should no longer be used.
    baos.write(//from  w  ww  .ja v  a  2  s  . c  o m
            Base64.encodeBase64(Serializers.timerRollupInstance.toByteBufferWithV1Serialization(r0).array()));
    baos.write("\n".getBytes());
    baos.close();

    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:implementations.terrastoreDB.java

@Override
public int updateDB(String ID, String newValue) {
    int ret;//  w ww.  j a  v  a 2s  . co m
    org.json.JSONObject myjson = null;
    try {
        myjson = XML.toJSONObject(newValue);
    } catch (JSONException e1) {
        e1.printStackTrace();
    }
    try {
        newValue = myjson.toString();
        CharsetDecoder utf8Decoder = Charset.forName("UTF-8").newDecoder();
        utf8Decoder.onMalformedInput(CodingErrorAction.REPLACE);
        utf8Decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
        ByteBuffer bytes = ByteBuffer.wrap(newValue.getBytes("UTF8"));
        CharBuffer parsed = utf8Decoder.decode(bytes);
        client.bucket("test").key(ID).put(parsed.toString());
        ret = 1;
    } catch (Exception e) {
        ret = -1;
        e.printStackTrace();
    }
    return ret;
}

From source file:com.rackspacecloud.blueflood.io.serializers.StringSerializerTest.java

@Test(expected = UnexpectedStringSerializationException.class)
public void testStringFullSerializationShouldFail() throws Throwable {
    ByteArrayOutputStream baos = serializeString(TEST_STRING);
    ByteBuffer byteBuffer = ByteBuffer.wrap(baos.toByteArray());
    try {//from   w ww  .  ja  v a  2s  .  co  m
        NumericSerializer.serializerFor(Object.class).fromByteBuffer(byteBuffer);
    } catch (RuntimeException re) {
        throw re.getCause();
    }
}

From source file:info.archinnov.achilles.it.bugs.TestEntityWithByteBufferTypeIT.java

@Test
public void should_support_bytebuffer_type() throws Exception {
    //Given/*from  w  ww  . j  a va2s  .co m*/
    final Cluster cluster = CassandraEmbeddedServerBuilder.builder().useUnsafeCassandraDeamon()
            .withScript("functions/createFunctions.cql").buildNativeCluster();

    final Long id = RandomUtils.nextLong(0, Long.MAX_VALUE);
    final byte[] bytes = RandomUtils.nextBytes(100);
    final ByteBuffer value = ByteBuffer.wrap(bytes);

    //When
    final ManagerFactory managerFactory = ManagerFactoryBuilder.builder(cluster)
            .withManagedEntityClasses(EntityWithByteBufferType.class).doForceSchemaCreation(true)
            .withDefaultKeyspaceName(DEFAULT_CASSANDRA_EMBEDDED_KEYSPACE_NAME).build();

    final EntityWithByteBufferType_Manager manager = managerFactory.forEntityWithByteBufferType();

    final EntityWithByteBufferType entity = new EntityWithByteBufferType(id, value);

    manager.crud().insert(entity).execute();

    final Row one = manager.getNativeSession()
            .execute("SELECT * FROM " + EntityWithByteBufferType.TABLE + " WHERE id = " + id).one();

    assertThat(one).isNotNull();
    assertThat(one.getBytes("value")).isEqualTo(value);
}

From source file:org.cloudfoundry.metron.MetronMetricWriter.java

private static void send(AtomicReference<Optional<Session>> sessionReference, Message<?, ?> message) {
    sessionReference.get()//from   w  ww .  j av a  2s.  c o  m
            .ifPresent(session -> session.getAsyncRemote().sendBinary(ByteBuffer.wrap(message.encode())));
}

From source file:edu.harvard.iq.dvn.unf.Base64Encoding.java

/**
 *
 * @param digest byte array for encoding in base 64,
 * @param  chngByteOrd boolean indicating if to change byte order
 * @return String the encoded base64 of digest
 *//*w  w  w  . ja v a2s .  com*/
public static String tobase64(byte[] digest, boolean chngByteOrd) {

    byte[] tobase64 = null;
    ByteOrder local = ByteOrder.nativeOrder();
    String ordbyte = local.toString();
    mLog.finer("Native byte order is: " + ordbyte);
    ByteBuffer btstream = ByteBuffer.wrap(digest);
    btstream.order(ByteOrder.BIG_ENDIAN);
    byte[] revdigest = null;
    if (chngByteOrd) {
        revdigest = changeByteOrder(digest, local);
    }
    if (revdigest != null) {
        btstream.put(revdigest);
    } else {
        btstream.put(digest);
    }

    tobase64 = Base64.encodeBase64(btstream.array());

    return new String(tobase64);

}

From source file:com.amazonaws.services.logs.connectors.elasticsearch.ElasticsearchTransformerTest.java

@Test
public void transformAccessLog() throws IOException {
    ElasticsearchTransformer classUnderTest = new ElasticsearchTransformer();

    // load the example events
    byte[] data = TestUtils.getCompressedTestFile("/access-log-example.json");

    // execute//from   w  w  w . j a  v a2 s . c o  m
    List<CloudWatchLogsEvent> logEvents = new ArrayList<>(
            classUnderTest.toClass(new Record().withData(ByteBuffer.wrap(data))));

    List<ElasticsearchObject> elasticsearchDocuments = new ArrayList<>();

    for (CloudWatchLogsEvent logEvent : logEvents) {
        elasticsearchDocuments.add(classUnderTest.fromClass(logEvent));
    }

    // verify
    assertEquals("49545295115971876468408574808414755329919666212443258898",
            elasticsearchDocuments.get(0).getId());
    assertEquals("49545295115971876468408574808465530214343480843939348498",
            elasticsearchDocuments.get(1).getId());

    assertEquals("cwl-2015.01.13", elasticsearchDocuments.get(0).getIndex());
    assertEquals("cwl-2015.01.13", elasticsearchDocuments.get(1).getIndex());

    assertEquals("Apache/access.log", elasticsearchDocuments.get(0).getType());
    assertEquals("Apache/access.log", elasticsearchDocuments.get(1).getType());

    JsonNode sourceNode;

    // event 1
    sourceNode = JSON_OBJECT_MAPPER.readTree(new StringReader(elasticsearchDocuments.get(0).getSource()));

    assertEquals("49545295115971876468408574808414755329919666212443258898", sourceNode.get("@id").asText());
    assertEquals(1421116133213L, sourceNode.get("@timestamp").asLong());
    assertEquals("123456789012", sourceNode.get("@owner").asText());
    assertEquals("Apache/access.log", sourceNode.get("@log_group").asText());
    assertEquals("i-c3f9bec9", sourceNode.get("@log_stream").asText());
    assertEquals("127.0.0.1 frank GET 200 4535", sourceNode.get("@message").asText());

    assertEquals(200, sourceNode.get("status_code").asLong());
    assertEquals("GET", sourceNode.get("verb").asText());
    assertEquals(4535, sourceNode.get("response_size").asLong());
    assertEquals("frank", sourceNode.get("user").asText());
    assertEquals("127.0.0.1", sourceNode.get("ip").asText());

    // event 2
    sourceNode = JSON_OBJECT_MAPPER.readTree(new StringReader(elasticsearchDocuments.get(1).getSource()));

    assertEquals("49545295115971876468408574808465530214343480843939348498", sourceNode.get("@id").asText());
    assertEquals(1421116143214L, sourceNode.get("@timestamp").asLong());
    assertEquals("123456789012", sourceNode.get("@owner").asText());
    assertEquals("Apache/access.log", sourceNode.get("@log_group").asText());
    assertEquals("i-c3f9bec9", sourceNode.get("@log_stream").asText());
    assertEquals("127.0.0.1 alice POST 404 34", sourceNode.get("@message").asText());

    assertEquals(404, sourceNode.get("status_code").asLong());
    assertEquals("POST", sourceNode.get("verb").asText());
    assertEquals(34, sourceNode.get("response_size").asLong());
    assertEquals("alice", sourceNode.get("user").asText());
    assertEquals("127.0.0.1", sourceNode.get("ip").asText());
}