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.store.Utils.java

public static void addBlockLong(Value value, Value block) {
    ByteBuffer buf = ByteBuffer.wrap((byte[]) value.getData());
    //block value is integer
    long k = buf.getLong() + ByteBuffer.wrap((byte[]) block.getData()).getInt();
    byte[] data = putLong(k);
    value.setData(data);//from  w w w . jav  a 2s .c o  m
    value.setVersion(value.getVersion() + 1);
}

From source file:com.openteach.diamond.network.waverider.master.MasterState.java

public ByteBuffer toByteBuffer() {
    ByteArrayOutputStream bout = null;
    ObjectOutputStream oout = null;
    try {/*  w w w .j a  v  a 2s.co m*/
        bout = new ByteArrayOutputStream();
        oout = new ObjectOutputStream(bout);
        oout.writeObject(this);
        oout.flush();
        return ByteBuffer.wrap(bout.toByteArray());
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (oout != null) {
                oout.close();
            }
            if (bout != null) {
                bout.close();
            }
        } catch (IOException e) {
            logger.error(e);
        }
    }
}

From source file:com.yahoo.druid.pig.udfs.PostAggregatorAdapter.java

@Override
public T exec(Tuple input) throws IOException {
    try {/* w w w .j av a2  s.c om*/
        if (input == null || input.size() < 1) {
            throw new IOException("Null Input or Not enough arguments.");
        }

        Map<String, Object> row = new HashMap<>(columnTypes.size());
        for (int i = 0; i < columnTypes.size(); i++) {
            String type = columnTypes.get(i).getType();
            if (DruidUtils.isComplex(type)) {
                ComplexMetricSerde cms = ComplexMetrics.getSerdeForType(type);
                if (cms != null) {
                    ObjectStrategy strategy = cms.getObjectStrategy();
                    byte[] data = ((DataByteArray) input.get(i)).get();
                    row.put(columnTypes.get(i).getName(),
                            strategy.fromByteBuffer(ByteBuffer.wrap(data), data.length));
                } else
                    throw new IllegalArgumentException("failed to find object strategy for " + type);
            } else {
                row.put(columnTypes.get(i).getName(), input.get(i));
            }
        }

        //As pig needs a non-Object return type, or else we get following error on foreach
        //ERROR 2080: Foreach currently does not handle type Unknown
        //so we let concrete classes decide whether to return byte[] or finalize the
        //computation on complex object and return Long, Float etc.
        return (T) aggFactory.compute(row);
    } catch (ExecException e) {
        throw new IOException(e);
    }
}

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

public static ByteBuffer bytebuffer(UUID uuid) {
    if (uuid == null) {
        return null;
    }//w  w w.  jav a  2s  .c om
    return ByteBuffer.wrap(bytes(uuid));
}

From source file:com.ebuddy.cassandra.structure.StructureConverter.java

/**
 * @throws DataFormatException if object cannot be encoded as JSON
 */// w  ww .j  a v a2 s  .  co  m
public ByteBuffer toByteBuffer(Object obj) {
    if (obj == null) {
        return null;
    }

    if (obj instanceof String) {
        return ByteBuffer.wrap(((String) obj).getBytes(UTF8_CHARSET));
    }

    // write as special header bytes followed by JSON
    // intercept the Null token which stands in for a real null
    if (obj == NULL) {
        obj = null;
    }
    String jsonString = encodeJson(obj);
    byte[] jsonBytes = jsonString.getBytes(UTF8_CHARSET);
    byte[] result = new byte[jsonBytes.length + UTF8_HEADER_BYTES.length];
    System.arraycopy(UTF8_HEADER_BYTES, 0, result, 0, UTF8_HEADER_BYTES.length);
    System.arraycopy(jsonBytes, 0, result, UTF8_HEADER_BYTES.length, jsonBytes.length);
    return ByteBuffer.wrap(result);
}

From source file:de.brendamour.jpasskit.signing.PKInMemorySigningUtil.java

private ByteBuffer createPassJSONFile(final PKPass pass) throws PKSigningException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {//from   ww w.j  ava2 s . c  o  m
        objectWriter.writeValue(byteArrayOutputStream, pass);
        return ByteBuffer.wrap(byteArrayOutputStream.toByteArray());
    } catch (IOException e) {
        throw new PKSigningException("Error when writing pass.json", e);
    } finally {
        IOUtils.closeQuietly(byteArrayOutputStream);
    }
}

From source file:com.saasovation.common.port.adapter.messaging.slothmq.SlothWorker.java

protected void sendTo(int aPort, String anEncodedMessage) {
    SocketChannel socketChannel = null;

    try {// w  ww  .  j a va 2 s .c om
        socketChannel = SocketChannel.open();
        InetSocketAddress address = new InetSocketAddress(InetAddress.getLoopbackAddress(), aPort);
        socketChannel.connect(address);
        socketChannel.write(ByteBuffer.wrap(anEncodedMessage.getBytes()));
        logger.debug("Sent: {}", anEncodedMessage);

    } catch (IOException e) {
        logger.error("Failed to send because: {}: Continuing...", e.getMessage(), e);
    } finally {
        if (socketChannel != null) {
            try {
                socketChannel.close();
            } catch (IOException e) {
                logger.error("Failed to close client socket because: {}: Continuing...", e.getMessage(), e);
            }
        }
    }
}

From source file:ezbake.azkaban.submitter.AzkabanSubmitter.java

private void run(CmdLineParser parser) throws TException, IOException, CmdLineException {
    if (!(submit)) {
        throw new CmdLineException(parser, "Must provide -u option to client");
    }//  w  w w . j a  v a  2  s  .  c  o  m

    final EzConfiguration config;
    try {
        config = new EzConfiguration();
    } catch (EzConfigurationLoaderException e) {
        throw new IOException(e);
    }

    config.getProperties().setProperty(EzBakePropertyConstants.EZBAKE_SECURITY_ID, securityId);

    if (submit) {
        if (Strings.isNullOrEmpty(projectId))
            throw new CmdLineException(parser, "Pipeline ID required for submission");
        File zipFile = new File(pathToTarGz);
        byte[] fileBytes = FileUtils.readFileToByteArray(zipFile);
        UploaderResult result = submit(ByteBuffer.wrap(fileBytes), projectId);
        System.out.println("Upload " + (result.hasError() ? "FAILED" : "SUCCESSFUL"));
    }
}

From source file:com.linkedin.pinot.core.startree.StarTreeDataSorter.java

/**
 * Sort from to given start (inclusive) to end (exclusive) as per the provided sort order.
 * @param startRecordId inclusive//from   www .j a  v a  2  s .c  om
 * @param endRecordId exclusive
 * @param sortOrder
 */
public void sort(int startRecordId, int endRecordId, final int[] sortOrder) {
    int length = endRecordId - startRecordId;
    final int startOffset = startRecordId * totalSizeInBytes;

    List<Integer> idList = new ArrayList<Integer>();
    for (int i = startRecordId; i < endRecordId; i++) {
        idList.add(i - startRecordId);
    }

    Comparator<Integer> comparator = new Comparator<Integer>() {
        byte[] buf1 = new byte[dimensionSizeInBytes];
        byte[] buf2 = new byte[dimensionSizeInBytes];

        @Override
        public int compare(Integer o1, Integer o2) {
            int pos1 = startOffset + (o1) * totalSizeInBytes;
            int pos2 = startOffset + (o2) * totalSizeInBytes;

            mappedByteBuffer.copyTo(pos1, buf1, 0, dimensionSizeInBytes);
            mappedByteBuffer.copyTo(pos2, buf2, 0, dimensionSizeInBytes);

            IntBuffer bb1 = ByteBuffer.wrap(buf1).asIntBuffer();
            IntBuffer bb2 = ByteBuffer.wrap(buf2).asIntBuffer();

            for (int dimIndex : sortOrder) {
                int v1 = bb1.get(dimIndex);
                int v2 = bb2.get(dimIndex);
                if (v1 != v2) {
                    return v1 - v2;
                }
            }
            return 0;
        }
    };

    Collections.sort(idList, comparator);
    int[] currentPositions = new int[length];
    int[] indexToRecordIdMapping = new int[length];

    byte[] buf1 = new byte[totalSizeInBytes];
    byte[] buf2 = new byte[totalSizeInBytes];

    for (int i = 0; i < length; i++) {
        currentPositions[i] = i;
        indexToRecordIdMapping[i] = i;
    }

    for (int i = 0; i < length; i++) {
        int thisRecordId = indexToRecordIdMapping[i];
        int thisRecordIdPos = currentPositions[thisRecordId];

        int thatRecordId = idList.get(i);
        int thatRecordIdPos = currentPositions[thatRecordId];

        // swap the buffers
        mappedByteBuffer.copyTo(startOffset + thisRecordIdPos * totalSizeInBytes, buf1, 0, totalSizeInBytes);
        mappedByteBuffer.copyTo(startOffset + thatRecordIdPos * totalSizeInBytes, buf2, 0, totalSizeInBytes);
        mappedByteBuffer.readFrom(buf2, 0, startOffset + thisRecordIdPos * totalSizeInBytes, totalSizeInBytes);
        mappedByteBuffer.readFrom(buf1, 0, startOffset + thatRecordIdPos * totalSizeInBytes, totalSizeInBytes);

        // update the positions
        indexToRecordIdMapping[i] = thatRecordId;
        indexToRecordIdMapping[thatRecordIdPos] = thisRecordId;

        currentPositions[thatRecordId] = i;
        currentPositions[thisRecordId] = thatRecordIdPos;
    }
}

From source file:com.amazonaws.services.kinesis.producer.KinesisProducerTest.java

@Test
public void differentCredsForRecordsAndMetrics() throws InterruptedException, ExecutionException {
    final String AKID_A = "AKIAAAAAAAAAAAAAAAAA";
    final String AKID_B = "AKIABBBBBBBBBBBBBBBB";

    final KinesisProducer kp = getProducer(
            new StaticCredentialsProvider(new BasicAWSCredentials(AKID_A, StringUtils.repeat("a", 40))),
            new StaticCredentialsProvider(new BasicAWSCredentials(AKID_B, StringUtils.repeat("b", 40))));

    final long start = System.nanoTime();
    while (System.nanoTime() - start < 500 * 1000000) {
        kp.addUserRecord("a", "a", ByteBuffer.wrap(new byte[0]));
        kp.flush();//from w  w w .  j  a va2  s.com
        Thread.sleep(10);
    }

    kp.flushSync();
    kp.destroy();

    Map<String, AtomicInteger> counts = new HashMap<String, AtomicInteger>();
    counts.put(AKID_A, new AtomicInteger(0));
    counts.put(AKID_B, new AtomicInteger(0));

    for (ClientRequest cr : server.getRequests()) {
        String auth = cr.getHeaders().get("Authorization");
        if (auth == null) {
            auth = cr.getHeaders().get("authorization");
        }
        String host = cr.getHeaders().get("Host");
        if (host == null) {
            cr.getHeaders().get("host");
        }
        if (auth.contains(AKID_B)) {
            assertFalse(host.contains("kinesis"));
            counts.get(AKID_B).getAndIncrement();
        } else if (auth.contains(AKID_A)) {
            assertFalse(host.contains("monitoring"));
            counts.get(AKID_A).getAndIncrement();
        } else {
            fail("Expected AKID(s) not found in auth header");
        }
    }

    assertTrue(counts.get(AKID_A).get() > 1);
    assertTrue(counts.get(AKID_B).get() > 1);
}