Example usage for java.nio ByteBuffer hasRemaining

List of usage examples for java.nio ByteBuffer hasRemaining

Introduction

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

Prototype

public final boolean hasRemaining() 

Source Link

Document

Indicates if there are elements remaining in this buffer, that is if position < limit .

Usage

From source file:com.glaf.core.util.ByteBufferUtils.java

public static InputStream inputStream(ByteBuffer bytes) {
    final ByteBuffer copy = bytes.duplicate();

    return new InputStream() {
        public int read() throws IOException {
            if (!copy.hasRemaining())
                return -1;

            return copy.get() & 0xFF;
        }//from  w ww  .j a  v  a 2 s  .  co m

        @Override
        public int read(byte[] bytes, int off, int len) throws IOException {
            if (!copy.hasRemaining())
                return -1;

            len = Math.min(len, copy.remaining());
            copy.get(bytes, off, len);
            return len;
        }

        @Override
        public int available() throws IOException {
            return copy.remaining();
        }
    };
}

From source file:com.flexive.shared.FxFileUtils.java

/**
 * Copy data from source to destination nio channel
 *
 * @param source      source channel/*from   w  w w.j  a v  a  2 s .  c om*/
 * @param destination destination channel
 * @return total number of bytes copied
 * @throws java.io.IOException on errors
 */
public static long copyNIOChannel(ReadableByteChannel source, WritableByteChannel destination)
        throws IOException {
    ByteBuffer xferBuffer = ByteBuffer.allocateDirect(4096);
    long count = 0, read, written;
    while (true) {
        read = source.read(xferBuffer);
        if (read < 0)
            return count;
        xferBuffer.flip();
        written = destination.write(xferBuffer);
        if (written > 0) {
            count += written;
            if (xferBuffer.hasRemaining())
                xferBuffer.compact();
            else
                xferBuffer.clear();
        } else {
            while (xferBuffer.hasRemaining()) {
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    LOG.warn(e);
                }
                written = destination.write(xferBuffer);
                if (written > 0) {
                    count += written;
                    if (xferBuffer.hasRemaining())
                        xferBuffer.compact();
                }
            }
            if (!xferBuffer.hasRemaining())
                xferBuffer.clear();
        }
    }
}

From source file:org.cryptomator.ui.util.SingleInstanceManager.java

/**
 * tries to fill the given buffer for the given time
 * //from w  w  w.j a  v a 2s  . co  m
 * @param channel
 * @param buf
 * @param timeout
 * @throws ClosedChannelException
 * @throws IOException
 */
public static <T extends SelectableChannel & ReadableByteChannel> void tryFill(T channel, final ByteBuffer buf,
        int timeout) throws IOException {
    if (channel.isBlocking()) {
        throw new IllegalStateException("Channel is in blocking mode.");
    }

    try (Selector selector = Selector.open()) {
        channel.register(selector, SelectionKey.OP_READ);

        TimeoutTask.attempt(remainingTime -> {
            if (!buf.hasRemaining()) {
                return true;
            }
            if (selector.select(remainingTime) > 0) {
                if (channel.read(buf) < 0) {
                    return true;
                }
            }
            return !buf.hasRemaining();
        }, timeout, 1);
    }
}

From source file:org.apache.cassandra.jmeter.AbstractCassandaTestElement.java

private static String bytesToHex(ByteBuffer bb) {
    char[] hexChars = new char[bb.remaining() * 2];
    int j = 0;/*from  w  w w  . ja  v a 2 s.  c o m*/
    while (bb.hasRemaining()) {
        int v = bb.get() & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        j++;
    }

    return "0x" + new String(hexChars);
}

From source file:com.mgmtp.perfload.perfalyzer.util.IoUtilities.java

public static void writeToChannel(final WritableByteChannel destChannel, final ByteBuffer buffer) {
    try {/*from w w w  .j  av  a  2  s .  com*/
        // write to the destination channel
        destChannel.write(buffer);

        // If partial transfer, shift remainder down so it does not get lost
        // If buffer is empty, this is the same as calling clear()
        buffer.compact();

        // EOF will leave buffer in fill state
        buffer.flip();

        // make sure the buffer is fully drained
        while (buffer.hasRemaining()) {
            destChannel.write(buffer);
        }
    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    }
}

From source file:com.healthmarketscience.jackcess.impl.OleUtil.java

private static String readZeroTermStr(ByteBuffer bb) {
    int off = bb.position();
    while (bb.hasRemaining()) {
        byte b = bb.get();
        if (b == 0) {
            break;
        }//ww w . jav a 2  s  .  c om
    }
    int len = bb.position() - off;
    return readStr(bb, off, len);
}

From source file:org.gephi.io.importer.api.ImportUtils.java

/**
 * Uncompress a GZIP file.//from  w w w .java  2s. c om
 */
public static File getGzFile(FileObject in, File out, boolean isTar) throws IOException {

    // Stream buffer
    final int BUFF_SIZE = 8192;
    final byte[] buffer = new byte[BUFF_SIZE];

    GZIPInputStream inputStream = null;
    FileOutputStream outStream = null;

    try {
        inputStream = new GZIPInputStream(new FileInputStream(in.getPath()));
        outStream = new FileOutputStream(out);

        if (isTar) {
            // Read Tar header
            int remainingBytes = readTarHeader(inputStream);

            // Read content
            ByteBuffer bb = ByteBuffer.allocateDirect(4 * BUFF_SIZE);
            byte[] tmpCache = new byte[BUFF_SIZE];
            int nRead, nGet;
            while ((nRead = inputStream.read(tmpCache)) != -1) {
                if (nRead == 0) {
                    continue;
                }
                bb.put(tmpCache);
                bb.position(0);
                bb.limit(nRead);
                while (bb.hasRemaining() && remainingBytes > 0) {
                    nGet = Math.min(bb.remaining(), BUFF_SIZE);
                    nGet = Math.min(nGet, remainingBytes);
                    bb.get(buffer, 0, nGet);
                    outStream.write(buffer, 0, nGet);
                    remainingBytes -= nGet;
                }
                bb.clear();
            }
        } else {
            int len;
            while ((len = inputStream.read(buffer)) > 0) {
                outStream.write(buffer, 0, len);
            }
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (outStream != null) {
            outStream.close();
        }
    }

    return out;
}

From source file:org.gephi.io.importer.api.ImportUtils.java

/**
 * Uncompress a Bzip2 file./*from  w  w w. j av  a 2  s . co  m*/
 */
public static File getBzipFile(FileObject in, File out, boolean isTar) throws IOException {

    // Stream buffer
    final int BUFF_SIZE = 8192;
    final byte[] buffer = new byte[BUFF_SIZE];

    BZip2CompressorInputStream inputStream = null;
    FileOutputStream outStream = null;

    try {
        FileInputStream is = new FileInputStream(in.getPath());
        inputStream = new BZip2CompressorInputStream(is);
        outStream = new FileOutputStream(out.getAbsolutePath());

        if (isTar) {
            // Read Tar header
            int remainingBytes = readTarHeader(inputStream);

            // Read content
            ByteBuffer bb = ByteBuffer.allocateDirect(4 * BUFF_SIZE);
            byte[] tmpCache = new byte[BUFF_SIZE];
            int nRead, nGet;
            while ((nRead = inputStream.read(tmpCache)) != -1) {
                if (nRead == 0) {
                    continue;
                }
                bb.put(tmpCache);
                bb.position(0);
                bb.limit(nRead);
                while (bb.hasRemaining() && remainingBytes > 0) {
                    nGet = Math.min(bb.remaining(), BUFF_SIZE);
                    nGet = Math.min(nGet, remainingBytes);
                    bb.get(buffer, 0, nGet);
                    outStream.write(buffer, 0, nGet);
                    remainingBytes -= nGet;
                }
                bb.clear();
            }
        } else {
            int len;
            while ((len = inputStream.read(buffer)) > 0) {
                outStream.write(buffer, 0, len);
            }
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
        if (outStream != null) {
            outStream.close();
        }
    }

    return out;
}

From source file:com.pavlospt.rxfile.RxFile.java

private static void fastChannelCopy(final ReadableByteChannel src, final WritableByteChannel dest)
        throws IOException {
    final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
    while (src.read(buffer) != -1) {
        buffer.flip();/* w w w .ja va 2  s .c  o  m*/
        dest.write(buffer);
        buffer.compact();
    }
    buffer.flip();
    while (buffer.hasRemaining()) {
        dest.write(buffer);
    }
}

From source file:net.pms.util.AudioUtils.java

private static void parseRealAudioMetaData(ByteBuffer buffer, DLNAMediaAudio audio, short version) {
    buffer.position(buffer.position() + (version == 4 ? 3 : 4)); // skip unknown
    byte b = buffer.get();
    if (b != 0) {
        byte[] title = new byte[Math.min(b & 0xFF, buffer.remaining())];
        buffer.get(title);/*from w  w w.  j  a v a 2  s.  co  m*/
        String titleString = new String(title, StandardCharsets.US_ASCII);
        audio.setSongname(titleString);
        audio.setAudioTrackTitleFromMetadata(titleString);
    }
    if (buffer.hasRemaining()) {
        b = buffer.get();
        if (b != 0) {
            byte[] artist = new byte[Math.min(b & 0xFF, buffer.remaining())];
            buffer.get(artist);
            audio.setArtist(new String(artist, StandardCharsets.US_ASCII));
        }
    }
}