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.ottogroup.bi.spqr.pipeline.statistics.MicroPipelineStatistics.java

/**
 * Converts the provided byte array into a {@link MicroPipelineStatistics} representation
 * @param statsContent//  ww  w  .j ava  2  s . c o  m
 * @return
 */
public static MicroPipelineStatistics fromByteArray(final byte[] statsContent) {

    MicroPipelineStatistics stats = new MicroPipelineStatistics();
    ByteBuffer buf = ByteBuffer.wrap(statsContent);

    // ensure that the order is the same as when populating the array 
    stats.setNumOfMessages(buf.getInt());
    stats.setStartTime(buf.getLong());
    stats.setEndTime(buf.getLong());
    stats.setMinDuration(buf.getInt());
    stats.setMaxDuration(buf.getInt());
    stats.setAvgDuration(buf.getInt());
    stats.setMinSize(buf.getInt());
    stats.setMaxSize(buf.getInt());
    stats.setAvgSize(buf.getInt());
    stats.setErrors(buf.getInt());

    byte[] procNodeId = new byte[buf.getInt()];
    buf.get(procNodeId);

    byte[] pipelineId = new byte[buf.getInt()];
    buf.get(pipelineId);

    byte[] componentId = new byte[buf.getInt()];
    buf.get(componentId);

    stats.setProcessingNodeId(new String(procNodeId));
    stats.setPipelineId(new String(pipelineId));
    stats.setComponentId(new String(componentId));

    return stats;
}

From source file:com.netflix.astyanax.thrift.ThriftAllRowsImpl.java

/**
 * Each call to .iterator() returns a new context starting at the beginning
 * of the column family./*  w  w w  .j av  a 2s .  c o  m*/
 */
@Override
public Iterator<Row<K, C>> iterator() {
    return new Iterator<Row<K, C>>() {
        private KeyRange range;
        private org.apache.cassandra.thrift.KeySlice lastRow;
        private List<org.apache.cassandra.thrift.KeySlice> list = null;
        private Iterator<org.apache.cassandra.thrift.KeySlice> iter = null;
        private boolean bContinueSearch = true;
        private boolean bIgnoreTombstones = true;

        {
            String startToken = query.getStartToken() == null ? partitioner.getMinToken()
                    : query.getStartToken();
            String endToken = query.getEndToken() == null ? partitioner.getMaxToken() : query.getEndToken();

            range = new KeyRange().setCount(query.getBlockSize()).setStart_token(startToken)
                    .setEnd_token(endToken);

            if (query.getIncludeEmptyRows() == null) {
                if (query.getPredicate().isSetSlice_range()
                        && query.getPredicate().getSlice_range().getCount() == 0) {
                    bIgnoreTombstones = false;
                }
            } else {
                bIgnoreTombstones = !query.getIncludeEmptyRows();
            }
        }

        @Override
        public boolean hasNext() {
            // Get the next block
            while (iter == null || (!iter.hasNext() && bContinueSearch)) {
                if (lastRow != null) {
                    // Determine the start token for the next page
                    String token = partitioner.getTokenForKey(ByteBuffer.wrap(lastRow.getKey()));
                    if (query.getRepeatLastToken()) {
                        // Start token is non-inclusive
                        range.setStart_token(partitioner.getTokenMinusOne(token));
                    } else {
                        range.setStart_token(token);
                    }
                }

                // Get the next block of rows from cassandra, exit if none returned
                list = query.getNextBlock(range);
                if (list == null || list.isEmpty()) {
                    return false;
                }

                // Since we may trim tombstones set a flag indicating whether a complete
                // block was returned so we can know to try to fetch the next one
                bContinueSearch = (list.size() == query.getBlockSize());

                // Trim the list from tombstoned rows, i.e. rows with no columns
                iter = list.iterator();
                if (iter == null || !iter.hasNext()) {
                    return false;
                }

                KeySlice previousLastRow = lastRow;
                lastRow = Iterables.getLast(list);

                if (query.getRepeatLastToken() && previousLastRow != null) {
                    iter.next();
                    iter.remove();
                }

                if (iter.hasNext() && bIgnoreTombstones) {
                    // Discard any tombstones
                    while (iter.hasNext()) {
                        KeySlice row = iter.next();
                        if (row.getColumns().isEmpty()) {
                            iter.remove();
                        }
                    }

                    // Get the iterator again
                    iter = list.iterator();
                }
            }
            return iter.hasNext();
        }

        @Override
        public Row<K, C> next() {
            org.apache.cassandra.thrift.KeySlice row = iter.next();
            return new ThriftRowImpl<K, C>(columnFamily.getKeySerializer().fromBytes(row.getKey()),
                    ByteBuffer.wrap(row.getKey()), new ThriftColumnOrSuperColumnListImpl<C>(row.getColumns(),
                            columnFamily.getColumnSerializer()));
        }

        @Override
        public void remove() {
            throw new IllegalStateException();
        }
    };
}

From source file:net.lightbody.bmp.proxy.jetty.http.nio.SocketChannelOutputStream.java

public void write(byte[] buf) throws IOException {
    if (buf.length > _buffer.capacity())
        _flush = ByteBuffer.wrap(buf);
    else {//w  w  w  .  j  a v a2 s.  c  o  m
        _buffer.clear();
        _buffer.put(buf);
        _buffer.flip();
        _flush = _buffer;
    }
    flushBuffer();
}

From source file:com.servioticy.queueclient.KestrelThriftClient.java

@Override
protected boolean putImpl(Object item) {
    int numKestrels = _kestrels.size();
    int kestrelIndex = Math.abs(item.hashCode()) % numKestrels;
    KestrelClientInfo info;/*from   w  w w  . ja  v a2  s.  c  o m*/
    long now = System.currentTimeMillis();
    for (int i = 0; i < numKestrels; i++) {
        info = _kestrels.get((kestrelIndex + i) % numKestrels);
        if (now > info.blacklistTillTimeMs) {
            List<ByteBuffer> items = new ArrayList<ByteBuffer>();
            items.add(ByteBuffer.wrap(serialize(item)));
            try {
                if (item instanceof String) {
                    info.getValidClient().put(getRelativeAddress(), (String) item, 0);
                    return true;
                } else if (info.getValidClient().put(getRelativeAddress(), items, 0) == 1) {
                    return true;
                }
            } catch (TException e) {
                blacklist(info, e);
                continue;
            }
        }
    }
    return false;
}

From source file:SequentialFramesRecordReader.java

public List<List<Writable>> sequenceRecord(URI uri, DataInputStream dataInputStream) throws IOException {
    byte[] data = IOUtils.toByteArray(dataInputStream);
    ByteBuffer bb = ByteBuffer.wrap(data);
    SequentialFramesRecordReader.FixedByteBufferSeekableByteChannel sbc = new SequentialFramesRecordReader.FixedByteBufferSeekableByteChannel(
            bb);/*ww w .j  a v a 2 s  .co m*/
    return this.loadData(sbc, null);
}

From source file:reactor.io.netty.http.PostAndGetTests.java

private void get(String path, SocketAddress address) {
    try {/* w w  w .  ja v a  2s  . c om*/
        StringBuilder request = new StringBuilder().append(String.format("GET %s HTTP/1.1\r\n", path))
                .append("Connection: Keep-Alive\r\n").append("\r\n");
        java.nio.channels.SocketChannel channel = java.nio.channels.SocketChannel.open(address);
        System.out.println(String.format("get: request >> [%s]", request.toString()));
        channel.write(ByteBuffer.wrap(request.toString().getBytes()));
        ByteBuffer buf = ByteBuffer.allocate(4 * 1024);
        while (channel.read(buf) > -1)
            ;
        String response = new String(buf.array());
        System.out.println(String.format("get: << Response: %s", response));
        channel.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.amazonaws.hbase.kinesis.BatchedStreamSource.java

private void flushBuffer() throws IOException {
    PutRecordRequest putRecordRequest = new PutRecordRequest();
    putRecordRequest.setStreamName(config.KINESIS_INPUT_STREAM);
    putRecordRequest.setData(ByteBuffer.wrap(bufferToBytes()));
    putRecordRequest.setPartitionKey(String.valueOf(UUID.randomUUID()));
    kinesisClient.putRecord(putRecordRequest);
    buffer.clear();/*w ww .  j a  v a  2 s  .com*/
}

From source file:com.tinspx.util.io.callbacks.FileTests.java

private static <T extends ContentCallback<? super BasicError.Listener, ? super ByteBuffer>> void testWriteSingle(
        byte[] ref, Supplier<T> supplier, Function<? super T, byte[]> function) throws IOException {
    Closer closer = Closer.create();//from w  ww  .  j  av  a2s  .c  o m
    T c = supplier.get();
    try {
        closer.register(Content.completeOnClose(null, c));
        c.onContentStart(null);
        for (byte b : ref) {
            c.onContent(null, ByteBuffer.wrap(new byte[] { b }));
        }
        c.onContentComplete(null);
        assertArrayEquals(ref, function.apply(c));
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

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

public static ByteBuffer bytebuffer(String s) {
    return ByteBuffer.wrap(bytes(s));
}

From source file:pl.bristleback.server.bristle.engine.tomcat.servlet.TomcatServletWebsocketEngine.java

@Override
public void sendMessage(WebsocketConnector connector, byte[] contentAsBytes) throws Exception {
    ByteBuffer buffer = ByteBuffer.wrap(contentAsBytes);
    ((TomcatConnector) connector).getConnection().writeBinaryMessage(buffer);
}