Java Code Examples for java.nio.ByteBuffer.capacity()

The following are Jave code examples for showing how to use capacity() of the java.nio.ByteBuffer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: s-store   File: ExecutionEngineIPC.java   View Source Code Vote up 6 votes
/**
 * Retrieve a dependency table and send it via the connection. If
 * no table is available send a response code indicating such.
 * The message is prepended with two lengths. One length is for
 * the network layer and is the size of the whole message not including
 * the length prefix.
 * @param dependencyId ID of the dependency table to send to the client
 */
private void sendDependencyTable(final int dependencyId) throws IOException{
    final byte[] dependencyBytes = nextDependencyAsBytes(dependencyId);
    if (dependencyBytes == null) {
        m_connection.m_socket.getOutputStream().write(Connection.kErrorCode_DependencyNotFound);
        return;
    }
    // 1 for response code + 4 for dependency length prefix + dependencyBytes.length
    final ByteBuffer message = ByteBuffer.allocate(1 + 4 + dependencyBytes.length);

    // write the response code
    message.put((byte)Connection.kErrorCode_DependencyFound);

    // write the dependency's length prefix
    message.putInt(dependencyBytes.length);

    // finally, write dependency table itself
    message.put(dependencyBytes);
    message.rewind();
    if (m_connection.m_socketChannel.write(message) != message.capacity()) {
        throw new IOException("Unable to send dependency table to client. Attempted blocking write of " +
                message.capacity() + " but not all of it was written");
    }
}
 
Example 2
Project: openjdk-jdk10   File: TrueTypeFont.java   View Source Code Vote up 6 votes
private void setCJKSupport(ByteBuffer os2Table) {
    /* required info is in ulong at offset 46 */
    if (os2Table == null || os2Table.capacity() < 50) {
        return;
    }
    int range2 = os2Table.getInt(46); /* ulUnicodeRange2 */

    /* Any of these bits set in the 32-63 range indicate a font with
     * support for a CJK range. We aren't looking at some other bits
     * in the 64-69 range such as half width forms as its unlikely a font
     * would include those and none of these.
     */
    supportsCJK = ((range2 & 0x29bf0000) != 0);

    /* This should be generalised, but for now just need to know if
     * Hiragana or Katakana ranges are supported by the font.
     * In the 4 longs representing unicode ranges supported
     * bits 49 & 50 indicate hiragana and katakana
     * This is bits 17 & 18 in the 2nd ulong. If either is supported
     * we presume this is a JA font.
     */
    supportsJA = ((range2 & 0x60000) != 0);
}
 
Example 3
Project: ImageClassify   File: CameraActivity.java   View Source Code Vote up 5 votes
protected void fillBytes(final Plane[] planes, final byte[][] yuvBytes) {
  // Because of the variable row stride it's not possible to know in
  // advance the actual necessary dimensions of the yuv planes.
  for (int i = 0; i < planes.length; ++i) {
    final ByteBuffer buffer = planes[i].getBuffer();
    if (yuvBytes[i] == null) {
      LOGGER.d("Initializing buffer %d at size %d", i, buffer.capacity());
      yuvBytes[i] = new byte[buffer.capacity()];
    }
    buffer.get(yuvBytes[i]);
  }
}
 
Example 4
Project: kafka-0.11.0.0-src-with-comment   File: MemoryRecordsBuilderTest.java   View Source Code Vote up 5 votes
@Test(expected = IllegalArgumentException.class)
public void testWriteEndTxnMarkerNonTransactionalBatch() {
    ByteBuffer buffer = ByteBuffer.allocate(128);
    buffer.position(bufferOffset);

    long pid = 9809;
    short epoch = 15;
    int sequence = RecordBatch.NO_SEQUENCE;

    MemoryRecordsBuilder builder = new MemoryRecordsBuilder(buffer, RecordBatch.CURRENT_MAGIC_VALUE, compressionType, TimestampType.CREATE_TIME,
            0L, 0L, pid, epoch, sequence, false, true, RecordBatch.NO_PARTITION_LEADER_EPOCH, buffer.capacity());
    builder.appendEndTxnMarker(RecordBatch.NO_TIMESTAMP, new EndTransactionMarker(ControlRecordType.ABORT, 0));
}
 
Example 5
Project: QDrill   File: DirectCodecFactory.java   View Source Code Vote up 5 votes
private ByteBuffer ensure(ByteBuffer buffer, int size) {
  if (buffer == null) {
    buffer = allocator.allocate(size);
  } else if (buffer.capacity() >= size) {
    buffer.clear();
  } else {
    allocator.release(buffer);
    release(buffer);
    buffer = allocator.allocate(size);
  }
  return buffer;
}
 
Example 6
Project: monarch   File: HeapDataOutputStream.java   View Source Code Vote up 5 votes
/**
 * @param doNotCopy if true then byte arrays/buffers/sources will not be copied to this hdos but
 *        instead referenced.
 */
public HeapDataOutputStream(ByteBuffer initialBuffer, Version version, boolean doNotCopy) {
  if (initialBuffer.position() != 0) {
    initialBuffer = initialBuffer.slice();
  }
  int allocSize = initialBuffer.capacity();
  if (allocSize < 32) {
    this.MIN_CHUNK_SIZE = 32;
  } else {
    this.MIN_CHUNK_SIZE = allocSize;
  }
  this.buffer = initialBuffer;
  this.version = version;
  this.doNotCopy = doNotCopy;
}
 
Example 7
Project: kafka-0.11.0.0-src-with-comment   File: MemoryRecordsBuilderTest.java   View Source Code Vote up 5 votes
@Test(expected = IllegalArgumentException.class)
public void testWriteControlBatchNotAllowedMagicV1() {
    ByteBuffer buffer = ByteBuffer.allocate(128);
    buffer.position(bufferOffset);

    long pid = 9809;
    short epoch = 15;
    int sequence = 2342;

    new MemoryRecordsBuilder(buffer, RecordBatch.MAGIC_VALUE_V1, compressionType, TimestampType.CREATE_TIME,
            0L, 0L, pid, epoch, sequence, false, true, RecordBatch.NO_PARTITION_LEADER_EPOCH, buffer.capacity());
}
 
Example 8
Project: creacoinj   File: NativeSecp256k1.java   View Source Code Vote up 5 votes
/**
 * libsecp256k1 PrivKey Tweak-Mul - Tweak privkey by multiplying to it
 *
 * @param tweak some bytes to tweak with
 * @param seckey 32-byte seckey
 */
public static byte[] privKeyTweakMul(byte[] privkey, byte[] tweak) throws AssertFailException {
    Preconditions.checkArgument(privkey.length == 32);

    ByteBuffer byteBuff = nativeECDSABuffer.get();
    if (byteBuff == null || byteBuff.capacity() < privkey.length + tweak.length) {
        byteBuff = ByteBuffer.allocateDirect(privkey.length + tweak.length);
        byteBuff.order(ByteOrder.nativeOrder());
        nativeECDSABuffer.set(byteBuff);
    }
    byteBuff.rewind();
    byteBuff.put(privkey);
    byteBuff.put(tweak);

    byte[][] retByteArray;
    r.lock();
    try {
        retByteArray = secp256k1_privkey_tweak_mul(byteBuff, Secp256k1Context.getContext());
    } finally {
        r.unlock();
    }

    byte[] privArr = retByteArray[0];

    int privLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
    int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();

    assertEquals(privArr.length, privLen, "Got bad pubkey length.");

    assertEquals(retVal, 1, "Failed return value check.");

    return privArr;
}
 
Example 9
Project: crypto-core   File: NativeSecp256k1.java   View Source Code Vote up 5 votes
/**
 * libsecp256k1 PrivKey Tweak-Mul - Tweak privkey by multiplying to it
 *
 * @param tweak some bytes to tweak with
 * @param privkey 32-byte seckey
 */
public static byte[] privKeyTweakMul(byte[] privkey, byte[] tweak) throws AssertFailException {
    Preconditions.checkArgument(privkey.length == 32);

    ByteBuffer byteBuff = nativeECDSABuffer.get();
    if (byteBuff == null || byteBuff.capacity() < privkey.length + tweak.length) {
        byteBuff = ByteBuffer.allocateDirect(privkey.length + tweak.length);
        byteBuff.order(ByteOrder.nativeOrder());
        nativeECDSABuffer.set(byteBuff);
    }
    byteBuff.rewind();
    byteBuff.put(privkey);
    byteBuff.put(tweak);

    byte[][] retByteArray;
    r.lock();
    try {
        retByteArray = secp256k1_privkey_tweak_mul(byteBuff, Secp256k1Context.getContext());
    } finally {
        r.unlock();
    }

    byte[] privArr = retByteArray[0];

    int privLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
    int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();

    assertEquals(privArr.length, privLen, "Got bad pubkey length.");

    assertEquals(retVal, 1, "Failed return value check.");

    return privArr;
}
 
Example 10
Project: GitHub   File: Dex.java   View Source Code Vote up 5 votes
/**
 * Returns a copy of the the bytes of this dex.
 */
public byte[] getBytes() {
    ByteBuffer data = this.data.duplicate(); // positioned ByteBuffers aren't thread safe
    byte[] result = new byte[data.capacity()];
    data.position(0);
    data.get(result);
    return result;
}
 
Example 11
Project: DreamSocket   File: MessageDecode.java   View Source Code Vote up 5 votes
public final void decode(SocketAddress address, byte[] array, int offset, int length) {
    ByteBuffer buffer = mAddressByteBufferMap.get(address);
    if (buffer == null) {
        buffer = ByteBuffer.allocate(CACHE_BUFFER_LENGTH);
        mAddressByteBufferMap.put(address, buffer);
        buffer.flip();
        LoggerFactory.getLogger().info("创建 " + address.toString() + " 数据缓冲区ByteBuffer");
    }
    LoggerFactory.getLogger().info(String.format("%s 上次未解码 position=%d limit=%d", address.toString(), buffer.position(), buffer.limit()));
    if (buffer.limit() + length > buffer.capacity()) {
        LoggerFactory.getLogger().warn(address.toString() + " -> decode缓存区已满,读取的数据被丢弃!!!!!");
        return;
    }
    buffer.compact();
    buffer.put(array, offset, length);
    buffer.flip();
    buffer.mark();
    LoggerFactory.getLogger().info(String.format("%s 合并未解码 position=%d limit=%d", address.toString(), buffer.position(), buffer.limit()));
    LoggerFactory.getLogger().info(address.toString() + " 开始解码数据");
    while (buffer.hasRemaining() && (decode(address, buffer) != null)) {
        LoggerFactory.getLogger().info(address.toString() + " 成功解码一条数据");
        buffer.compact();
        buffer.flip();
        buffer.mark();
    }
    LoggerFactory.getLogger().info(address.toString() + " 退出解码");
    buffer.reset();
    LoggerFactory.getLogger().info(String.format("%s 未解码数据 position=%d limit=%d", address.toString(), buffer.position(), buffer.limit()));
}
 
Example 12
Project: openjdk-jdk10   File: CMap.java   View Source Code Vote up 5 votes
static CMap createCMap(ByteBuffer buffer, int offset, char[] xlat) {
    /* First do a sanity check that this cmap subtable is contained
     * within the cmap table.
     */
    int subtableFormat = buffer.getChar(offset);
    long subtableLength;
    if (subtableFormat < 8) {
        subtableLength = buffer.getChar(offset+2);
    } else {
        subtableLength = buffer.getInt(offset+4) & INTMASK;
    }
    if (offset+subtableLength > buffer.capacity()) {
        if (FontUtilities.isLogging()) {
            FontUtilities.getLogger().warning("Cmap subtable overflows buffer.");
        }
    }
    switch (subtableFormat) {
    case 0:  return new CMapFormat0(buffer, offset);
    case 2:  return new CMapFormat2(buffer, offset, xlat);
    case 4:  return new CMapFormat4(buffer, offset, xlat);
    case 6:  return new CMapFormat6(buffer, offset, xlat);
    case 8:  return new CMapFormat8(buffer, offset, xlat);
    case 10: return new CMapFormat10(buffer, offset, xlat);
    case 12: return new CMapFormat12(buffer, offset, xlat);
    default: throw new RuntimeException("Cmap format unimplemented: " +
                                        (int)buffer.getChar(offset));
    }
}
 
Example 13
Project: kafka-0.11.0.0-src-with-comment   File: MemoryRecordsBuilderTest.java   View Source Code Vote up 5 votes
@Test
public void buildUsingLogAppendTime() {
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    buffer.position(bufferOffset);

    long logAppendTime = System.currentTimeMillis();
    MemoryRecordsBuilder builder = new MemoryRecordsBuilder(buffer, RecordBatch.MAGIC_VALUE_V1, compressionType,
            TimestampType.LOG_APPEND_TIME, 0L, logAppendTime, RecordBatch.NO_PRODUCER_ID, RecordBatch.NO_PRODUCER_EPOCH,
            RecordBatch.NO_SEQUENCE, false, false, RecordBatch.NO_PARTITION_LEADER_EPOCH, buffer.capacity());
    builder.append(0L, "a".getBytes(), "1".getBytes());
    builder.append(0L, "b".getBytes(), "2".getBytes());
    builder.append(0L, "c".getBytes(), "3".getBytes());
    MemoryRecords records = builder.build();

    MemoryRecordsBuilder.RecordsInfo info = builder.info();
    assertEquals(logAppendTime, info.maxTimestamp);

    if (compressionType != CompressionType.NONE)
        assertEquals(2L, info.shallowOffsetOfMaxTimestamp);
    else
        assertEquals(0L, info.shallowOffsetOfMaxTimestamp);

    for (RecordBatch batch : records.batches()) {
        assertEquals(TimestampType.LOG_APPEND_TIME, batch.timestampType());
        for (Record record : batch)
            assertEquals(logAppendTime, record.timestamp());
    }
}
 
Example 14
Project: crypto-core   File: NativeSecp256k1.java   View Source Code Vote up 5 votes
/**
 * libsecp256k1 create ECDH secret - constant time ECDH calculation
 *
 * @param seckey byte array of secret key used in exponentiaion
 * @param pubkey byte array of public key used in exponentiaion
 */
public static byte[] createECDHSecret(byte[] seckey, byte[] pubkey) throws AssertFailException {
    Preconditions.checkArgument(seckey.length <= 32 && pubkey.length <= 65);

    ByteBuffer byteBuff = nativeECDSABuffer.get();
    if (byteBuff == null || byteBuff.capacity() < 32 + pubkey.length) {
        byteBuff = ByteBuffer.allocateDirect(32 + pubkey.length);
        byteBuff.order(ByteOrder.nativeOrder());
        nativeECDSABuffer.set(byteBuff);
    }
    byteBuff.rewind();
    byteBuff.put(seckey);
    byteBuff.put(pubkey);

    byte[][] retByteArray;
    r.lock();
    try {
        retByteArray = secp256k1_ecdh(byteBuff, Secp256k1Context.getContext(), pubkey.length);
    } finally {
        r.unlock();
    }

    byte[] resArr = retByteArray[0];
    int retVal = new BigInteger(new byte[] { retByteArray[1][0] }).intValue();

    assertEquals(resArr.length, 32, "Got bad result length.");
    assertEquals(retVal, 1, "Failed return value check.");

    return resArr;
}
 
Example 15
Project: hadoop-oss   File: DirectBufferPool.java   View Source Code Vote up 5 votes
/**
 * Return a buffer into the pool. After being returned,
 * the buffer may be recycled, so the user must not
 * continue to use it in any way.
 * @param buf the buffer to return
 */
public void returnBuffer(ByteBuffer buf) {
  buf.clear(); // reset mark, limit, etc
  int size = buf.capacity();
  Queue<WeakReference<ByteBuffer>> list = buffersBySize.get(size);
  if (list == null) {
    list = new ConcurrentLinkedQueue<WeakReference<ByteBuffer>>();
    Queue<WeakReference<ByteBuffer>> prev = buffersBySize.putIfAbsent(size, list);
    // someone else put a queue in the map before we did
    if (prev != null) {
      list = prev;
    }
  }
  list.add(new WeakReference<ByteBuffer>(buf));
}
 
Example 16
Project: jdk8u-jdk   File: NativeUnpack.java   View Source Code Vote up 5 votes
private long readInputFn(ByteBuffer pbuf, long minlen) throws IOException {
    if (in == null)  return 0;  // nothing is readable
    long maxlen = pbuf.capacity() - pbuf.position();
    assert(minlen <= maxlen);  // don't talk nonsense
    long numread = 0;
    int steps = 0;
    while (numread < minlen) {
        steps++;
        // read available input, up to buf.length or maxlen
        int readlen = _buf.length;
        if (readlen > (maxlen - numread))
            readlen = (int)(maxlen - numread);
        int nr = in.read(_buf, 0, readlen);
        if (nr <= 0)  break;
        numread += nr;
        assert(numread <= maxlen);
        // %%% get rid of this extra copy by using nio?
        pbuf.put(_buf, 0, nr);
    }
    if (_verbose > 1)
        Utils.log.fine("readInputFn("+minlen+","+maxlen+") => "+numread+" steps="+steps);
    if (maxlen > 100) {
        _estByteLimit = _byteCount + maxlen;
    } else {
        _estByteLimit = (_byteCount + numread) * 20;
    }
    _byteCount += numread;
    updateProgress();
    return numread;
}
 
Example 17
Project: okwallet   File: NativeSecp256k1.java   View Source Code Vote up 5 votes
/**
 * libsecp256k1 PrivKey Tweak-Mul - Tweak privkey by multiplying to it
 *
 * @param tweak some bytes to tweak with
 * @param privkey 32-byte seckey
 */
public static byte[] privKeyTweakMul(byte[] privkey, byte[] tweak) throws AssertFailException {
    Preconditions.checkArgument(privkey.length == 32);

    ByteBuffer byteBuff = nativeECDSABuffer.get();
    if (byteBuff == null || byteBuff.capacity() < privkey.length + tweak.length) {
        byteBuff = ByteBuffer.allocateDirect(privkey.length + tweak.length);
        byteBuff.order(ByteOrder.nativeOrder());
        nativeECDSABuffer.set(byteBuff);
    }
    byteBuff.rewind();
    byteBuff.put(privkey);
    byteBuff.put(tweak);

    byte[][] retByteArray;
    r.lock();
    try {
        retByteArray = secp256k1_privkey_tweak_mul(byteBuff, Secp256k1Context.getContext());
    } finally {
        r.unlock();
    }

    byte[] privArr = retByteArray[0];

    int privLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
    int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();

    assertEquals(privArr.length, privLen, "Got bad pubkey length.");

    assertEquals(retVal, 1, "Failed return value check.");

    return privArr;
}
 
Example 18
Project: creacoinj   File: NativeSecp256k1.java   View Source Code Vote up 5 votes
/**
 * libsecp256k1 Create an ECDSA signature.
 *
 * @param data Message hash, 32 bytes
 * @param key Secret key, 32 bytes
 * @return sig byte array of signature
 */
public static byte[] sign(byte[] data, byte[] sec) throws AssertFailException {
    Preconditions.checkArgument(data.length == 32 && sec.length <= 32);

    ByteBuffer byteBuff = nativeECDSABuffer.get();
    if (byteBuff == null || byteBuff.capacity() < 32 + 32) {
        byteBuff = ByteBuffer.allocateDirect(32 + 32);
        byteBuff.order(ByteOrder.nativeOrder());
        nativeECDSABuffer.set(byteBuff);
    }
    byteBuff.rewind();
    byteBuff.put(data);
    byteBuff.put(sec);

    byte[][] retByteArray;

    r.lock();
    try {
        retByteArray = secp256k1_ecdsa_sign(byteBuff, Secp256k1Context.getContext());
    } finally {
        r.unlock();
    }

    byte[] sigArr = retByteArray[0];
    int sigLen = new BigInteger(new byte[] { retByteArray[1][0] }).intValue();
    int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();

    assertEquals(sigArr.length, sigLen, "Got bad signature length.");

    return retVal == 0 ? new byte[0] : sigArr;
}
 
Example 19
Project: feeyo-redisproxy   File: ByteBufferPagePool.java   View Source Code Vote up 5 votes
public  ByteBuffer expandBuffer(ByteBuffer buffer){
    int oldCapacity = buffer.capacity();
    int newCapacity = oldCapacity << 1;
    ByteBuffer newBuffer = allocate(newCapacity);
    if(newBuffer != null){
        int newPosition = buffer.position();
        buffer.flip();
        newBuffer.put(buffer);
        newBuffer.position(newPosition);
        recycle(buffer);
        return  newBuffer;
    }
    return null;
}
 
Example 20
Project: tomcat7   File: AjpNioProcessor.java   View Source Code Vote up 4 votes
private int readSocket(byte[] buf, int pos, int n, boolean block)
        throws IOException {
    int nRead = 0;
    ByteBuffer readBuffer =
            socketWrapper.getSocket().getBufHandler().getReadBuffer();
    readBuffer.clear();
    if (n < readBuffer.capacity()) {
        readBuffer.limit(n);
    }
    if ( block ) {
        Selector selector = null;
        try {
            selector = pool.get();
        } catch ( IOException x ) {
            // Ignore
        }
        try {
            NioEndpoint.KeyAttachment att =
                    (NioEndpoint.KeyAttachment) socketWrapper.getSocket().getAttachment();
            if ( att == null ) throw new IOException("Key must be cancelled.");
            nRead = pool.read(readBuffer, socketWrapper.getSocket(),
                    selector, att.getTimeout());
        } catch ( EOFException eof ) {
            nRead = -1;
        } finally { 
            if ( selector != null ) pool.put(selector);
        }
    } else {
        nRead = socketWrapper.getSocket().read(readBuffer);
    }
    if (nRead > 0) {
        readBuffer.flip();
        readBuffer.limit(nRead);
        readBuffer.get(buf, pos, nRead);
        return nRead;
    } else if (nRead == -1) {
        //return false;
        throw new EOFException(sm.getString("iib.eof.error"));
    } else {
        return 0;
    }
}