Example usage for java.nio ByteBuffer position

List of usage examples for java.nio ByteBuffer position

Introduction

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

Prototype

public final int position() 

Source Link

Document

Returns the position of this buffer.

Usage

From source file:gda.device.scannable.keyence.Keyence.java

/**
 * Send command to the server.//from w w  w .  ja  v a2s.  c o  m
 * 
 * @param msg
 *            an unterminated command
 * @param expectedReplyItems 
 * @return the reply string.
 * @throws DeviceException
 */
public Object[] processImageRequest(String msg, int expectedReplyItems) throws DeviceException {
    if (expectedReplyItems < 2)
        throw new IllegalArgumentException("need at least two values for images (length definition and data)");
    String command = msg + '\r';
    Object reply[] = new Object[expectedReplyItems + 1];
    logger.debug(getName() + ": sent command: " + msg);
    synchronized (socketAccessLock) {
        try {
            if (!isConnected()) {
                throw new DeviceException("not connected");
            }
            cleanPipe();
            socketChannel.write(encoder.encode(CharBuffer.wrap(command)));

            ByteBuffer singleByte = ByteBuffer.allocate(1);

            StringBuilder sb = new StringBuilder();
            int argCounter = 0;
            while (argCounter < expectedReplyItems) {
                singleByte.clear();
                socketChannel.socket().setSoTimeout(socketTimeOut);
                socketChannel.configureBlocking(true);
                while (singleByte.position() == 0)
                    socketChannel.read(singleByte);
                singleByte.flip();
                String c = decoder.decode(singleByte).toString();
                logger.debug(c.toString());
                if (c.equals(",")) {
                    reply[argCounter] = sb.toString();
                    sb = new StringBuilder();
                    argCounter++;
                } else if (c.equals("\r")) {
                    throw new DeviceException(
                            "sendCommand: not enough data for image received - suspect an error");
                } else {
                    sb.append(c);
                }
            }

            int imageLength = Integer.parseInt(reply[expectedReplyItems - 1].toString());

            byte[] imageData = new byte[imageLength];
            ByteBuffer bybu = ByteBuffer.wrap(imageData);

            while (bybu.remaining() != 0) {
                socketChannel.read(bybu);
            }

            reply[expectedReplyItems] = imageData;
        } catch (SocketTimeoutException ex) {
            throw new DeviceException("sendCommand read timeout " + ex.getMessage(), ex);
        } catch (IOException ex) {
            // treat as fatal
            connected = false;
            throw new DeviceException("sendCommand: " + ex.getMessage(), ex);
        }
    }
    return reply;
}

From source file:eu.stratosphere.nephele.services.iomanager.IOManagerPerformanceBenchmark.java

@SuppressWarnings("resource")
private final void speedTestNIO(int bufferSize, boolean direct) throws IOException {
    final Channel.ID tmpChannel = ioManager.createChannel();

    File tempFile = null;/*from w ww  .  j  ava 2  s . c o m*/
    FileChannel fs = null;

    try {
        tempFile = new File(tmpChannel.getPath());

        RandomAccessFile raf = new RandomAccessFile(tempFile, "rw");
        fs = raf.getChannel();

        ByteBuffer buf = direct ? ByteBuffer.allocateDirect(bufferSize) : ByteBuffer.allocate(bufferSize);

        long writeStart = System.currentTimeMillis();

        int valsLeft = NUM_INTS_WRITTEN;
        while (valsLeft-- > 0) {
            if (buf.remaining() < 4) {
                buf.flip();
                fs.write(buf);
                buf.clear();
            }
            buf.putInt(valsLeft);
        }

        if (buf.position() > 0) {
            buf.flip();
            fs.write(buf);
        }

        fs.close();
        raf.close();
        fs = null;

        long writeElapsed = System.currentTimeMillis() - writeStart;

        // ----------------------------------------------------------------

        raf = new RandomAccessFile(tempFile, "r");
        fs = raf.getChannel();
        buf.clear();

        long readStart = System.currentTimeMillis();

        fs.read(buf);
        buf.flip();

        valsLeft = NUM_INTS_WRITTEN;
        while (valsLeft-- > 0) {
            if (buf.remaining() < 4) {
                buf.compact();
                fs.read(buf);
                buf.flip();
            }
            if (buf.getInt() != valsLeft) {
                throw new IOException();
            }
        }

        fs.close();
        raf.close();

        long readElapsed = System.currentTimeMillis() - readStart;

        LOG.info("NIO Channel with buffer " + bufferSize + ": write " + writeElapsed + " msecs, read "
                + readElapsed + " msecs.");
    } finally {
        // close if possible
        if (fs != null) {
            fs.close();
            fs = null;
        }
        // try to delete the file
        if (tempFile != null) {
            tempFile.delete();
        }
    }
}

From source file:com.amazonaws.http.UrlHttpClient.java

/**
 * Writes the content (if any) of the request to the passed connection
 *
 * @param request/*www.  j  a  v a  2s  .c  o m*/
 * @param connection
 * @param curlBuilder
 * @throws IOException
 */
void writeContentToConnection(final HttpRequest request, final HttpURLConnection connection,
        final CurlBuilder curlBuilder) throws IOException {
    // Note: if DoOutput is set to true and method is GET, HttpUrlConnection
    // will silently change the method to POST.
    if (request.getContent() != null && request.getContentLength() >= 0) {
        connection.setDoOutput(true);
        // This is for backward compatibility, because
        // setFixedLengthStreamingMode(long) is available in API level 19.
        if (!request.isStreaming()) {
            connection.setFixedLengthStreamingMode((int) request.getContentLength());
        }
        final OutputStream os = connection.getOutputStream();
        ByteBuffer curlBuffer = null;
        if (curlBuilder != null) {
            if (request.getContentLength() < Integer.MAX_VALUE) {
                curlBuffer = ByteBuffer.allocate((int) request.getContentLength());
            } else {
                curlBuilder.setContentOverflow(true);
            }
        }
        write(request.getContent(), os, curlBuilder, curlBuffer);
        if (curlBuilder != null && curlBuffer != null && curlBuffer.position() != 0) {
            // has content
            curlBuilder.setContent(new String(curlBuffer.array(), "UTF-8"));
        }
        os.flush();
        os.close();
    }
}

From source file:bamboo.openhash.fileshare.FileShare.java

public void write() {
    logger.debug("write");

    if (is != null) {
        while (ready.size() < MAX_BUFFER) {
            ByteBuffer bb = ByteBuffer.wrap(new byte[1024]);
            bb.putInt(0);//from www.ja va 2  s  . com
            int len = 0;
            try {
                len = is.read(bb.array(), 4, bb.limit() - 4);
            } catch (IOException e) {
                is = null;
                break;
            }
            if (len == -1) {
                is = null;
                break;
            }
            logger.debug("position=" + bb.position() + " read " + len + " bytes");
            // We're going to flip this later, so set the position
            // where we want the limit to end up.
            bb.position(len + 4);
            wblocks.elementAt(0).addLast(bb);
            logger.debug("read a block");
            if (wblocks.elementAt(0).size() == BRANCHING)
                make_parents(false);
        }
        if (is == null) {
            make_parents(true);
            // There should now be only one non-empty level, at it
            // should have exactly one block in it.
            for (int l = 0; l < wblocks.size(); ++l) {
                if (!wblocks.elementAt(l).isEmpty()) {
                    ByteBuffer bb = wblocks.elementAt(l).removeFirst();
                    bb.flip();
                    md.update(secret);
                    md.update(bb.array(), 0, bb.limit());
                    byte[] dig = md.digest();
                    StringBuffer sb = new StringBuffer(100);
                    bytes_to_sbuf(dig, 0, dig.length, false, sb);
                    logger.info("root digest is 0x" + sb.toString());
                    ready.addLast(new Pair<byte[], ByteBuffer>(dig, bb));
                    break;
                }
            }
        }
    }

    // Do put.

    if (ready.isEmpty()) {
        if (outstanding == 0) {
            logger.info("all puts finished successfully");
            System.exit(0);
        }
    } else {
        Pair<byte[], ByteBuffer> head = ready.removeFirst();
        outstanding++;

        bamboo_put_args put = new bamboo_put_args();
        put.application = APPLICATION;
        // GatewayClient will fill in put.client_library
        put.value = new bamboo_value();
        if (head.second.limit() == head.second.array().length)
            put.value.value = head.second.array();
        else {
            put.value.value = new byte[head.second.limit()];
            head.second.get(put.value.value);
        }
        put.key = new bamboo_key();
        put.key.value = head.first;
        put.ttl_sec = 3600; // TODO

        StringBuffer sb = new StringBuffer(100);
        bytes_to_sbuf(head.first, 0, head.first.length, false, sb);
        logger.debug("putting block size=" + put.value.value.length + " key=0x" + sb.toString());
        client.put(put, curry(put_done_cb, put));
    }
}

From source file:org.archive.modules.recrawl.wbm.WbmPersistLoadProcessor.java

protected HashMap<String, Object> getLastCrawl(InputStream is) throws IOException {
    // read CDX lines, save most recent (at the end) hash.
    ByteBuffer buffer = ByteBuffer.allocate(32);
    ByteBuffer tsbuffer = ByteBuffer.allocate(14);
    int field = 0;
    int c;//from   w  w w .j  av  a 2  s  .  c  o m
    do {
        c = is.read();
        if (field == 1) {
            // 14-digits timestamp
            tsbuffer.clear();
            while (Character.isDigit(c) && tsbuffer.remaining() > 0) {
                tsbuffer.put((byte) c);
                c = is.read();
            }
            if (c != ' ' || tsbuffer.position() != 14) {
                tsbuffer.clear();
            }
            // fall through to skip the rest
        } else if (field == 5) {
            buffer.clear();
            while ((c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') && buffer.remaining() > 0) {
                buffer.put((byte) c);
                c = is.read();
            }
            if (c != ' ' || buffer.position() != 32) {
                buffer.clear();
            }
            // fall through to skip the rest
        }
        while (true) {
            if (c == -1) {
                break;
            } else if (c == '\n') {
                field = 0;
                break;
            } else if (c == ' ') {
                field++;
                break;
            }
            c = is.read();
        }
    } while (c != -1);

    HashMap<String, Object> info = new HashMap<String, Object>();
    if (buffer.remaining() == 0) {
        info.put(RecrawlAttributeConstants.A_CONTENT_DIGEST, contentDigestScheme + new String(buffer.array()));
    }
    if (tsbuffer.remaining() == 0) {
        try {
            long ts = DateUtils.parse14DigitDate(new String(tsbuffer.array())).getTime();
            // A_TIMESTAMP has been used for sorting history long before A_FETCH_BEGAN_TIME
            // field was introduced. Now FetchHistoryProcessor fails if A_FETCH_BEGAN_TIME is
            // not set. We could stop storing A_TIMESTAMP and sort by A_FETCH_BEGAN_TIME.
            info.put(FetchHistoryHelper.A_TIMESTAMP, ts);
            info.put(CoreAttributeConstants.A_FETCH_BEGAN_TIME, ts);
        } catch (ParseException ex) {
        }
    }
    return info.isEmpty() ? null : info;
}

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

@Override
public synchronized int write(ByteBuffer src) throws IOException {
    checkWriteOptions();// w  w w  . jav  a2s .  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:de.rwhq.btree.InnerNode.java

/**
 * @param serializedKey/*from www  . jav  a 2 s  . co  m*/
 * @param pageId
 * @param posOfKeyForInsert
 */
private void insertKeyPointerPageIdAtPosition(final byte[] serializedKey, final Integer pageId,
        final int posOfKeyForInsert) {

    final KeyStruct thisKeyStruct = new KeyStruct(posOfKeyForInsert);
    final ByteBuffer buf = rawPage().bufferForWriting(thisKeyStruct.getOffset());

    final int spaceNeededForInsert = getSizeOfPageId() + keySerializer.getSerializedLength();
    System.arraycopy(buf.array(), buf.position(), buf.array(), buf.position() + spaceNeededForInsert,
            buf.limit() - buf.position() - spaceNeededForInsert);

    buf.put(serializedKey);
    buf.putInt(pageId);

    setNumberOfKeys(getNumberOfKeys() + 1);
    rawPage().sync();
}

From source file:com.l2jfree.network.mmocore.ReadWriteThread.java

private boolean tryReadPacket2(T con, ByteBuffer buf) {
    // check if header could be processed
    if (buf.remaining() >= 2) {
        // parse all headers and get expected packet size
        final int size = (buf.getChar() - PACKET_HEADER_SIZE);

        // do we got enough bytes for the packet?
        if (size <= buf.remaining()) {
            // avoid parsing dummy packets (packets without body)
            if (size > 0) {
                int pos = buf.position();
                parseClientPacket(buf, size, con);
                buf.position(pos + size);
            } else {
                // let's report error to trigger protection
                getMMOController().report(ErrorMode.EMPTY_PACKET, con, null, null);
            }//  www  . ja  va 2s. c  o  m

            return true;
        } else {
            // we dont have enough bytes for the packet so we need to read and revert the header
            buf.position(buf.position() - PACKET_HEADER_SIZE);
            return false;
        }
    } else {
        // we dont have enough data for header so we need to read
        return false;
    }
}

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/*w  w  w  .  j a  v a2  s . c  o m*/
 * @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:de.rwhq.btree.LeafNode.java

/**
 * @param key//from  w  w w  .j  a v a2s  . c om
 * @param takeNext
 *       boolean, whether if the key was not found the next higher key should be taken
 * @return position to set the buffer to, where the key starts, -1 if key not found
 */
private int offsetOfKey(final K key, final boolean takeNext) {

    final byte[] pointerBuf = new byte[valueSerializer.getSerializedLength()];
    final byte[] keyBuf = new byte[keySerializer.getSerializedLength()];

    final ByteBuffer buffer = rawPage().bufferForReading(Header.size());

    for (int i = 0; i < getNumberOfEntries(); i++) {

        buffer.get(keyBuf);

        final int compResult = comparator.compare(keySerializer.deserialize(keyBuf), key);

        if (compResult == 0) {
            return buffer.position() - keySerializer.getSerializedLength();
        } else if (compResult > 0) {
            if (takeNext)
                return buffer.position() - keySerializer.getSerializedLength();
            else
                return NOT_FOUND;
        }

        // if compresult < 0:
        // get the data pointer but do nothing with it
        buffer.get(pointerBuf);
    }
    return NOT_FOUND;
}