Example usage for java.nio ByteBuffer capacity

List of usage examples for java.nio ByteBuffer capacity

Introduction

In this page you can find the example usage for java.nio ByteBuffer capacity.

Prototype

public final int capacity() 

Source Link

Document

Returns the capacity of this buffer.

Usage

From source file:com.cinchapi.concourse.server.plugin.PluginManager.java

/**
 * Invoke {@code method} that is defined in the plugin endpoint inside of
 * {@clazz}. The provided {@code creds}, {@code transaction} token and
 * {@code environment} are used to ensure proper alignment with the
 * corresponding client session on the server.
 * /*  w ww.ja va2  s  .c o m*/
 * @param clazz the {@link Plugin} endpoint class
 * @param method the name of the method to invoke
 * @param args a list of arguments to pass to the method
 * @param creds the {@link AccessToken} submitted to ConcourseServer via the
 *            invokePlugin method
 * @param transaction the {@link TransactionToken} submitted to
 *            ConcourseServer via the invokePlugin method
 * @param environment the environment submitted to ConcourseServer via the
 *            invokePlugin method
 * @return the response from the plugin
 */
public ComplexTObject invoke(String clazz, String method, List<ComplexTObject> args, final AccessToken creds,
        TransactionToken transaction, String environment) {
    SharedMemory fromServer = (SharedMemory) router.get(clazz, PluginInfoColumn.FROM_SERVER);
    RemoteMethodRequest request = new RemoteMethodRequest(method, creds, transaction, environment, args);
    ByteBuffer data0 = Serializables.getBytes(request);
    ByteBuffer data = ByteBuffer.allocate(data0.capacity() + 4);
    data.putInt(Plugin.Instruction.REQUEST.ordinal());
    data.put(data0);
    fromServer.write(ByteBuffers.rewind(data));
    ConcurrentMap<AccessToken, RemoteMethodResponse> fromPluginResponses = (ConcurrentMap<AccessToken, RemoteMethodResponse>) router
            .get(clazz, PluginInfoColumn.FROM_PLUGIN_RESPONSES);
    RemoteMethodResponse response = ConcurrentMaps.waitAndRemove(fromPluginResponses, creds);
    if (!response.isError()) {
        return response.response;
    } else {
        throw Throwables.propagate(response.error);
    }
}

From source file:com.cinchapi.concourse.server.plugin.PluginManager.java

/**
 * Create a {@link SharedMemory} segment over which the PluginManager will
 * stream real-time {@link Packet packets} that contain writes.
 * //w w  w .j av  a2  s. c  om
 * @param id the plugin id
 */
private void initRealTimeStream(String id) {
    String streamFile = FileSystem.tempFile();
    SharedMemory stream = new SharedMemory(streamFile);
    ByteBuffer payload = ByteBuffers.fromString(streamFile);
    ByteBuffer message = ByteBuffer.allocate(payload.capacity() + 4);
    message.putInt(Instruction.MESSAGE.ordinal());
    message.put(payload);
    SharedMemory fromServer = (SharedMemory) router.get(id, PluginInfoColumn.FROM_SERVER);
    fromServer.write(ByteBuffers.rewind(message));
    streams.add(stream);
}

From source file:org.zuinnote.hadoop.bitcoin.format.BitcoinRawBlockRecordReader.java

/**
*
* Read a next block. /*www  .ja  v a  2s . c om*/
*
* @param key is a 64 byte array (hashMerkleRoot and prevHashBlock)
* @param value is a deserialized Java object of class BitcoinBlock
*
* @return true if next block is available, false if not
*/
public boolean next(BytesWritable key, BytesWritable value) throws IOException {
    // read all the blocks, if necessary a block overlapping a split
    while (getFilePosition() <= getEnd()) { // did we already went beyond the split (remote) or do we have no further data left?
        ByteBuffer dataBlock = null;
        try {
            dataBlock = getBbr().readRawBlock();
        } catch (BitcoinBlockReadException e) {
            // log
            LOG.error(e);
        }
        if (dataBlock == null)
            return false;
        byte newKey[] = getBbr().getKeyFromRawBlock(dataBlock);
        key.set(newKey, 0, newKey.length);
        byte[] dataBlockArray = null;
        if (dataBlock.hasArray() == true) {
            dataBlockArray = dataBlock.array();
        } else {
            dataBlockArray = new byte[dataBlock.capacity()];
            dataBlock.get(dataBlockArray);
        }
        value.set(dataBlockArray, 0, dataBlockArray.length);
        return true;
    }
    return false;
}

From source file:org.jtrfp.trcl.core.Texture.java

Texture(ByteBuffer imageRGBA8888, ByteBuffer imageESTuTv8888, String debugName, TR tr, boolean uvWrapping) {
    this(tr, debugName, uvWrapping);
    if (imageRGBA8888.capacity() == 0) {
        throw new IllegalArgumentException("Cannot create texture of zero size.");
    } //end if capacity==0
    imageRGBA8888.clear();//Doesn't erase, just resets the tracking vars
    vqCompress(imageRGBA8888, imageESTuTv8888);
}

From source file:voldemort.store.cachestore.impl.LogChannel.java

public KeyValue readRecord(int recordNo) {
    if (isEOF(recordNo))
        throw new RuntimeException("record out of range " + getTotalRecord() + " expected " + recordNo);
    ByteBuffer buf = ByteBuffer.allocate(RECORD_SIZE);
    long pos = ChannelStore.OFFSET + (long) recordNo * RECORD_SIZE;
    try {//from  w  w w .java  2  s  . c om
        if (isLastRecord(recordNo)) {
            logger.info("skip due to " + totalRecord + " read " + recordNo);
            return null;
        }
        getIndexChannel().read(buf, pos);
        assert (buf.capacity() == RECORD_SIZE);
        buf.rewind();
        byte status = buf.get();
        long keyOffset2Len = buf.getLong();
        byte[] keys = readChannel(keyOffset2Len, getKeyChannel());
        Key k = toKey(keys);
        long dataOffset2Len = buf.getLong();
        byte[] datas = readChannel(dataOffset2Len, getDataChannel());
        long block2version = buf.getLong();
        Value<byte[]> value = null;
        //if delete return value=null, not delete read value
        if (!isDeleted(status))
            value = new BlockValue<byte[]>(datas, BlockUtil.getVersionNo(block2version), (short) 0);
        return new KeyValue(k, value);
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:thproject.test.com.myapplication.SongRecognitionActivity.java

public void startStreaming() throws GnException {
    isListening = true;/*from  w w w .  ja  v a 2 s .  co  m*/
    gnMicrophone = new GnMic(44100, 16, 1); //mic initialization
    gnMicrophone.sourceInit();
    //initialize music stream
    gnMusicIdStream = new GnMusicIdStream(gnUser, new GnMusicIdStreamEvents());
    gnMusicIdStream.audioProcessStart(gnMicrophone.samplesPerSecond(), gnMicrophone.sampleSizeInBits(),
            gnMicrophone.numberOfChannels());
    Thread audioProcessThread = new Thread(new Runnable() {
        @Override
        public void run() {
            ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024 * 4);
            long bytesRead = 0;
            //                Log.d("startRecording","begin loop");
            while (isListening) {
                bytesRead = gnMicrophone.getData(byteBuffer, byteBuffer.capacity());
                try {
                    gnMusicIdStream.audioProcess(byteBuffer.array(), bytesRead);
                } catch (GnException e) {
                    e.printStackTrace();
                }
            }

        }
    });
    audioProcessThread.start();
    gnMusicIdStream.identifyAlbumAsync();
}

From source file:org.codehaus.preon.buffer.DefaultBitBuffer.java

/**
 * Constructs a new instance.//from w  w  w .j a va  2  s  .  com
 *
 * @param inputByteBuffer input buffered byte stream
 */
public DefaultBitBuffer(ByteBuffer inputByteBuffer) {
    // TODO: I think we should use #limit() instead of #capacity()
    this(inputByteBuffer, ((long) (inputByteBuffer.capacity())) << 3, 0L);
}

From source file:com.turn.ttorrent.client.ConnectionHandler.java

/**
 * Validate an expected handshake on a connection.
 *
 * <p>//from  w  ww  .j  av a  2  s . co m
 * Reads an expected handshake message from the given connected socket,
 * parses it and validates that the torrent hash_info corresponds to the
 * torrent we're sharing, and that the peerId matches the peer ID we expect
 * to see coming from the remote peer.
 * </p>
 *
 * @param channel The connected socket channel to the remote peer.
 * @param peerId The peer ID we expect in the handshake. If <em>null</em>,
 * any peer ID is accepted (this is the case for incoming connections).
 * @return The validated handshake message object.
 */
private Handshake validateHandshake(SocketChannel channel, byte[] peerId) throws IOException, ParseException {
    ByteBuffer len = ByteBuffer.allocate(1);
    ByteBuffer data;

    // Read the handshake from the wire
    logger.trace("Reading handshake size (1 byte) from {}...", this.socketRepr(channel));
    if (channel.read(len) < len.capacity()) {
        throw new IOException("Handshake size read underrrun");
    }

    len.rewind();
    int pstrlen = len.get();

    data = ByteBuffer.allocate(Handshake.BASE_HANDSHAKE_LENGTH + pstrlen);
    data.put((byte) pstrlen);
    int expected = data.remaining();
    int read = channel.read(data);
    if (read < expected) {
        throw new IOException("Handshake data read underrun (" + read + " < " + expected + " bytes)");
    }

    // Parse and check the handshake
    data.rewind();
    Handshake hs = Handshake.parse(data);
    if (!Arrays.equals(hs.getInfoHash(), this.torrent.getInfoHash())) {
        throw new ParseException("Handshake for unknow torrent " + Utils.bytesToHex(hs.getInfoHash()) + " from "
                + this.socketRepr(channel) + ".", pstrlen + 9);
    }

    if (peerId != null && !Arrays.equals(hs.getPeerId(), peerId)) {
        throw new ParseException("Announced peer ID " + Utils.bytesToHex(hs.getPeerId())
                + " did not match expected peer ID " + Utils.bytesToHex(peerId) + ".", pstrlen + 29);
    }

    return hs;
}

From source file:org.apache.carbondata.core.util.CarbonUtil.java

/**
 * This method will form one single byte [] for all the high card dims.
 * First it will add all the indexes of variable length byte[] and then the
 * actual value/*from ww w.  ja  v  a  2  s  .co m*/
 *
 * @param byteBufferArr
 * @return byte[] key.
 */
public static byte[] packByteBufferIntoSingleByteArray(ByteBuffer[] byteBufferArr) {
    // for empty array means there is no data to remove dictionary.
    if (null == byteBufferArr || byteBufferArr.length == 0) {
        return null;
    }
    int noOfCol = byteBufferArr.length;
    short offsetLen = (short) (noOfCol * 2);
    int totalBytes = calculateTotalBytes(byteBufferArr) + offsetLen;
    ByteBuffer buffer = ByteBuffer.allocate(totalBytes);
    // writing the offset of the first element.
    buffer.putShort(offsetLen);

    // prepare index for byte []
    for (int index = 0; index < byteBufferArr.length - 1; index++) {
        ByteBuffer individualCol = byteBufferArr[index];
        int noOfBytes = individualCol.capacity();
        buffer.putShort((short) (offsetLen + noOfBytes));
        offsetLen += noOfBytes;
        individualCol.rewind();
    }

    // put actual data.
    for (int index = 0; index < byteBufferArr.length; index++) {
        ByteBuffer individualCol = byteBufferArr[index];
        buffer.put(individualCol.array());
    }

    buffer.rewind();
    return buffer.array();

}

From source file:com.bittorrent.mpetazzoni.client.ConnectionHandler.java

/**
 * Validate an expected handshake on a connection.
 *
 * <p>/*from w w  w  .  j  a  v a2 s.c  o m*/
 * Reads an expected handshake message from the given connected socket,
 * parses it and validates that the torrent hash_info corresponds to the
 * torrent we're sharing, and that the peerId matches the peer ID we expect
 * to see coming from the remote peer.
 * </p>
 *
 * @param channel The connected socket channel to the remote peer.
 * @param peerId The peer ID we expect in the handshake. If <em>null</em>,
 * any peer ID is accepted (this is the case for incoming connections).
 * @return The validated handshake message object.
 */
private Handshake validateHandshake(SocketChannel channel, byte[] peerId) throws IOException, ParseException {
    ByteBuffer len = ByteBuffer.allocate(1);
    ByteBuffer data;

    // Read the handshake from the wire
    logger.trace("Reading handshake size (1 byte) from {}...", this.socketRepr(channel));
    if (channel.read(len) < len.capacity()) {
        throw new IOException("Handshake size read underrrun");
    }

    len.rewind();
    int pstrlen = len.get();

    data = ByteBuffer.allocate(Handshake.BASE_HANDSHAKE_LENGTH + pstrlen);
    data.put((byte) pstrlen);
    int expected = data.remaining();
    int read = channel.read(data);
    if (read < expected) {
        throw new IOException("Handshake data read underrun (" + read + " < " + expected + " bytes)");
    }

    // Parse and check the handshake
    data.rewind();
    Handshake hs = Handshake.parse(data);
    if (!Arrays.equals(hs.getInfoHash(), this.torrent.getInfoHash())) {
        throw new ParseException("Handshake for unknow torrent "
                + Torrent.byteArrayToHexString(hs.getInfoHash()) + " from " + this.socketRepr(channel) + ".",
                pstrlen + 9);
    }

    if (peerId != null && !Arrays.equals(hs.getPeerId(), peerId)) {
        throw new ParseException(
                "Announced peer ID " + Torrent.byteArrayToHexString(hs.getPeerId())
                        + " did not match expected peer ID " + Torrent.byteArrayToHexString(peerId) + ".",
                pstrlen + 29);
    }

    return hs;
}