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:org.apache.hadoop.hbase.ipc.CellBlockBuilder.java

/**
 * Puts CellScanner Cells into a cell block using passed in <code>codec</code> and/or
 * <code>compressor</code>./*  www. j a v a 2s  .com*/
 * @param codec
 * @param compressor
 * @param cellScanner
 * @return Null or byte buffer filled with a cellblock filled with passed-in Cells encoded using
 *         passed in <code>codec</code> and/or <code>compressor</code>; the returned buffer has
 *         been flipped and is ready for reading. Use limit to find total size.
 * @throws IOException
 */
public ByteBuffer buildCellBlock(final Codec codec, final CompressionCodec compressor,
        final CellScanner cellScanner) throws IOException {
    ByteBufferOutputStreamSupplier supplier = new ByteBufferOutputStreamSupplier();
    if (buildCellBlock(codec, compressor, cellScanner, supplier)) {
        ByteBuffer bb = supplier.baos.getByteBuffer();
        // If no cells, don't mess around. Just return null (could be a bunch of existence checking
        // gets or something -- stuff that does not return a cell).
        return bb.hasRemaining() ? bb : null;
    } else {
        return null;
    }
}

From source file:io.github.dsheirer.record.wave.WaveWriter.java

/**
 * Opens a new data chunk if a data chunk is not currently open.  This method can be invoked repeatedly as an
 * assurance that the data chunk header has been written.
 *
 * @throws IOException if there is an error writing the data chunk header.
 *//*w  ww .j a  v  a2s. c o  m*/
private void openDataChunk() throws IOException {
    if (!mDataChunkOpen) {
        if (mFileChannel.size() + 32 >= mMaxSize) {
            rollover();
        }

        ByteBuffer formatChunk = getFormatChunk(mAudioFormat);
        formatChunk.position(0);

        while (formatChunk.hasRemaining()) {
            mFileChannel.write(formatChunk);
        }

        ByteBuffer dataHeader = getDataHeader();
        dataHeader.position(0);

        while (dataHeader.hasRemaining()) {
            mFileChannel.write(dataHeader);
        }

        mDataChunkSizeOffset = mFileChannel.size() - 4;
        mDataChunkSize = 0;
        mDataChunkOpen = true;

        updateTotalSize();
    }
}

From source file:org.wso2.andes.tools.messagestore.commands.Dump.java

protected List<List> createMessageData(java.util.List<Long> msgids, List<QueueEntry> messages,
        boolean showHeaders, boolean showRouting, boolean showMessageHeaders) {

    List<List> display = new LinkedList<List>();

    List<String> hex = new LinkedList<String>();
    List<String> ascii = new LinkedList<String>();
    display.add(hex);//from   ww  w  .  ja v  a 2  s . c o  m
    display.add(ascii);

    for (QueueEntry entry : messages) {
        ServerMessage msg = entry.getMessage();
        if (!includeMsg(msg, msgids)) {
            continue;
        }

        //Add divider between messages
        hex.add(Console.ROW_DIVIDER);
        ascii.add(Console.ROW_DIVIDER);

        // Show general message information
        hex.add(Show.Columns.ID.name());
        ascii.add(msg.getMessageNumber().toString());

        hex.add(Console.ROW_DIVIDER);
        ascii.add(Console.ROW_DIVIDER);

        if (showRouting) {
            addShowInformation(hex, ascii, msg, "Routing Details", true, false, false);
        }
        if (showHeaders) {
            addShowInformation(hex, ascii, msg, "Headers", false, true, false);
        }
        if (showMessageHeaders) {
            addShowInformation(hex, ascii, msg, null, false, false, true);
        }

        // Add Content Body section
        hex.add("Content Body");
        ascii.add("");
        hex.add(Console.ROW_DIVIDER);
        ascii.add(Console.ROW_DIVIDER);

        final int messageSize = (int) msg.getSize();
        if (messageSize != 0) {
            hex.add("Hex");
            hex.add(Console.ROW_DIVIDER);

            ascii.add("ASCII");
            ascii.add(Console.ROW_DIVIDER);

            java.nio.ByteBuffer buf = java.nio.ByteBuffer.allocate(64 * 1024);

            int position = 0;

            while (position < messageSize) {

                position += msg.getContent(buf, position);
                buf.flip();
                //Duplicate so we don't destroy original data :)
                java.nio.ByteBuffer hexBuffer = buf;

                java.nio.ByteBuffer charBuffer = hexBuffer.duplicate();

                Hex hexencoder = new Hex();

                while (hexBuffer.hasRemaining()) {
                    byte[] line = new byte[LINE_SIZE];

                    int bufsize = hexBuffer.remaining();
                    if (bufsize < LINE_SIZE) {
                        hexBuffer.get(line, 0, bufsize);
                    } else {
                        bufsize = line.length;
                        hexBuffer.get(line);
                    }

                    byte[] encoded = hexencoder.encode(line);

                    try {
                        String encStr = new String(encoded, 0, bufsize * 2, DEFAULT_ENCODING);
                        String hexLine = "";

                        int strLength = encStr.length();
                        for (int c = 0; c < strLength; c++) {
                            hexLine += encStr.charAt(c);

                            if ((c & 1) == 1 && SPACE_BYTES) {
                                hexLine += BYTE_SPACER;
                            }
                        }

                        hex.add(hexLine);
                    } catch (UnsupportedEncodingException e) {
                        _console.println(e.getMessage());
                        return null;
                    }
                }

                while (charBuffer.hasRemaining()) {
                    String asciiLine = "";

                    for (int pos = 0; pos < LINE_SIZE; pos++) {
                        if (charBuffer.hasRemaining()) {
                            byte ch = charBuffer.get();

                            if (isPrintable(ch)) {
                                asciiLine += (char) ch;
                            } else {
                                asciiLine += NON_PRINTING_ASCII_CHAR;
                            }

                            if (SPACE_BYTES) {
                                asciiLine += BYTE_SPACER;
                            }
                        } else {
                            break;
                        }
                    }

                    ascii.add(asciiLine);
                }
                buf.clear();
            }
        } else {
            List<String> result = new LinkedList<String>();

            display.add(result);
            result.add("No ContentBodies");
        }
    }

    // if hex is empty then we have no data to display
    if (hex.size() == 0) {
        return null;
    }

    return display;
}

From source file:org.cloudata.core.commitlog.pipe.Bulk.java

public OperationResult write(SocketChannel ch) throws IOException {
    if (bufferList.size() == 0) {
        throw new IOException("Pipe is closed");
    }/*  ww w  . j  a v  a  2  s  .c o  m*/

    int numWritten = 0;

    while (true) {
        ByteBuffer readBuf = bufferList.get(currentWriteBufIndex);
        ByteBuffer writeBuffer = readBuf.duplicate();
        writeBuffer.position(writtenPos);
        writeBuffer.limit(readBuf.position());

        numWritten = ch.write(writeBuffer);

        writtenPos += numWritten;
        totalNumWritten += numWritten;

        if (writeBuffer.hasRemaining()) {
            return OperationResult.partially;
        }

        //LOG.info("totalNumWritten : " + totalNumWritten + ", totalNumRead : " + totalNumRead);
        if (totalNumWritten < totalNumRead) {
            if (currentWriteBufIndex < currentReadBufIndex) {
                currentWriteBufIndex++;
                writtenPos = 0;
            } else {
                return OperationResult.partially;
            }
        } else {
            return OperationResult.completed;
        }
    }
}

From source file:org.springframework.messaging.simp.stomp.StompDecoder.java

private void readHeaders(ByteBuffer byteBuffer, StompHeaderAccessor headerAccessor) {
    while (true) {
        ByteArrayOutputStream headerStream = new ByteArrayOutputStream(256);
        boolean headerComplete = false;
        while (byteBuffer.hasRemaining()) {
            if (tryConsumeEndOfLine(byteBuffer)) {
                headerComplete = true;//  ww w  .java  2 s.c o m
                break;
            }
            headerStream.write(byteBuffer.get());
        }
        if (headerStream.size() > 0 && headerComplete) {
            String header = new String(headerStream.toByteArray(), StandardCharsets.UTF_8);
            int colonIndex = header.indexOf(':');
            if (colonIndex <= 0) {
                if (byteBuffer.remaining() > 0) {
                    throw new StompConversionException(
                            "Illegal header: '" + header + "'. A header must be of the form <name>:[<value>].");
                }
            } else {
                String headerName = unescape(header.substring(0, colonIndex));
                String headerValue = unescape(header.substring(colonIndex + 1));
                try {
                    headerAccessor.addNativeHeader(headerName, headerValue);
                } catch (InvalidMimeTypeException ex) {
                    if (byteBuffer.remaining() > 0) {
                        throw ex;
                    }
                }
            }
        } else {
            break;
        }
    }
}

From source file:org.exist.versioning.svn.core.internal.io.fs.FSFile.java

public int read(ByteBuffer target) throws IOException {
    int read = 0;
    while (target.hasRemaining()) {
        if (fill() < 0) {
            return read > 0 ? read : -1;
        }//  w ww .j  ava  2  s. com
        myBuffer.position((int) (myPosition - myBufferPosition));

        int couldRead = Math.min(myBuffer.remaining(), target.remaining());
        int readFrom = myBuffer.position() + myBuffer.arrayOffset();
        target.put(myBuffer.array(), readFrom, couldRead);
        if (myDigest != null) {
            myDigest.update(myBuffer.array(), readFrom, couldRead);
        }
        myPosition += couldRead;
        read += couldRead;
        myBuffer.position(myBuffer.position() + couldRead);
    }
    return read;
}

From source file:com.newatlanta.appengine.nio.channels.GaeFileChannel.java

@Override
public synchronized int write(ByteBuffer src) throws IOException {
    checkWriteOptions();/*from w ww  .  j  av a  2 s  . c  o m*/
    int bytesWritten = 0;
    while (src.hasRemaining()) {
        int r = src.remaining();
        initBuffer(r);
        if (calcBlockIndex(position + r - 1) == index) {
            // writing entirely within current block
            bytesWritten += writeBuffer(src);
        } else {
            // fill the current block then repeat loop
            int limit = src.limit();
            src.limit(src.position() + (blockSize - buffer.position()));
            bytesWritten += writeBuffer(src);
            src.limit(limit);
        }
    }
    //flush();
    return bytesWritten;
}

From source file:org.celstec.arlearn2.upload.BlobStoreServlet.java

private BlobKey storeBlob(String contentType, String fileName, InputStream stream) throws IOException {
    FileService fileService = FileServiceFactory.getFileService();
    AppEngineFile file = fileService.createNewBlobFile(contentType, fileName);

    boolean lock = true;
    FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
    ByteBuffer buf = ByteBuffer.allocateDirect(10);

    byte[] bytes = new byte[1024];
    int count = 0;
    int index = 0;

    // Continue writing bytes until there are no more
    while (count >= 0) {
        if (index == count) {
            count = stream.read(bytes);//from w w w .j a v a2  s.c o  m
            index = 0;
        }
        // Fill ByteBuffer
        while (index < count && buf.hasRemaining()) {
            buf.put(bytes[index++]);
        }

        // Set the limit to the current position and the
        // position to 0
        // making the new bytes visible for write()
        buf.flip();

        // Write the bytes to the channel
        int numWritten = writeChannel.write(buf);

        // Check if all bytes were written
        if (buf.hasRemaining()) {
            buf.compact();
        } else {
            buf.clear();
        }
    }

    writeChannel.closeFinally();
    return fileService.getBlobKey(file);
}

From source file:org.celstec.arlearn2.upload.BlobStoreServletIncremental.java

private AppEngineFile storeBlob(String contentType, String fileName, InputStream stream, boolean last,
        String serverPath) throws IOException {

    AppEngineFile file;//from   w w w  .jav  a  2s .  co m
    if (serverPath == null) {
        file = fileService.createNewBlobFile(contentType, fileName);
    } else {
        file = new AppEngineFile(serverPath);
    }

    //      boolean lock = true;
    log.warning("last is" + last + "file fullpath " + file.getFullPath());
    FileWriteChannel writeChannel = fileService.openWriteChannel(file, last);
    ByteBuffer buf = ByteBuffer.allocateDirect(10);

    byte[] bytes = new byte[1024];
    int count = 0;
    int index = 0;

    // Continue writing bytes until there are no more
    while (count >= 0) {
        if (index == count) {
            count = stream.read(bytes);
            index = 0;
        }
        // Fill ByteBuffer
        while (index < count && buf.hasRemaining()) {
            buf.put(bytes[index++]);
        }

        // Set the limit to the current position and the
        // position to 0
        // making the new bytes visible for write()
        buf.flip();

        // Write the bytes to the channel
        int numWritten = writeChannel.write(buf);

        // Check if all bytes were written
        if (buf.hasRemaining()) {
            buf.compact();
        } else {
            buf.clear();
        }
    }
    writeChannel.close();
    if (last)
        writeChannel.closeFinally();
    return file;
    //      return fileService.getBlobKey(file);
}

From source file:com.openteach.diamond.network.waverider.session.DefaultSession.java

@Override
public void onWrite() throws IOException {
    logger.debug("onWrite");
    int count = 0;
    Command command = null;/*  www.j ava 2 s .  c  o m*/
    Packet packet = null;
    ByteBuffer data = null;
    while ((command = outputBuffer.poll()) != null) {
        packet = Packet.newDataPacket(command);
        data = packet.marshall();
        count += data.remaining();
        while (data.hasRemaining()) {
            channel.write(data);
        }
        // flush
        channel.socket().getOutputStream().flush();
    }

    //logger.info("Session is onWrite, write " + count + " bytes");
}