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.openteach.diamond.network.waverider.network.DefaultNetWorkClient.java

/**
 * ?, outputBuffer/*  w w w  .j a  v a2  s.c  om*/
 * ?
 * @param key
 * @throws IOException
 */
private void onWrite(SelectionKey key) throws IOException {
    logger.debug("onWrite");
    key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
    Command command = null;
    Packet packet = null;
    ByteBuffer data = null;
    //int size = 0;
    while ((command = outputBuffer.poll()) != null) {
        //size = 0;
        // ???
        packet = Packet.newDataPacket(command);
        // ???ByteBuffer
        data = packet.marshall();
        //size = data.remaining();
        while (data.hasRemaining()) {
            socketChannel.write(data);
        }
        socketChannel.socket().getOutputStream().flush();
        //logger.info("Slave write one packet, " + size + " bytes");
    }
    //key.interestOps(SelectionKey.OP_READ);
}

From source file:org.apache.arrow.vector.util.Text.java

/**
 * Finds any occurence of <code>what</code> in the backing buffer, starting as position <code>start</code>. The
 * starting position is measured in bytes and the return value is in terms of byte position in the buffer. The backing
 * buffer is not converted to a string for this operation.
 *
 * @return byte position of the first occurence of the search string in the UTF-8 buffer or -1 if not found
 *///from   w  ww.j a  va 2  s  .  c  o  m
public int find(String what, int start) {
    try {
        ByteBuffer src = ByteBuffer.wrap(this.bytes, 0, this.length);
        ByteBuffer tgt = encode(what);
        byte b = tgt.get();
        src.position(start);

        while (src.hasRemaining()) {
            if (b == src.get()) { // matching first byte
                src.mark(); // save position in loop
                tgt.mark(); // save position in target
                boolean found = true;
                int pos = src.position() - 1;
                while (tgt.hasRemaining()) {
                    if (!src.hasRemaining()) { // src expired first
                        tgt.reset();
                        src.reset();
                        found = false;
                        break;
                    }
                    if (!(tgt.get() == src.get())) {
                        tgt.reset();
                        src.reset();
                        found = false;
                        break; // no match
                    }
                }
                if (found) {
                    return pos;
                }
            }
        }
        return -1; // not found
    } catch (CharacterCodingException e) {
        // can't get here
        e.printStackTrace();
        return -1;
    }
}

From source file:org.apache.jackrabbit.oak.plugins.segment.Segment.java

/**
 * Writes this segment to the given output stream.
 *
 * @param stream stream to which this segment will be written
 * @throws IOException on an IO error/*from w ww .j a v  a2 s .  c o  m*/
 */
public void writeTo(OutputStream stream) throws IOException {
    ByteBuffer buffer = data.duplicate();
    WritableByteChannel channel = Channels.newChannel(stream);
    while (buffer.hasRemaining()) {
        channel.write(buffer);
    }
}

From source file:org.bimserver.collada.ColladaSerializer.java

private List<String> floatBufferToStringList(ByteBuffer buffer, Format formatter) {
    // Transform the array into a list.
    List<Float> list = new ArrayList<Float>();
    while (buffer.hasRemaining())
        list.add(new Float(buffer.getFloat()));
    // Get the data as a list of String objects.
    return listToStringList(list, formatter);
}

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

private void parseClientPacket(ByteBuffer buf, int dataSize, T client) {
    final int pos = buf.position();
    final DataSizeHolder dsh = getDataSizeHolder().init(dataSize);

    if (client.decipher(buf, dsh) && buf.hasRemaining()) {
        // remove useless bytes
        dsh.decreaseSize(dsh.getMinPadding());
        // calculate possibly remaining useless bytes
        final int maxPossiblePadding = dsh.getMaxPadding() - dsh.getMinPadding();

        // apply limit
        final int limit = buf.limit();
        buf.limit(pos + dsh.getSize());/* ww w .  j av  a  2s .  c om*/

        final int opcode = buf.get() & 0xFF;

        if (getMMOController().canReceivePacketFrom(client, opcode)) {
            RP cp = getPacketHandler().handlePacket(buf, client, opcode);

            if (cp != null) {
                System.out.println("READ: " + client.getState() + " " + cp.getClass().getSimpleName());

                // remove useless bytes #2, using packet specs
                int maxLeftoverPadding = maxPossiblePadding;
                final int overflow = buf.remaining() - cp.getMaximumLength();
                if (maxPossiblePadding > 0 && // there may be useless bytes
                        overflow > 0) // and we have too much
                {
                    // avoid any damage to the packet body
                    final int removable = Math.min(overflow, maxPossiblePadding);
                    buf.limit(buf.limit() - removable);
                    maxLeftoverPadding -= removable;
                }

                getMmoBuffer().setByteBuffer(buf);
                cp.setClient(client);

                try {
                    if (getMmoBuffer().getAvailableBytes() < cp.getMinimumLength()) {
                        getMMOController().report(ErrorMode.BUFFER_UNDER_FLOW, client, cp, null);
                    } else if (getMmoBuffer().getAvailableBytes() > cp.getMaximumLength()) {
                        getMMOController().report(ErrorMode.BUFFER_OVER_FLOW, client, cp, null);
                    } else {
                        cp.read(getMmoBuffer());

                        client.executePacket(cp);

                        if (buf.hasRemaining() && // some unused data, a bad sign
                                buf.remaining() > maxLeftoverPadding) // and definitely not padded bytes
                        {
                            // FIXME disabled until packet structures updated properly
                            //report(ErrorMode.BUFFER_OVER_FLOW, client, cp, null);

                            MMOController._log.info("Invalid packet format (buf: " + buf + ", dataSize: "
                                    + dataSize + ", pos: " + pos + ", limit: " + limit + ", opcode: 0x"
                                    + HexUtil.fillHex(opcode, 2) + ") used for reading - " + client + " - "
                                    + cp.getType() + " - " + getMMOController().getVersionInfo());
                        }
                    }
                } catch (BufferUnderflowException e) {
                    getMMOController().report(ErrorMode.BUFFER_UNDER_FLOW, client, cp, e);
                } catch (RuntimeException e) {
                    getMMOController().report(ErrorMode.FAILED_READING, client, cp, e);
                }

                getMmoBuffer().setByteBuffer(null);
            }
        }

        buf.limit(limit);
    }
}

From source file:com.github.jinahya.verbose.codec.BinaryCodecTest.java

protected final void encodeDecode(final ReadableByteChannel expectedChannel) throws IOException {

    if (expectedChannel == null) {
        throw new NullPointerException("null expectedChannel");
    }/*from  w w w  .  ja  v a  2s  .com*/

    final Path encodedPath = Files.createTempFile("test", null);
    getRuntime().addShutdownHook(new Thread(() -> {
        try {
            Files.delete(encodedPath);
        } catch (final IOException ioe) {
            ioe.printStackTrace(System.err);
        }
    }));
    final WritableByteChannel encodedChannel = FileChannel.open(encodedPath, StandardOpenOption.WRITE);

    final ByteBuffer decodedBuffer = ByteBuffer.allocate(128);
    final ByteBuffer encodedBuffer = ByteBuffer.allocate(decodedBuffer.capacity() << 1);

    while (expectedChannel.read(decodedBuffer) != -1) {
        decodedBuffer.flip(); // limit -> position; position -> zero
        encoder.encode(decodedBuffer, encodedBuffer);
        encodedBuffer.flip();
        encodedChannel.write(encodedBuffer);
        encodedBuffer.compact(); // position -> n  + 1; limit -> capacity
        decodedBuffer.compact();
    }

    decodedBuffer.flip();
    while (decodedBuffer.hasRemaining()) {
        encoder.encode(decodedBuffer, encodedBuffer);
        encodedBuffer.flip();
        encodedChannel.write(encodedBuffer);
        encodedBuffer.compact();
    }

    encodedBuffer.flip();
    while (encodedBuffer.hasRemaining()) {
        encodedChannel.write(encodedBuffer);
    }
}

From source file:org.usergrid.persistence.Schema.java

public static ByteBuffer encrypt(ByteBuffer clear) {
    if (clear == null || !clear.hasRemaining())
        return clear;
    try {//from   www  . j a  v a 2  s  .  co m
        SecretKeySpec sKeySpec = new SecretKeySpec(getRawKey(encryptionSeed), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
        ByteBuffer encrypted = ByteBuffer.allocate(cipher.getOutputSize(clear.remaining()));
        cipher.doFinal(clear, encrypted);
        encrypted.rewind();
        return encrypted;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.usergrid.persistence.Schema.java

public static ByteBuffer decrypt(ByteBuffer encrypted) {
    if (encrypted == null || !encrypted.hasRemaining())
        return encrypted;
    try {/* www.j a v  a 2 s. c  o  m*/
        SecretKeySpec sKeySpec = new SecretKeySpec(getRawKey(encryptionSeed), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
        ByteBuffer decrypted = ByteBuffer.allocate(cipher.getOutputSize(encrypted.remaining()));
        cipher.doFinal(encrypted, decrypted);
        decrypted.rewind();
        return decrypted;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.commoncrawl.util.TextBytes.java

/**
 * Finds any occurence of <code>what</code> in the backing buffer, starting as
 * position <code>start</code>. The starting position is measured in bytes and
 * the return value is in terms of byte position in the buffer. The backing
 * buffer is not converted to a string for this operation.
 * /*w w w . ja  va  2 s. c o  m*/
 * @return byte position of the first occurence of the search string in the
 *         UTF-8 buffer or -1 if not found
 */
public int find(String what, int start) {
    try {
        ByteBuffer src = ByteBuffer.wrap(bytes.get(), bytes.getOffset(), bytes.getCount());
        ByteBuffer tgt = encode(what);
        byte b = tgt.get();
        src.position(start);

        while (src.hasRemaining()) {
            if (b == src.get()) { // matching first byte
                src.mark(); // save position in loop
                tgt.mark(); // save position in target
                boolean found = true;
                int pos = src.position() - 1;
                while (tgt.hasRemaining()) {
                    if (!src.hasRemaining()) { // src expired first
                        tgt.reset();
                        src.reset();
                        found = false;
                        break;
                    }
                    if (!(tgt.get() == src.get())) {
                        tgt.reset();
                        src.reset();
                        found = false;
                        break; // no match
                    }
                }
                if (found)
                    return pos;
            }
        }
        return -1; // not found
    } catch (CharacterCodingException e) {
        // can't get here
        e.printStackTrace();
        return -1;
    }
}

From source file:edu.hawaii.soest.pacioos.text.SocketTextSource.java

@Override
protected boolean execute() {

    log.debug("SocketTextSource.execute() called.");
    // do not execute the stream if there is no connection
    if (!isConnected())
        return false;

    boolean failed = false;

    /* Get a connection to the instrument */
    SocketChannel socket = getSocketConnection();
    if (socket == null)
        return false;

    // while data are being sent, read them into the buffer
    try {//  ww w  .  ja  va  2  s.c o m
        // create four byte placeholders used to evaluate up to a four-byte 
        // window.  The FIFO layout looks like:
        //           -------------------------
        //   in ---> | One | Two |Three|Four |  ---> out
        //           -------------------------
        byte byteOne = 0x00, // set initial placeholder values
                byteTwo = 0x00, byteThree = 0x00, byteFour = 0x00;

        // Create a buffer that will store the sample bytes as they are read
        ByteBuffer sampleBuffer = ByteBuffer.allocate(getBufferSize());

        // create a byte buffer to store bytes from the TCP stream
        ByteBuffer buffer = ByteBuffer.allocateDirect(getBufferSize());

        // while there are bytes to read from the socket ...
        while (socket.read(buffer) != -1 || buffer.position() > 0) {

            // prepare the buffer for reading
            buffer.flip();

            // while there are unread bytes in the ByteBuffer
            while (buffer.hasRemaining()) {
                byteOne = buffer.get();

                // log the byte stream
                String character = new String(new byte[] { byteOne });
                if (log.isDebugEnabled()) {
                    List<Byte> whitespaceBytes = new ArrayList<Byte>();
                    whitespaceBytes.add(new Byte((byte) 0x0A));
                    whitespaceBytes.add(new Byte((byte) 0x0D));
                    if (whitespaceBytes.contains(new Byte(byteOne))) {
                        character = new String(Hex.encodeHex((new byte[] { byteOne })));

                    }
                }
                log.debug("char: " + character + "\t" + "b1: "
                        + new String(Hex.encodeHex((new byte[] { byteOne }))) + "\t" + "b2: "
                        + new String(Hex.encodeHex((new byte[] { byteTwo }))) + "\t" + "b3: "
                        + new String(Hex.encodeHex((new byte[] { byteThree }))) + "\t" + "b4: "
                        + new String(Hex.encodeHex((new byte[] { byteFour }))) + "\t" + "sample pos: "
                        + sampleBuffer.position() + "\t" + "sample rem: " + sampleBuffer.remaining() + "\t"
                        + "sample cnt: " + sampleByteCount + "\t" + "buffer pos: " + buffer.position() + "\t"
                        + "buffer rem: " + buffer.remaining() + "\t" + "state: " + state);

                // evaluate each byte to find the record delimiter(s), and when found, validate and
                // send the sample to the DataTurbine.
                int numberOfChannelsFlushed = 0;

                if (getRecordDelimiters().length == 2) {
                    // have we hit the delimiters in the stream yet?
                    if (byteTwo == getFirstDelimiterByte() && byteOne == getSecondDelimiterByte()) {
                        sampleBuffer.put(byteOne);
                        sampleByteCount++;
                        // extract just the length of the sample bytes out of the
                        // sample buffer, and place it in the channel map as a 
                        // byte array.  Then, send it to the DataTurbine.
                        log.debug("Sample byte count: " + sampleByteCount);
                        byte[] sampleArray = new byte[sampleByteCount];
                        sampleBuffer.flip();
                        sampleBuffer.get(sampleArray);
                        String sampleString = new String(sampleArray, "US-ASCII");

                        if (validateSample(sampleString)) {
                            numberOfChannelsFlushed = sendSample(sampleString);

                        }

                        sampleBuffer.clear();
                        sampleByteCount = 0;
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;
                        log.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap.");

                    } else {
                        // still in the middle of the sample, keep adding bytes
                        sampleByteCount++; // add each byte found

                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);

                        } else {
                            sampleBuffer.compact();
                            log.debug("Compacting sampleBuffer ...");
                            sampleBuffer.put(byteOne);

                        }

                    }

                } else if (getRecordDelimiters().length == 1) {
                    // have we hit the delimiter in the stream yet?
                    if (byteOne == getFirstDelimiterByte()) {
                        sampleBuffer.put(byteOne);
                        sampleByteCount++;
                        // extract just the length of the sample bytes out of the
                        // sample buffer, and place it in the channel map as a 
                        // byte array.  Then, send it to the DataTurbine.
                        byte[] sampleArray = new byte[sampleByteCount];
                        sampleBuffer.flip();
                        sampleBuffer.get(sampleArray);
                        String sampleString = new String(sampleArray, "US-ASCII");

                        if (validateSample(sampleString)) {
                            numberOfChannelsFlushed = sendSample(sampleString);

                        }

                        sampleBuffer.clear();
                        sampleByteCount = 0;
                        byteOne = 0x00;
                        byteTwo = 0x00;
                        byteThree = 0x00;
                        byteFour = 0x00;
                        log.debug("Cleared b1,b2,b3,b4. Cleared sampleBuffer. Cleared rbnbChannelMap.");

                    } else {
                        // still in the middle of the sample, keep adding bytes
                        sampleByteCount++; // add each byte found

                        if (sampleBuffer.remaining() > 0) {
                            sampleBuffer.put(byteOne);

                        } else {
                            sampleBuffer.compact();
                            log.debug("Compacting sampleBuffer ...");
                            sampleBuffer.put(byteOne);

                        }

                    }

                } // end getRecordDelimiters().length

                // shift the bytes in the FIFO window
                byteFour = byteThree;
                byteThree = byteTwo;
                byteTwo = byteOne;

            } //end while (more unread bytes)

            // prepare the buffer to read in more bytes from the stream
            buffer.compact();

        } // end while (more socket bytes to read)
        socket.close();

    } catch (IOException e) {
        // handle exceptions
        // In the event of an i/o exception, log the exception, and allow execute()
        // to return false, which will prompt a retry.
        failed = true;
        log.error("There was a communication error in sending the data sample. The message was: "
                + e.getMessage());
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
        return !failed;

    } catch (SAPIException sapie) {
        // In the event of an RBNB communication  exception, log the exception, 
        // and allow execute() to return false, which will prompt a retry.
        failed = true;
        log.error("There was an RBNB error while sending the data sample. The message was: "
                + sapie.getMessage());
        if (log.isDebugEnabled()) {
            sapie.printStackTrace();
        }
        return !failed;
    }

    return !failed;

}