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

The following examples show how to use java.nio.ByteBuffer#capacity() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NetworkProtocol.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Decodes a series of events from the ByteBuffer. Handles event values and
 * types as bytes.
 *
 * @param buffer
 * @return
 * @throws ClientException
 */
public static Event[] decodeEvents(final ByteBuffer buffer)
		throws ClientException {
	final ArrayList<Event> events = new ArrayList<Event>();
	int nEvents = 0;

	// Read events while bytes remain in the buffer.
	try {
		while (buffer.position() < buffer.capacity()) {
			events.add(decodeEvent(buffer));
			nEvents++;
		}
	} catch (final BufferUnderflowException e) {
		throw new ClientException("Malformed event message");
	}

	return events.toArray(new Event[nEvents]);
}
 
Example 2
Source File: TestByteBufferKeyValue.java    From hbase with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetKeyMethods() throws Exception {
  KeyValue kvCell = new KeyValue(row1, fam1, qual1, 0L, Type.Put, row1, tags);
  ByteBuffer buf = ByteBuffer.allocateDirect(kvCell.getKeyLength());
  ByteBufferUtils.copyFromArrayToBuffer(buf, kvCell.getBuffer(), kvCell.getKeyOffset(),
    kvCell.getKeyLength());
  ByteBufferExtendedCell offheapKeyOnlyKV = new ByteBufferKeyOnlyKeyValue(buf, 0, buf.capacity());
  assertEquals(
    ROW1,
    ByteBufferUtils.toStringBinary(offheapKeyOnlyKV.getRowByteBuffer(),
      offheapKeyOnlyKV.getRowPosition(), offheapKeyOnlyKV.getRowLength()));
  assertEquals(
    FAM1,
    ByteBufferUtils.toStringBinary(offheapKeyOnlyKV.getFamilyByteBuffer(),
      offheapKeyOnlyKV.getFamilyPosition(), offheapKeyOnlyKV.getFamilyLength()));
  assertEquals(
    QUAL1,
    ByteBufferUtils.toStringBinary(offheapKeyOnlyKV.getQualifierByteBuffer(),
      offheapKeyOnlyKV.getQualifierPosition(),
      offheapKeyOnlyKV.getQualifierLength()));
  assertEquals(0L, offheapKeyOnlyKV.getTimestamp());
  assertEquals(Type.Put.getCode(), offheapKeyOnlyKV.getTypeByte());
}
 
Example 3
Source File: AiffData.java    From slick2d-maven with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**	
 * Creates a AiffData container from the specified ByetBuffer.
 * If the buffer is backed by an array, it will be used directly, 
 * else the contents of the buffer will be copied using get(byte[]).
 *
 * @param buffer ByteBuffer containing sound file
 * @return AiffData containing data, or null if a failure occured
 */
public static AiffData create(ByteBuffer buffer) {
	try {
		byte[] bytes = null;
		
		if(buffer.hasArray()) {
			bytes = buffer.array();
		} else {
			bytes = new byte[buffer.capacity()];
			buffer.get(bytes);
		}
		return create(bytes);
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
}
 
Example 4
Source File: NetworkProtocol.java    From buffer_bci with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Decodes a series of extended header chunks from the bytebuffer.
 *
 * @param buffer
 * @return
 * @throws ClientException
 */
private static Chunk[] decodeChunks(final ByteBuffer buffer)
		throws ClientException {
	final ArrayList<Chunk> chunks = new ArrayList<Chunk>();
	int nChunks = 0;

	// Read events while bytes remain in the buffer.
	try {
		while (buffer.position() < buffer.capacity()) {
			chunks.add(decodeChunk(buffer));
			nChunks++;
		}
	} catch (final BufferUnderflowException e) {
		throw new ClientException("Malformed header message");
	}

	return chunks.toArray(new Chunk[nChunks]);
}
 
Example 5
Source File: PreloadBufferPool.java    From journalkeeper with Apache License 2.0 6 votes vote down vote up
@Override
public void releaseDirect(ByteBuffer byteBuffer, BufferHolder bufferHolder) {
    directBufferHolders.remove(bufferHolder);
    int size = byteBuffer.capacity();
    PreLoadCache preLoadCache = bufferCache.get(size);
    if (null != preLoadCache) {
        if (needEviction() && preLoadCache.cache.size() >= preLoadCache.maxCount) {
            destroyOne(byteBuffer);
        } else {
            byteBuffer.clear();
            preLoadCache.cache.add(byteBuffer);
        }
        preLoadCache.onFlyCounter.getAndDecrement();
    } else {
        destroyOne(byteBuffer);
    }
}
 
Example 6
Source File: JavaVMemServiceImplNGTest.java    From mnemonic with Apache License 2.0 6 votes vote down vote up
/**
 * test to verify the allocate() is working when initzero = true
 */
@Test(enabled = true, dependsOnMethods = "testToInitByCreateNewFile1")
public void testToAllocateWithInit() throws IOException, ClassNotFoundException {
  //Ensure it doesn't impact the test file
  String dest = "./jvmstestallocatewithinit.dat";
  Files.copy(Paths.get(testFile), Paths.get(dest));

  JavaVMemServiceImpl vms = new JavaVMemServiceImpl();
  long cap = 10 * 1024 * 1024;
  long memPool = vms.init(cap, dest, true);
  BufferBlockInfo blockInfo = vms.getMemPools().get((int)memPool).getByteBufferBlocksList().get(0);
  long handler = vms.allocate(memPool, 513, true);
  assertTrue(handler > 0L);
  ByteBuffer bb = vms.retrieveByteBuffer(memPool, handler);
  Assert.assertEquals(bb.capacity(), 513);
  for (int i = 0; i < bb.capacity(); i++) {
    Assert.assertEquals(bb.get(i), (byte)0);
  }
  vms.destroyByteBuffer(memPool, bb, null);
  vms.close(memPool);
  Files.delete(Paths.get(dest));
}
 
Example 7
Source File: YuvHelper.java    From webrtc_android with MIT License 6 votes vote down vote up
/** Helper method for copying I420 to tightly packed NV12 destination buffer. */
public static void I420ToNV12(ByteBuffer srcY, int srcStrideY, ByteBuffer srcU, int srcStrideU,
    ByteBuffer srcV, int srcStrideV, ByteBuffer dst, int width, int height) {
  final int chromaWidth = (width + 1) / 2;
  final int chromaHeight = (height + 1) / 2;

  final int minSize = width * height + chromaWidth * chromaHeight * 2;
  if (dst.capacity() < minSize) {
    throw new IllegalArgumentException("Expected destination buffer capacity to be at least "
        + minSize + " was " + dst.capacity());
  }

  final int startY = 0;
  final int startUV = height * width;

  dst.position(startY);
  final ByteBuffer dstY = dst.slice();
  dst.position(startUV);
  final ByteBuffer dstUV = dst.slice();

  nativeI420ToNV12(srcY, srcStrideY, srcU, srcStrideU, srcV, srcStrideV, dstY, width, dstUV,
      chromaWidth * 2, width, height);
}
 
Example 8
Source File: Draft.java    From Slyther with MIT License 5 votes vote down vote up
public static HandshakeBuilder translateHandshakeHttp( ByteBuffer buf, Role role ) throws InvalidHandshakeException , IncompleteHandshakeException {
	HandshakeBuilder handshake;

	String line = readStringLine( buf );
	if( line == null )
		throw new IncompleteHandshakeException( buf.capacity() + 128 );

	String[] firstLineTokens = line.split( " ", 3 );// eg. HTTP/1.1 101 Switching the Protocols
	if( firstLineTokens.length != 3 ) {
		throw new InvalidHandshakeException();
	}

	if( role == Role.CLIENT ) {
		// translating/parsing the response from the SERVER
		handshake = new HandshakeImpl1Server();
		ServerHandshakeBuilder serverhandshake = (ServerHandshakeBuilder) handshake;
		serverhandshake.setHttpStatus( Short.parseShort( firstLineTokens[ 1 ] ) );
		serverhandshake.setHttpStatusMessage( firstLineTokens[ 2 ] );
	} else {
		// translating/parsing the request from the CLIENT
		ClientHandshakeBuilder clienthandshake = new HandshakeImpl1Client();
		clienthandshake.setResourceDescriptor( firstLineTokens[ 1 ] );
		handshake = clienthandshake;
	}

	line = readStringLine( buf );
	while ( line != null && line.length() > 0 ) {
		String[] pair = line.split( ":", 2 );
		if( pair.length != 2 )
			throw new InvalidHandshakeException( "not an http header" );
		handshake.put( pair[ 0 ], pair[ 1 ].replaceFirst( "^ +", "" ) );
		line = readStringLine( buf );
	}
	if( line == null )
		throw new IncompleteHandshakeException();
	return handshake;
}
 
Example 9
Source File: NativeSecp256k1.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
/**
 * libsecp256k1 PubKey Tweak-Add - Tweak pubkey by adding to it
 *
 * @param tweak  some bytes to tweak with
 * @param pubkey 32-byte seckey
 */
public static byte[] pubKeyTweakAdd(byte[] pubkey, byte[] tweak) throws AssertFailException {
    Preconditions.checkArgument(pubkey.length == 33 || pubkey.length == 65);

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

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

    byte[] pubArr = retByteArray[0];

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

    assertEquals(pubArr.length, pubLen, "Got bad pubkey length.");

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

    return pubArr;
}
 
Example 10
Source File: ByteUtilTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private static byte[] duplicateRemaining(ByteBuffer buffer, int offset, int bytes) {
   final int end = offset + bytes;
   final int expectedRemaining = buffer.capacity() - end;
   //it is handling the case of <0 just to allow from to > capacity
   if (expectedRemaining <= 0) {
      return null;
   }
   final byte[] remaining = new byte[expectedRemaining];
   final ByteBuffer duplicate = buffer.duplicate();
   duplicate.clear().position(end);
   duplicate.get(remaining, 0, expectedRemaining);
   return remaining;
}
 
Example 11
Source File: Graphics.java    From slick2d-maven with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get an ara of pixels as RGBA values into a buffer
 * 
 * @param x The x position in the context to grab from
 * @param y The y position in the context to grab from
 * @param width The width of the area to grab from 
 * @param height The hiehgt of the area to grab from
 * @param target The target buffer to grab into
 */
public void getArea(int x, int y, int width, int height, ByteBuffer target)
{
	if (target.capacity() < width * height * 4) 
	{
		throw new IllegalArgumentException("Byte buffer provided to get area is not big enough");
	}
	
	predraw();	
	GL.glReadPixels(x, screenHeight - y - height, width, height, SGL.GL_RGBA,
			SGL.GL_UNSIGNED_BYTE, target);
	postdraw();
}
 
Example 12
Source File: BaseAudioDecoder.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected MediaCodec.BufferInfo onInputBufferAvailable(@NonNull MediaExtractor extractor, @NonNull ByteBuffer inputBuffer) {
    long sampleTime = extractor.getSampleTime();
    int counter = 0;
    int maxresult = 0;
    int result;
    boolean advanced = false;

    do {
        result = extractor.readSampleData(inputBuffer, counter);
        if (result >= 0) {
            advanced = extractor.advance();
            maxresult = Math.max(maxresult, result);
            counter += result;
        }
    } while (result >= 0 && advanced && inputBuffer.capacity() - inputBuffer.limit() > maxresult);
    // the remaining capacity should be more than enough for another sample data block

    // queue the input buffer. At end of file counter will be 0 and flags marks end of stream
    // offset MUST be 0. The output buffer code cannot handle offsets
    // result < 0 means the end of the file input is reached
    int flags = advanced ? 0 : MediaCodec.BUFFER_FLAG_END_OF_STREAM;

    MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo();
    bufferInfo.set(0, counter, sampleTime, flags);

    return bufferInfo;
}
 
Example 13
Source File: QueryKeyRequest.java    From bboxdb with Apache License 2.0 5 votes vote down vote up
@Override
public long writeToOutputStream(final OutputStream outputStream) throws PackageEncodeException {

	try {
		final byte[] tableBytes = table.getFullnameBytes();
		final byte[] keyBytes = key.getBytes();
		
		final ByteBuffer bb = ByteBuffer.allocate(8);
		bb.order(Const.APPLICATION_BYTE_ORDER);
		
		bb.put(getQueryType());
		
		if(pagingEnabled) {
			bb.put((byte) 1);
		} else {
			bb.put((byte) 0);
		}
		
		bb.putShort(tuplesPerPage);
		bb.putShort((short) tableBytes.length);
		bb.putShort((short) keyBytes.length);
		
		final long bodyLength = bb.capacity() + tableBytes.length + keyBytes.length;
		final long headerLength = appendRequestPackageHeader(bodyLength, outputStream);

		// Write body
		outputStream.write(bb.array());
		outputStream.write(tableBytes);
		outputStream.write(keyBytes);
		
		return headerLength + bodyLength;
	} catch (IOException e) {
		throw new PackageEncodeException("Got exception while converting package into bytes", e);
	}	
}
 
Example 14
Source File: TrueTypeFont.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private void setStyle(ByteBuffer os_2Table) {
        /* fsSelection is unsigned short at buffer offset 62 */
        if (os_2Table == null || os_2Table.capacity() < 64) {
            super.setStyle();
            return;
        }
        int fsSelection = os_2Table.getChar(62) & 0xffff;
        int italic  = fsSelection & fsSelectionItalicBit;
        int bold    = fsSelection & fsSelectionBoldBit;
        int regular = fsSelection & fsSelectionRegularBit;
//      System.out.println("platname="+platName+" font="+fullName+
//                         " family="+familyName+
//                         " R="+regular+" I="+italic+" B="+bold);
        if (regular!=0 && ((italic|bold)!=0)) {
            /* This is inconsistent. Try using the font name algorithm */
            super.setStyle();
            return;
        } else if ((regular|italic|bold) == 0) {
            /* No style specified. Try using the font name algorithm */
            super.setStyle();
            return;
        }
        switch (bold|italic) {
        case fsSelectionItalicBit:
            style = Font.ITALIC;
            break;
        case fsSelectionBoldBit:
            if (FontUtilities.isSolaris && platName.endsWith("HG-GothicB.ttf")) {
                /* Workaround for Solaris's use of a JA font that's marked as
                 * being designed bold, but is used as a PLAIN font.
                 */
                style = Font.PLAIN;
            } else {
                style = Font.BOLD;
            }
            break;
        case fsSelectionBoldBit|fsSelectionItalicBit:
            style = Font.BOLD|Font.ITALIC;
        }
    }
 
Example 15
Source File: DataInputDecoder.java    From stratosphere with Apache License 2.0 5 votes vote down vote up
@Override
public ByteBuffer readBytes(ByteBuffer old) throws IOException {
	int length = readInt();
	ByteBuffer result;
	if (old != null && length <= old.capacity() && old.hasArray()) {
		result = old;
		result.clear();
	} else {
		result = ByteBuffer.allocate(length);
	}
	in.readFully(result.array(), result.arrayOffset() + result.position(), length);
	result.limit(length);
	return result;
}
 
Example 16
Source File: Fitness.java    From OpenFit with MIT License 4 votes vote down vote up
@SuppressWarnings("unused")
public static void parseData() {
    Log.d(LOG_TAG, "Parsing data");
    ByteBuffer buffer = ByteBuffer.wrap(fitnessStream.toByteArray());
    buffer = buffer.order(ByteOrder.LITTLE_ENDIAN);

    if(buffer.capacity() < 14) {
        return;
    }

    byte msgType = buffer.get();
    int msgSize = buffer.getInt();
    int byte4 = buffer.getInt();
    int byte1 = buffer.getInt();
    byte byteFF = buffer.get();
    Log.d(LOG_TAG, "type: " + msgType);
    Log.d(LOG_TAG, "msgSize: " + msgSize);

    while(buffer.hasRemaining()) {
        byte fitnessType = buffer.get();
        Log.d(LOG_TAG, "Fitness type: " + fitnessType);
        if(fitnessType ==  OpenFitData.DATA_TYPE_USER_PROFILE) {
            Log.d(LOG_TAG, "User Profile");
            parseUserProfile(buffer);
        }
        else if(fitnessType ==  OpenFitData.DATA_TYPE_PEDOMETER_PROFILE) {
            Log.d(LOG_TAG, "Pedometer Profile");
            parsePedometerProfile(buffer);
        }
        else if(fitnessType ==  OpenFitData.DATA_TYPE_PEDO_RESULTRECORD) {
            Log.d(LOG_TAG, "Pedometer Result Record");
            parsePedoResultRecord(buffer);
        }
        else if(fitnessType ==  OpenFitData.DATA_TYPE_HEARTRATE_RESULTRECORD) {
            Log.d(LOG_TAG, "Heartrate Result Record");
            parseHeartrateResultRecord(buffer);
        }
        else if(fitnessType ==  OpenFitData.DATA_TYPE_PEDO_INFO) {
            Log.d(LOG_TAG, "Pedometer Info");
            parsePedoInfo(buffer);
        }
        else if(fitnessType == OpenFitData.DATA_TYPE_SLEEP_INFO) {
            Log.d(LOG_TAG, "Sleep Info");
            parseSleepInfo(buffer);
        }
        else if(fitnessType == OpenFitData.DATA_TYPE_SLEEP_RESULTRECORD) {
            Log.d(LOG_TAG, "Sleep Result Record");
            parseSleepResultRecord(buffer);
        }
        else if(fitnessType == OpenFitData.DATA_TYPE_COACHING_VARS) {
            Log.d(LOG_TAG, "Coaching Vars");
            parseCoachingVars(buffer);
        }
        else if(fitnessType == OpenFitData.DATA_TYPE_COACHING_EXERCISERESULT) {
            Log.d(LOG_TAG, "Coaching Excercise Result");
            parseCoachingExerciseResult(buffer);
        }
        else if(fitnessType == OpenFitData.DATA_TYPE_COACHING_RESULTRECORD) {
            Log.d(LOG_TAG, "Coaching Result Record");
            parseCoachingResultRecord(buffer);

        }
        else {
            Log.d(LOG_TAG, "Unsupported: " + fitnessType);
            //logBuffer(buffer);
            depleteBuffer(buffer);
        }
    }

    Log.d(LOG_TAG, "remaining buffer: " + buffer.remaining());
}
 
Example 17
Source File: CacheObjectAdapter.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param cacheObjType Cache object type.
 * @param buf Buffer to write value to.
 * @param off Offset in source binary data.
 * @param len Length of the data to write.
 * @param valBytes Binary data.
 * @param start Start offset in binary data.
 * @return {@code True} if data were successfully written.
 * @throws IgniteCheckedException If failed.
 */
public static boolean putValue(byte cacheObjType,
    final ByteBuffer buf,
    int off,
    int len,
    byte[] valBytes,
    final int start)
    throws IgniteCheckedException
{
    int dataLen = valBytes.length;

    if (buf.remaining() < len)
        return false;

    final int headSize = 5; // 4 bytes len + 1 byte type

    if (off == 0 && len >= headSize) {
        buf.putInt(dataLen);
        buf.put(cacheObjType);

        len -= headSize;
    }
    else if (off >= headSize)
        off -= headSize;
    else {
        // Partial header write.
        final ByteBuffer head = ByteBuffer.allocate(headSize);

        head.order(buf.order());

        head.putInt(dataLen);
        head.put(cacheObjType);

        head.position(off);

        if (len < head.capacity())
            head.limit(off + Math.min(len, head.capacity() - off));

        buf.put(head);

        if (head.limit() < headSize)
            return true;

        len -= headSize - off;
        off = 0;
    }

    buf.put(valBytes, start + off, len);

    return true;
}
 
Example 18
Source File: MapedFile.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
public static void clean(final ByteBuffer buffer) {
    if (buffer == null || !buffer.isDirect() || buffer.capacity() == 0)
        return;
    invoke(invoke(viewed(buffer), "cleaner"), "clean");
}
 
Example 19
Source File: BufferStructureBuilder.java    From JglTF with MIT License 3 votes vote down vote up
/**
 * Apply the given byte stride to the given buffer and return the result
 * as a new buffer. The directness or byte order of the result are not
 * specified.<br>
 * <br>
 * This is supposed to be applied to accessor byte buffers. For example:
 * For an an accessor with 2D float elements, the old byte stride will 
 * be 2 * 4, and the old byte buffer may contain 24 bytes. Calling this
 * method with a new byte stride of 3 * 4 will cause padding bytes to
 * be inserted in the returned buffer: 
 * <pre><code>
 * oldByteBuffer: |X0|Y0|X1|Y1|X2|Y2|
 * newByteBuffer: |X0|Y0|..|X1|Y1|..|X2|Y2|..|
 * </code></pre>
 *  
 * @param oldByteBuffer The old byte buffer 
 * @param oldByteStride The old byte stride
 * @param newByteStride The new byte stride
 * @return The new byte buffer
 */
private static ByteBuffer applyByteStride(
    ByteBuffer oldByteBuffer, int oldByteStride, int newByteStride)
{
    int count = oldByteBuffer.capacity() / oldByteStride;
    ByteBuffer newByteBuffer = ByteBuffer.allocate(count * newByteStride);
    for (int i = 0; i < count; i++)
    {
        int srcPos = i * oldByteStride;
        int dstPos = i * newByteStride;
        Buffers.bufferCopy(oldByteBuffer, srcPos, 
            newByteBuffer, dstPos, oldByteStride);
    }
    return newByteBuffer;
}
 
Example 20
Source File: ByteBufferArrayData.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Constructor
 *
 * @param buf ByteBuffer to create array data with.
 */
ByteBufferArrayData(final ByteBuffer buf) {
    super(buf.capacity());
    this.buf = buf;
}