Example usage for java.nio ByteBuffer remaining

List of usage examples for java.nio ByteBuffer remaining

Introduction

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

Prototype

public final int remaining() 

Source Link

Document

Returns the number of remaining elements in this buffer, that is limit - position .

Usage

From source file:org.apache.hadoop.mapred.nativetask.handlers.BufferPuller.java

@Override
public boolean receiveData() throws IOException {
    if (closed) {
        return false;
    }//from   w w  w  .j  a v a2  s .com

    final ByteBuffer input = inputBuffer.getByteBuffer();

    if (null != asideBuffer && asideBuffer.length() > 0) {
        if (asideBuffer.remaining() > 0) {
            final byte[] output = asideBuffer.getByteBuffer().array();
            final int write = Math.min(asideBuffer.remaining(), input.remaining());
            input.get(output, asideBuffer.position(), write);
            asideBuffer.position(asideBuffer.position() + write);
        }

        if (asideBuffer.remaining() == 0) {
            asideBuffer.position(0);
        }
    }

    if (input.remaining() == 0) {
        return true;
    }

    if (input.remaining() < KV_HEADER_LENGTH) {
        throw new IOException("incomplete data, input length is: " + input.remaining());
    }
    final int position = input.position();
    final int keyLength = input.getInt();
    final int valueLength = input.getInt();
    input.position(position);
    final int kvLength = keyLength + valueLength + KV_HEADER_LENGTH;
    final int remaining = input.remaining();

    if (kvLength > remaining) {
        if (null == asideBuffer || asideBuffer.capacity() < kvLength) {
            asideBuffer = new InputBuffer(BufferType.HEAP_BUFFER, kvLength);
        }
        asideBuffer.rewind(0, kvLength);

        input.get(asideBuffer.array(), 0, remaining);
        asideBuffer.position(remaining);
    }
    return true;
}

From source file:org.apache.usergrid.persistence.cassandra.CursorCache.java

/** Turn the cursor cache into a string */
public String asString() {
    /**//w w w.j a va2 s  .c  o m
     * No cursors to return
     */
    if (cursors.size() == 0) {
        return null;
    }

    StringBuffer buff = new StringBuffer();

    int nullCount = 0;
    ByteBuffer value = null;

    for (Entry<Integer, ByteBuffer> entry : cursors.entrySet()) {
        value = entry.getValue();

        buff.append(entry.getKey());
        buff.append(":");
        buff.append(encodeBase64URLSafeString(bytes(value)));
        buff.append("|");

        // this range was empty, mark it as a null
        if (value == null || value.remaining() == 0) {
            nullCount++;
        }
    }

    // all cursors are complete, return null
    if (nullCount == cursors.size()) {
        return null;
    }

    // trim off the last pipe
    buff.setLength(buff.length() - 1);

    return encodeBase64URLSafeString(buff.toString().getBytes());
}

From source file:org.openhab.binding.insteonplm.internal.driver.hub.HubIOStream.java

/**
 * Sends Insteon message (byte array) as a readable ascii string to the Hub
 * /*www.j a  va 2 s.c o  m*/
 * @param msg byte array representing the Insteon message
 * @throws IOException in case of I/O error
 */
public synchronized void write(ByteBuffer msg) throws IOException {
    poll(); // fetch the status buffer before we send out commands
    clearBuffer(); // clear the status buffer explicitly.

    StringBuilder b = new StringBuilder();
    while (msg.remaining() > 0) {
        b.append(String.format("%02x", msg.get()));
    }
    String hexMSG = b.toString();
    getURL("/3?" + hexMSG + "=I=3");
}

From source file:org.apache.james.protocols.api.handler.CommandDispatcher.java

/**
 * Parse the line into a {@link Request}
 * //from   ww  w. j a v  a  2s.c  o  m
 * @param session
 * @param line
 * @return request
 * @throws Exception
 */
protected Request parseRequest(Session session, ByteBuffer buffer) throws Exception {
    String curCommandName = null;
    String curCommandArgument = null;
    byte[] line;
    if (buffer.hasArray()) {
        line = buffer.array();
    } else {
        line = new byte[buffer.remaining()];
        buffer.get(line);
    }
    // This should be changed once we move to java6
    String cmdString = new String(line, session.getCharset().name()).trim();
    int spaceIndex = cmdString.indexOf(" ");
    if (spaceIndex > 0) {
        curCommandName = cmdString.substring(0, spaceIndex);
        curCommandArgument = cmdString.substring(spaceIndex + 1);
    } else {
        curCommandName = cmdString;
    }
    curCommandName = curCommandName.toUpperCase(Locale.US);

    return new BaseRequest(curCommandName, curCommandArgument);

}

From source file:android.pim.vcard.VCardDataBuilder.java

private String encodeString(String originalString, String targetCharset) {
    if (mSourceCharset.equalsIgnoreCase(targetCharset)) {
        return originalString;
    }/*w  w w.  ja v  a2 s.  c  o m*/
    Charset charset = Charset.forName(mSourceCharset);
    ByteBuffer byteBuffer = charset.encode(originalString);
    // byteBuffer.array() "may" return byte array which is larger than
    // byteBuffer.remaining(). Here, we keep on the safe side.
    byte[] bytes = new byte[byteBuffer.remaining()];
    byteBuffer.get(bytes);
    try {
        return new String(bytes, targetCharset);
    } catch (UnsupportedEncodingException e) {
        Log.e(LOG_TAG, "Failed to encode: charset=" + targetCharset);
        return null;
    }
}

From source file:com.facebook.infrastructure.net.UdpConnection.java

private byte[] gobbleHeaderAndExtractBody(ByteBuffer buffer) {
    byte[] body = ArrayUtils.EMPTY_BYTE_ARRAY;
    byte[] protocol = new byte[4];
    buffer = buffer.get(protocol, 0, protocol.length);
    int value = BasicUtilities.byteArrayToInt(protocol);

    if (protocol_ != value) {
        logger_.info("Invalid protocol header in the incoming message " + value);
        return body;
    }/*  www . jav a 2s.  c o m*/
    body = new byte[buffer.remaining()];
    buffer.get(body, 0, body.length);
    return body;
}

From source file:org.apache.hadoop.crypto.OpensslCipher.java

/**
 * Finishes a multiple-part operation. The data is encrypted or decrypted,
 * depending on how this cipher was initialized.
 * <p/>//from  w w  w  . j av  a  2 s. c  o m
 * 
 * The result is stored in the output buffer. Upon return, the output buffer's
 * position will have advanced by n, where n is the value returned by this
 * method; the output buffer's limit will not have changed.
 * <p/>
 * 
 * If <code>output.remaining()</code> bytes are insufficient to hold the result,
 * a <code>ShortBufferException</code> is thrown.
 * <p/>
 * 
 * Upon finishing, this method resets this cipher object to the state it was
 * in when previously initialized. That is, the object is available to encrypt
 * or decrypt more data.
 * <p/>
 * 
 * If any exception is thrown, this cipher object need to be reset before it 
 * can be used again.
 * 
 * @param output the output ByteBuffer
 * @return int number of bytes stored in <code>output</code>
 * @throws ShortBufferException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 */
public int doFinal(ByteBuffer output)
        throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
    checkState();
    Preconditions.checkArgument(output.isDirect(), "Direct buffer is required.");
    int len = doFinal(context, output, output.position(), output.remaining());
    output.position(output.position() + len);
    return len;
}

From source file:io.protostuff.JsonOutput.java

/**
 * Writes a ByteBuffer field./*from   w w w  .ja v  a2s  .c o m*/
 */
@Override
public void writeBytes(int fieldNumber, ByteBuffer value, boolean repeated) throws IOException {
    writeByteRange(false, fieldNumber, value.array(), value.arrayOffset() + value.position(), value.remaining(),
            repeated);
}

From source file:jext2.DataInode.java

/**
 * Write data in buffer to disk. This works best when whole blocks which
 * are a multiple of blocksize in size are written. Partial blocks are
 * written by first reading the block and then writing the new data
 * to that buffer than write that new buffer to disk.
 * @throws NoSpaceLeftOnDevice/*from   w  ww. ja  va2s .  com*/
 * @throws FileTooLarge
 */
public int writeData(ByteBuffer buf, long offset) throws JExt2Exception, NoSpaceLeftOnDevice, FileTooLarge {
    /*
     * Note on sparse file support:
     * getBlocksAllocate does not care if there are holes. Just write as much
     * blocks as the buffer requires at the desired location an set inode.size
     * accordingly.
     */

    int blocksize = superblock.getBlocksize();
    long start = offset / blocksize;
    long end = (buf.capacity() + blocksize) / blocksize + start;
    int startOff = (int) (offset % blocksize);

    if (startOff > 0)
        end += 1;

    buf.rewind();

    while (start < end) {
        LinkedList<Long> blockNrs = accessData().getBlocksAllocate(start, 1);
        int bytesLeft = buf.capacity() - buf.position();

        if (bytesLeft < blocksize || startOff > 0) { /* write partial block */
            ByteBuffer onDisk = blockAccess.read(blockNrs.getFirst());

            onDisk.position(startOff);

            assert onDisk.limit() == blocksize;

            buf.limit(buf.position() + Math.min(bytesLeft, onDisk.remaining()));

            onDisk.put(buf);

            onDisk.position(startOff);
            blockAccess.writeFromBufferUnsynchronized((blockNrs.getFirst() & 0xffffffff) * blocksize, onDisk);
        } else { /* write whole block */
            buf.limit(buf.position() + blocksize);

            blockAccess.writeFromBufferUnsynchronized((blockNrs.getFirst() & 0xffffffff) * blocksize, buf);
        }

        start += 1;
        startOff = 0;
        accessData().unlockHierarchyChanges();

    }
    int written = buf.position();
    assert written == buf.capacity();

    /* increase inode.size if we grew the file */
    if (offset + written > getSize()) { /* file grew */
        setStatusChangeTime(new Date());
        setSize(offset + written);
    }

    return written;
}

From source file:com.intel.chimera.codec.OpensslCipher.java

/**
 * Finishes a multiple-part operation. The data is encrypted or decrypted,
 * depending on how this cipher was initialized.
 * <p/>/*from  w ww  . j av a2  s  . com*/
 * 
 * The result is stored in the output buffer. Upon return, the output buffer's
 * position will have advanced by n, where n is the value returned by this
 * method; the output buffer's limit will not have changed.
 * <p/>
 * 
 * If <code>output.remaining()</code> bytes are insufficient to hold the result,
 * a <code>ShortBufferException</code> is thrown.
 * <p/>
 * 
 * Upon finishing, this method resets this cipher object to the state it was
 * in when previously initialized. That is, the object is available to encrypt
 * or decrypt more data.
 * <p/>
 * 
 * If any exception is thrown, this cipher object need to be reset before it 
 * can be used again.
 * 
 * @param output the output ByteBuffer
 * @return int number of bytes stored in <code>output</code>
 * @throws ShortBufferException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 */
public int doFinal(ByteBuffer output)
        throws ShortBufferException, IllegalBlockSizeException, BadPaddingException {
    checkState();
    Preconditions.checkArgument(output.isDirect(), "Direct buffer is required.");
    int len = OpensslCipherNative.doFinal(context, output, output.position(), output.remaining());
    output.position(output.position() + len);
    return len;
}