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.sm.replica.ParaList.java

public static ParaList toParaList(byte[] bytes) {
    ByteBuffer buf = ByteBuffer.wrap(bytes);
    int size = buf.getInt();
    ArrayList<StoreParas> list = new ArrayList<StoreParas>(size);
    for (int i = 0; i < size; i++) {
        // length of StoreParas
        int s = buf.getInt();
        byte[] ds = new byte[s];
        buf.get(ds);//from w ww  . j av a2s  . c  o m
        list.add(toStoreParas(ds));

    }
    return new ParaList(list);

}

From source file:com.amazonaws.services.kinesis.multilang.messages.MessageTest.java

@Test
public void toStringTest() {
    Message[] messages = new Message[] { new CheckpointMessage("1234567890", null),
            new InitializeMessage("shard-123"), new ProcessRecordsMessage(new ArrayList<Record>() {
                {/*from  w  ww .j  a v  a 2  s.  c o m*/
                    this.add(new Record() {
                        {
                            this.withData(ByteBuffer.wrap("cat".getBytes()));
                            this.withPartitionKey("cat");
                            this.withSequenceNumber("555");
                        }
                    });
                }
            }), new ShutdownMessage(ShutdownReason.ZOMBIE), new StatusMessage("processRecords"),
            new InitializeMessage(), new ProcessRecordsMessage() };

    for (int i = 0; i < messages.length; i++) {
        Assert.assertTrue("Each message should contain the action field",
                messages[i].toString().contains("action"));
    }

    // Hit this constructor
    JsonFriendlyRecord defaultJsonFriendlyRecord = new JsonFriendlyRecord();
    Assert.assertNull(defaultJsonFriendlyRecord.getPartitionKey());
    Assert.assertNull(defaultJsonFriendlyRecord.getData());
    Assert.assertNull(defaultJsonFriendlyRecord.getSequenceNumber());
    Assert.assertNull(new ShutdownMessage(null).getReason());

    // Hit the bad object mapping path
    Message withBadMapper = new Message() {
    }.withObjectMapper(new ObjectMapper() {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        @Override
        public String writeValueAsString(Object m) throws JsonProcessingException {
            throw new JsonProcessingException(new Throwable()) {
            };
        }
    });
    String s = withBadMapper.toString();
    Assert.assertNotNull(s);
}

From source file:de.rwhq.serializer.FixedStringSerializer.java

@Override
public String deserialize(final byte[] o) {
    final ByteBuffer buf = ByteBuffer.wrap(o);
    final short length = buf.getShort();

    final byte[] bytes = new byte[length];
    buf.get(bytes);//from   w ww  .j  a  v a 2s. co  m
    return new String(bytes);
}

From source file:io.warp10.quasar.trl.QuasarTokenRevocationListLoader.java

public static QuasarTokenRevocationListLoader getInstance(Properties config, byte[] appSipHashKey) {
    if (singleton.compareAndSet(false, true)) {
        ByteBuffer bb = ByteBuffer.wrap(appSipHashKey);
        bb.order(ByteOrder.BIG_ENDIAN);
        appIdSipHashKeyK0 = bb.getLong();
        appIdSipHashKeyK1 = bb.getLong();
        quasarTokenRevocationListLoader = new QuasarTokenRevocationListLoader(config);
    }/*  ww  w .  j  a v  a 2  s  . com*/
    return quasarTokenRevocationListLoader;
}

From source file:com.ah.be.ls.processor2.TxProcessor.java

public void parsePacket(byte packetType, byte[] input) {
    ByteBuffer buf = ByteBuffer.wrap(input);
    switch (packetType) {
    case CommConst.PacketType_Error_Response:
        responseObj = new ErrorResponse();
        break;/*from  w  w w.j a v  a2 s. c  o m*/
    case CommConst.PacketType_Sample_Response:
        responseObj = new ResponseTxObjectSample();
        break;
    default:
        break;
    }
    if (responseObj != null) {
        responseObj.unpack(buf);
    }
}

From source file:com.spectralogic.ds3client.utils.IOUtils.java

public static long copy(final InputStream inputStream, final WritableByteChannel writableByteChannel,
        final int bufferSize, final String objName, final boolean isPutCommand) throws IOException {
    final byte[] buffer = new byte[bufferSize];
    final ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
    int len;//from w  w  w .  j av  a 2  s.  c  o m
    long totalBytes = 0;

    final long startTime = PerformanceUtils.getCurrentTime();
    long statusUpdateTime = startTime;

    try {
        while ((len = inputStream.read(buffer)) != -1) {
            totalBytes += len;

            try {
                byteBuffer.position(0);
                byteBuffer.limit(len);
                writableByteChannel.write(byteBuffer);
            } catch (final Throwable t) {
                throw new UnrecoverableIOException(t);
            }

            final long curTime = PerformanceUtils.getCurrentTime();
            if (statusUpdateTime <= curTime) {
                PerformanceUtils.logMbpsStatus(startTime, curTime, totalBytes, objName, isPutCommand);
                statusUpdateTime += 60000D; //Only logs status once a minute
            }
        }
    } catch (final ConnectionClosedException e) {
        LOG.error("Connection closed trying to copy from stream to channel.", e);
    }

    return totalBytes;
}

From source file:com.streamsets.pipeline.stage.lib.kinesis.KinesisTestUtil.java

public static List<com.amazonaws.services.kinesis.model.Record> getConsumerTestRecords(int i) {
    List<com.amazonaws.services.kinesis.model.Record> records = new ArrayList<>(i);

    for (int j = 0; j < i; j++) {
        com.amazonaws.services.kinesis.model.Record record = new com.amazonaws.services.kinesis.model.Record()
                .withData(ByteBuffer.wrap(String.format("{\"seq\": %s}", j).getBytes()))
                .withPartitionKey(StringUtils.repeat("0", 19)).withSequenceNumber(String.valueOf(j))
                .withApproximateArrivalTimestamp(Calendar.getInstance().getTime());
        records.add(new UserRecord(record));
    }//from   w ww  .java 2 s  .  c o  m

    return records;
}

From source file:Main.java

static long md5sum(String text) {

    byte[] defaultBytes = text.getBytes();

    try {//from w ww .  j  a  va2s . com

        MessageDigest algorithm = MessageDigest.getInstance("MD5");

        algorithm.reset();

        algorithm.update(defaultBytes);

        byte digest[] = algorithm.digest();

        ByteBuffer buffer = ByteBuffer.wrap(digest);

        return buffer.getLong();

    } catch (NoSuchAlgorithmException e) {

        Log.e("udt", "md5 failed: " + e);

        return 0;

    }

}

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

@Bean
AWSKMS kms() {//from   w w  w  .  j  a  v  a2  s.  co m
    final AWSKMS mock = mock(AWSKMS.class);
    final DecryptResult result = new DecryptResult();
    result.setPlaintext(ByteBuffer.wrap(KmsEncryptionIntegrationConfigurationTest.PLAINTEXT.getBytes()));
    when(mock.decrypt(any(DecryptRequest.class))).thenReturn(result);
    return mock;
}

From source file:ezbake.deployer.cli.commands.DeployTarCommand.java

@Override
public void call() throws IOException, TException, DeploymentException {

    String[] args = globalParameters.unparsedArgs;
    minExpectedArgs(1, args, this);
    String prefix = trimNamePrefix(args[0]);
    final File manifest = new File(prefix + "-manifest.yml");
    final File artifact = new File(prefix + ".tar.gz");

    ArtifactManifest artifactManifest = readManifestFile(manifest).get(0);
    byte[] artifactBuffer = FileUtils.readFileToByteArray(artifact);

    getClient().deployService(artifactManifest, ByteBuffer.wrap(artifactBuffer), getSecurityToken());
}