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:pl.allegro.tech.hermes.consumers.consumer.sender.http.ByteBufferEntityTest.java

@Test
public void testBasics() throws Exception {
    final ByteBuffer bytes = ByteBuffer.wrap("Message content".getBytes(Consts.ASCII));
    final ByteBufferEntity httpentity = new ByteBufferEntity(bytes);

    Assert.assertEquals(bytes.capacity(), httpentity.getContentLength());
    Assert.assertNotNull(httpentity.getContent());
    Assert.assertTrue(httpentity.isRepeatable());
    Assert.assertFalse(httpentity.isStreaming());
}

From source file:com.cloudera.flume.handlers.thrift.ThriftEventAdaptor.java

/**
 * This makes a thrift compatible copy of the event. It is here to encapsulate
 * future changes to the Event/ThriftFlumeEvent interface
 *///from ww  w  .  ja va 2 s  .  c om
public static ThriftFlumeEvent convert(Event e) {
    ThriftFlumeEvent evt = new ThriftFlumeEvent();
    evt.timestamp = e.getTimestamp();
    evt.priority = convert(e.getPriority());
    ByteBuffer buf = ByteBuffer.wrap(e.getBody());
    evt.body = buf;
    evt.nanos = e.getNanos();
    evt.host = e.getHost();

    Map<String, byte[]> tempMap = e.getAttrs();
    Map<String, ByteBuffer> returnMap = new HashMap<String, ByteBuffer>();
    for (String key : tempMap.keySet()) {
        buf.clear();
        buf = ByteBuffer.wrap(tempMap.get(key));
        returnMap.put(key, buf);
    }

    evt.fields = returnMap;
    return evt;
}

From source file:com.github.jinahya.verbose.codec.BinaryCodecTest.java

/**
 * Tests encoding/decoding for given byte array.
 *
 * @param expectedBytes the decoded byte array.
 *
 * @see HexEncoder#encode(byte[])//from   w  w  w.  j a v a  2  s.co  m
 * @see HexDecoder#decode(byte[])
 */
protected final void encodeDecode(final byte[] expectedBytes) {

    encodeDecode(ByteBuffer.wrap(expectedBytes));
}

From source file:ezbake.deployer.publishers.EzFrackPublisher.java

@Override
public void publish(DeploymentArtifact artifact, EzSecurityToken callerToken) throws DeploymentException {
    Submitter.Client client;// w  ww . j av a 2 s.c om
    String pipelineId = ArtifactHelpers.getServiceId(artifact);
    try {
        client = pool.getClient(submitterConstants.SERVICE_NAME, Submitter.Client.class);

        // Kill the pipeline first
        try {
            log.info("Attempting to kill pipeline to make sure that the new deployment succeeds");
            client.shutdown(pipelineId);
        } catch (PipelineNotRunningException e) {
            log.warn("Pipeline was not running, continuing deployment. Exception from submitter: ", e);
        }

        log.info("Deploying pipeline {}", pipelineId);
        byte[] tarGz = handleKeys(artifact, callerToken);
        SubmitResult result = client.submit(ByteBuffer.wrap(tarGz), pipelineId);
        log.info("Frack submission was successful? " + result.isSubmitted());
        log.info("Frack submission result message: \n" + result.getMessage());
    } catch (TException e) {
        String message = "Could not submit artifact to Frack";
        log.error(message, e);
        throw new DeploymentException(message);
    }

}

From source file:ar.com.init.agros.license.LicenseVerifier.java

private boolean isMasterLicense(String file) throws IOException, FileNotFoundException {
    File licenseFile = new File(file);
    FileChannel fc = (new FileInputStream(licenseFile)).getChannel();
    byte[] bytes = new byte[(int) fc.size()];
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    fc.read(bb);/*from w w w  . j ava  2 s  .  c  o m*/
    String hash = DigestUtils.md5Hex(bytes);
    fc.close();
    boolean isMaster = hash.equals(MASTER_LICENSE_HASH);
    return isMaster;
}

From source file:ws.salient.aws.dynamodb.DynamoDBProfiles.java

private Settings getSettings(String accountId) {
    return accounts.computeIfAbsent(accountId, (id) -> {
        Settings settings = new Settings();
        ItemCollection<QueryOutcome> items = dynamodb.getTable("SalientProfile")
                .query(new QuerySpec().withHashKey("accountId", id));
        items.pages().forEach((page) -> {
            page.iterator().forEachRemaining((item) -> {
                try {
                    Profile profile = new Profile();
                    if (item.hasAttribute("aliases")) {
                        profile.setAliases(json.readValue(item.getJSON("aliases"), Map.class));
                    }//from   w ww .ja  v  a 2 s.  c o  m
                    if (item.hasAttribute("properties")) {
                        if (item.get("properties") instanceof byte[]) {
                            log.info("Decrypt profile " + item.getString("profileName"));
                            DecryptResult decrypt = kms.decrypt(
                                    new DecryptRequest().addEncryptionContextEntry("accountId", accountId)
                                            .withCiphertextBlob(ByteBuffer.wrap(item.getBinary("properties"))));
                            profile.setProperties(
                                    json.readValue(decrypt.getPlaintext().array(), Properties.class));
                        } else {
                            Properties properties = new Properties();
                            properties.putAll(item.getMap("properties"));
                            profile.setProperties(properties);
                        }
                    }
                    if (item.hasAttribute("repositories")) {
                        profile.setRepositories(json.readValue(item.getJSON("repositories"),
                                json.getTypeFactory().constructCollectionType(Set.class, Repository.class)));
                    }
                    String name = item.getString("profileName");
                    Boolean active = item.getBoolean("active");
                    settings.withProfile(name, profile);
                    if (active) {
                        settings.withActiveProfile(name);
                    }
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            });
        });
        return settings;
    });
}

From source file:com.amazonaws.services.kinesis.multilang.MessageWriterTest.java

@Test
public void writeProcessRecordsMessageTest() throws IOException, InterruptedException, ExecutionException {
    List<Record> records = new ArrayList<Record>() {
        {/*  w  ww  .  jav  a2 s  . c  o m*/
            this.add(new Record() {
                {
                    this.setData(ByteBuffer.wrap("kitten".getBytes()));
                    this.setPartitionKey("some cats");
                    this.setSequenceNumber("357234807854789057805");
                }
            });
            this.add(new Record());
        }
    };
    Future<Boolean> future = this.messageWriter.writeProcessRecordsMessage(records);
    future.get();

    Mockito.verify(this.stream, Mockito.atLeastOnce()).write(Mockito.any(byte[].class), Mockito.anyInt(),
            Mockito.anyInt());
    Mockito.verify(this.stream, Mockito.atLeastOnce()).flush();
}

From source file:domain.Employee.java

private static String uuidToBase64(String str) {
    UUID uuid = UUID.fromString(str);
    ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
    bb.putLong(uuid.getMostSignificantBits());
    bb.putLong(uuid.getLeastSignificantBits());
    return Base64.encodeBase64URLSafeString(bb.array());
}

From source file:ca.psiphon.ploggy.Robohash.java

public static Bitmap getRobohash(Context context, boolean cacheCandidate, byte[] data)
        throws Utils.ApplicationError {
    try {/*  w ww  . j a  v a 2s .c  o  m*/
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
        byte[] digest = sha1.digest(data);

        String key = Utils.formatFingerprint(digest);
        Bitmap cachedBitmap = mCache.get(key);
        if (cachedBitmap != null) {
            return cachedBitmap;
        }

        ByteBuffer byteBuffer = ByteBuffer.wrap(digest);
        byteBuffer.order(ByteOrder.BIG_ENDIAN);
        // TODO: SecureRandom SHA1PRNG (but not LinuxSecureRandom)
        Random random = new Random(byteBuffer.getLong());

        AssetManager assetManager = context.getAssets();

        if (mConfig == null) {
            mConfig = new JSONObject(loadAssetToString(assetManager, CONFIG_FILENAME));
        }

        int width = mConfig.getInt("width");
        int height = mConfig.getInt("height");

        JSONArray colors = mConfig.getJSONArray("colors");
        JSONArray parts = colors.getJSONArray(random.nextInt(colors.length()));

        Bitmap robotBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas robotCanvas = new Canvas(robotBitmap);

        for (int i = 0; i < parts.length(); i++) {
            JSONArray partChoices = parts.getJSONArray(i);
            String selection = partChoices.getString(random.nextInt(partChoices.length()));
            Bitmap partBitmap = loadAssetToBitmap(assetManager, selection);
            Rect rect = new Rect(0, 0, width, height);
            Paint paint = new Paint();
            paint.setAlpha(255);
            robotCanvas.drawBitmap(partBitmap, rect, rect, paint);
            partBitmap.recycle();
        }

        if (cacheCandidate) {
            mCache.set(key, robotBitmap);
        }

        return robotBitmap;

    } catch (IOException e) {
        throw new Utils.ApplicationError(LOG_TAG, e);
    } catch (JSONException e) {
        throw new Utils.ApplicationError(LOG_TAG, e);
    } catch (NoSuchAlgorithmException e) {
        throw new Utils.ApplicationError(LOG_TAG, e);
    }
}

From source file:com.knewton.mapreduce.SSTableColumnMapperTest.java

/**
 * Test the start time range filters in the mapper.
 * /*from  w w  w .ja va 2 s  .c  o  m*/
 * @throws IOException
 * @throws InterruptedException
 * @throws DecoderException
 */
@Test
public void testStartRangeStudentEvents() throws IOException, InterruptedException, DecoderException {

    // Mar.28.2013.19:53:38.0.0
    DateTime dt = new DateTime(2013, 3, 28, 19, 53, 10, DateTimeZone.UTC);
    long eventId1 = dt.getMillis();
    // Mar.29.2013.03:07:21.0.0
    dt = new DateTime(2013, 3, 29, 3, 7, 21, DateTimeZone.UTC);
    long eventId5 = dt.getMillis();

    ByteBuffer columnName = ByteBuffer.wrap(new byte[8]);
    columnName.putLong(eventId1);
    columnName.rewind();
    IColumn column = new Column(columnName, ByteBuffer.wrap(Hex.decodeHex(eventDataString.toCharArray())));
    Configuration conf = new Configuration();
    conf.set(StudentEventAbstractMapper.START_DATE_PARAMETER_NAME, "2013-03-28T23:03:02.394-04:00");
    DoNothingStudentEventMapper dnsem = new DoNothingStudentEventMapper();
    Mapper<ByteBuffer, IColumn, LongWritable, StudentEventWritable>.Context context = dnsem.new Context(conf,
            new TaskAttemptID(), null, null, null, new DoNothingStatusReporter(), null);
    dnsem.setup(context);
    dnsem.map(RandomStudentEventGenerator.getRandomIdBuffer(), column, context);
    assertNull(dnsem.getRowKey());
    columnName = ByteBuffer.wrap(new byte[8]);
    columnName.putLong(eventId5);
    columnName.rewind();
    column = new Column(columnName, ByteBuffer.wrap(Hex.decodeHex(eventDataString.toCharArray())));
    ByteBuffer randomKey = RandomStudentEventGenerator.getRandomIdBuffer();
    dnsem.map(randomKey, column, context);
    assertEquals(dnsem.getRowKey(), randomKey);
}