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:com.newatlanta.appengine.nio.channels.GaeFileChannel.java

private synchronized int writeBuffer(ByteBuffer src) throws IOException {
    int n = src.remaining();
    if (n > buffer.remaining()) {
        extendBuffer(buffer.position() + n);
    }// ww w  . j a  va 2  s.co m
    buffer.put(src);
    isDirty = true;
    fileObject.updateContentSize(position + n);
    positionInternal(position + n, false);
    return n;
}

From source file:com.offbynull.portmapper.pcp.PeerPcpRequest.java

/**
 * Constructs a {@link PeerPcpRequest} object.
 * @param mappingNonce random value used to map requests to responses
 * @param protocol IANA protocol number//from  w  ww.j a v  a  2  s.c o  m
 * @param internalPort internal port
 * @param suggestedExternalPort suggested external port ({@code 0} for no preference)
 * @param suggestedExternalIpAddress suggested external IP address ({@code null} or {@code ::} for no preference)
 * @param remotePeerPort remote port
 * @param remotePeerIpAddress remote IP address
 * @param lifetime requested lifetime in seconds
 * @param options PCP options to use
 * @throws NullPointerException if any argument is {@code null} or contains {@code null}
 * @throws IllegalArgumentException if protocol is {@code protocol < 1 or > 255}, or if
 * {@code internalPort < 1 or > 65535}, or if {@code suggestedExternalPort > 65535}, or if {@code mappingNonce} does not have {@code 12}
 * bytes remaining, or if {@code remotePort < 1 or > 65535}
 */
public PeerPcpRequest(ByteBuffer mappingNonce, int protocol, int internalPort, int suggestedExternalPort,
        InetAddress suggestedExternalIpAddress, int remotePeerPort, InetAddress remotePeerIpAddress,
        long lifetime, PcpOption... options) {
    super(2, lifetime, options);

    Validate.notNull(mappingNonce);
    Validate.isTrue(mappingNonce.remaining() == 12);
    Validate.inclusiveBetween(1, 255, protocol);
    Validate.inclusiveBetween(1, 65535, internalPort); // must not be 0
    Validate.inclusiveBetween(0, 65535, suggestedExternalPort); // 0 = no preference
    Validate.notNull(suggestedExternalIpAddress);
    Validate.inclusiveBetween(1, 65535, remotePeerPort); // cannot be 0
    Validate.notNull(remotePeerIpAddress);

    this.mappingNonce = ByteBufferUtils.copyContents(mappingNonce).asReadOnlyBuffer();
    this.protocol = protocol;
    this.internalPort = internalPort;
    this.suggestedExternalPort = suggestedExternalPort;
    this.suggestedExternalIpAddress = suggestedExternalIpAddress; // for any ipv4 must be ::ffff:0:0, for any ipv6 must be ::
    this.remotePeerPort = remotePeerPort;
    this.remotePeerIpAddress = remotePeerIpAddress; // for any ipv4 must be ::ffff:0:0, for any ipv6 must be ::
}

From source file:com.intel.chimera.cipher.Openssl.java

/**
 * Continues a multiple-part encryption or decryption operation. The data
 * is encrypted or decrypted, depending on how this cipher was initialized.
 * <p/>//  w  w w  .  j  a v a2  s  . c o  m
 *
 * All <code>input.remaining()</code> bytes starting at
 * <code>input.position()</code> are processed. The result is stored in
 * the output buffer.
 * <p/>
 *
 * Upon return, the input buffer's position will be equal to its limit;
 * its limit will not have changed. The output buffer's position will have
 * advanced by n, when 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.
 *
 * @param input the input ByteBuffer
 * @param output the output ByteBuffer
 * @return int number of bytes stored in <code>output</code>
 * @throws ShortBufferException if there is insufficient space in the
 * output buffer
 */
public int update(ByteBuffer input, ByteBuffer output) throws ShortBufferException {
    checkState();
    Utils.checkArgument(input.isDirect() && output.isDirect(), "Direct buffers are required.");
    int len = OpensslNative.update(context, input, input.position(), input.remaining(), output,
            output.position(), output.remaining());
    input.position(input.limit());
    output.position(output.position() + len);
    return len;
}

From source file:net.ymate.platform.serv.nio.support.NioSession.java

public void write() throws IOException {
    synchronized (__writeBufferQueue) {
        while (true) {
            ByteBuffer _buffer = __writeBufferQueue.peek();
            if (_buffer == null) {
                __selectionKey.interestOps(SelectionKey.OP_READ);
                break;
            } else {
                int _wLen = __doChannelWrite(_buffer);
                if (_wLen == 0 && _buffer.remaining() > 0) {
                    break;
                }/*from   w w  w  .ja v a  2 s.  c  om*/
                if (_buffer.remaining() == 0) {
                    __writeBufferQueue.remove();
                } else {
                    break;
                }
            }
        }
    }
}

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

void doPendingWrites() {
    try {//from  ww  w .  j a v  a 2s. co  m
        while (!pendingWrites_.isEmpty()) {
            ByteBuffer buffer = pendingWrites_.get(0);
            socketChannel_.write(buffer);
            if (buffer.remaining() > 0) {
                break;
            }
            pendingWrites_.remove(0);
        }

    } catch (IOException ex) {
        logger_.error(LogUtil.throwableToString(ex));
        // This is to fix the wierd Linux bug with NIO.
        errorClose();
    } finally {
        synchronized (this) {
            if (!pendingWrites_.isEmpty() && (key_.interestOps() & SelectionKey.OP_WRITE) == 0) {
                SelectorManager.getSelectorManager().modifyKeyForWrite(key_);
            }
        }
    }
}

From source file:org.apache.cassandra.db.context.CounterContextTest.java

@Test
public void testRemoveOldShards() {
    NodeId id1 = NodeId.fromInt(1);//from ww  w .  ja  v a 2s.co m
    NodeId id3 = NodeId.fromInt(3);
    NodeId id6 = NodeId.fromInt(6);
    List<NodeId.NodeIdRecord> records = new ArrayList<NodeId.NodeIdRecord>();
    records.add(new NodeId.NodeIdRecord(id1, 2L));
    records.add(new NodeId.NodeIdRecord(id3, 4L));
    records.add(new NodeId.NodeIdRecord(id6, 10L));

    ContextState ctx = ContextState.allocate(6, 2);
    ctx.writeElement(id1, 1L, 1L);
    ctx.writeElement(NodeId.fromInt(2), 2L, 2L);
    ctx.writeElement(id3, 3L, 3L, true);
    ctx.writeElement(NodeId.fromInt(4), 6L, 3L);
    ctx.writeElement(NodeId.fromInt(5), 7L, 3L, true);
    ctx.writeElement(id6, 5L, 6L);

    ByteBuffer merger = cc.computeOldShardMerger(ctx.context, records);
    ByteBuffer merged = cc.merge(ctx.context, merger);
    assert cc.total(ctx.context) == cc.total(merged);

    ByteBuffer cleaned = cc.removeOldShards(merged, (int) (System.currentTimeMillis() / 1000) + 1);
    assert cc.total(ctx.context) == cc.total(cleaned);
    assert cleaned.remaining() == ctx.context.remaining() - stepLength;

    merger = cc.computeOldShardMerger(cleaned, records);
    merged = cc.merge(cleaned, merger);
    assert cc.total(ctx.context) == cc.total(merged);

    cleaned = cc.removeOldShards(merged, (int) (System.currentTimeMillis() / 1000) + 1);
    assert cc.total(ctx.context) == cc.total(cleaned);
    assert cleaned.remaining() == ctx.context.remaining() - 2 * stepLength - 2;

}

From source file:com.intel.chimera.cipher.Openssl.java

/**
 * Finishes a multiple-part operation. The data is encrypted or decrypted,
 * depending on how this cipher was initialized.
 * <p/>/*from   www .ja v a  2s .  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();
    Utils.checkArgument(output.isDirect(), "Direct buffer is required.");
    int len = OpensslNative.doFinal(context, output, output.position(), output.remaining());
    output.position(output.position() + len);
    return len;
}

From source file:edu.umass.cs.gigapaxos.paxospackets.AcceptPacket.java

@Override
public synchronized byte[] toBytes() {
    long t = System.nanoTime();
    if (!(PaxosPacket.BYTEIFICATION && IntegerMap.allInt()))
        return super.toBytes();

    if (this.getByteifiedSelf() != null)
        return this.getByteifiedSelf();

    // else construct
    byte[] buf = super.toBytes(false);
    byte[] bytes = new byte[buf.length
            // ProposalPacket.slot
            + SIZEOF_PROPOSAL// w w w.ja  v a2  s . c om
            // PValuePacket:ballot, recovery, medianCheckpointedSlot,
            // noCoalesce
            + SIZEOF_PVALUE
            // AcceptPacket.sender
            + SIZEOF_ACCEPT];
    ByteBuffer bbuf = ByteBuffer.wrap(bytes);

    // request
    bbuf.put(buf);
    // proposal
    bbuf.putInt(this.slot)
            // pvalue
            .putInt(this.ballot.ballotNumber).putInt(this.ballot.coordinatorID)
            .put(this.isRecovery() ? (byte) 1 : 0).putInt(this.getMedianCheckpointedSlot()).put((byte) 0)
            // accept
            .putInt(this.sender);

    assert (bbuf.remaining() == 0); // exact alignment

    this.setByteifiedSelf(bytes);

    if (PaxosMessenger.INSTRUMENT_SERIALIZATION && Util.oneIn(100))
        DelayProfiler.updateDelayNano("accept->", t, this.batchSize() + 1);

    return bytes;
}

From source file:org.apache.james.protocols.smtp.core.DataLineMessageHookHandler.java

public Response onLine(SMTPSession session, ByteBuffer line, LineHandler<SMTPSession> next) {
    MailEnvelopeImpl env = (MailEnvelopeImpl) session.getAttachment(DataCmdHandler.MAILENV,
            ProtocolSession.State.Transaction);
    OutputStream out = env.getMessageOutputStream();
    try {/*from  w  w w  .j a  v a  2s . c  om*/
        // 46 is "."
        // Stream terminated            
        int c = line.get();
        if (line.remaining() == 2 && c == 46) {
            out.flush();
            out.close();

            Response response = processExtensions(session, env);
            session.popLineHandler();
            session.resetState();
            return response;

            // DotStuffing.
        } else if (c == 46 && line.get() == 46) {
            byte[] bline = readBytes(line);
            out.write(bline, 1, bline.length - 1);
            // Standard write
        } else {
            // TODO: maybe we should handle the Header/Body recognition here
            // and if needed let a filter to cache the headers to apply some
            // transformation before writing them to output.
            out.write(readBytes(line));
        }
        out.flush();
    } catch (IOException e) {
        session.getLogger().error("Unknown error occurred while processing DATA.", e);

        session.resetState();
        return ERROR_PROCESSING_MESSAGE;
    }
    return null;
}

From source file:com.turn.ttorrent.common.Torrent.java

private static String hashFiles(List<File> files, int pieceLenght)
        throws InterruptedException, IOException, NoSuchAlgorithmException {
    int threads = getHashingThreadsCount();
    ExecutorService executor = Executors.newFixedThreadPool(threads);
    ByteBuffer buffer = ByteBuffer.allocate(pieceLenght);
    List<Future<String>> results = new LinkedList<Future<String>>();
    StringBuilder hashes = new StringBuilder();

    long length = 0L;
    int pieces = 0;

    long start = System.nanoTime();
    for (File file : files) {
        logger.info("Hashing data from {} with {} threads ({} pieces)...", new Object[] { file.getName(),
                threads, (int) (Math.ceil((double) file.length() / pieceLenght)) });

        length += file.length();//from w  w w  .  ja  v  a 2 s.c  o m

        FileInputStream fis = new FileInputStream(file);
        FileChannel channel = fis.getChannel();
        int step = 10;

        try {
            while (channel.read(buffer) > 0) {
                if (buffer.remaining() == 0) {
                    buffer.clear();
                    results.add(executor.submit(new CallableChunkHasher(buffer)));
                }

                if (results.size() >= threads) {
                    pieces += accumulateHashes(hashes, results);
                }

                if (channel.position() / (double) channel.size() * 100f > step) {
                    logger.info("  ... {}% complete", step);
                    step += 10;
                }
            }
        } finally {
            channel.close();
            fis.close();
        }
    }

    // Hash the last bit, if any
    if (buffer.position() > 0) {
        buffer.limit(buffer.position());
        buffer.position(0);
        results.add(executor.submit(new CallableChunkHasher(buffer)));
    }

    pieces += accumulateHashes(hashes, results);

    // Request orderly executor shutdown and wait for hashing tasks to
    // complete.
    executor.shutdown();
    while (!executor.isTerminated()) {
        Thread.sleep(10);
    }
    long elapsed = System.nanoTime() - start;

    int expectedPieces = (int) (Math.ceil((double) length / pieceLenght));
    logger.info("Hashed {} file(s) ({} bytes) in {} pieces ({} expected) in {}ms.", new Object[] { files.size(),
            length, pieces, expectedPieces, String.format("%.1f", elapsed / 1e6), });

    return hashes.toString();
}