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

The following are Jave code examples for showing how to use duplicate() 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: sstable-adaptor   File: MapSerializer.java   View Source Code Vote up 6 votes
/**
 * Given a serialized map, gets the value associated with a given key.
 * @param serializedMap a serialized map
 * @param serializedKey a serialized key
 * @param keyType the key type for the map
 * @return the value associated with the key if one exists, null otherwise
 */
public ByteBuffer getSerializedValue(ByteBuffer serializedMap, ByteBuffer serializedKey, AbstractType keyType)
{
    try
    {
        ByteBuffer input = serializedMap.duplicate();
        int n = readCollectionSize(input, ProtocolVersion.V3);
        for (int i = 0; i < n; i++)
        {
            ByteBuffer kbb = readValue(input, ProtocolVersion.V3);
            ByteBuffer vbb = readValue(input, ProtocolVersion.V3);
            int comparison = keyType.compare(kbb, serializedKey);
            if (comparison == 0)
                return vbb;
            else if (comparison > 0)
                // since the map is in sorted order, we know we've gone too far and the element doesn't exist
                return null;
        }
        return null;
    }
    catch (BufferUnderflowException e)
    {
        throw new MarshalException("Not enough bytes to read a map");
    }
}
 
Example 2
Project: minebox   File: SingleFileBucket.java   View Source Code Vote up 6 votes
private boolean stillAllZeroes(ByteBuffer message) {
    if (fileWasZero) {
        final ByteBuffer checkForZeroes = message.duplicate();
        checkForZeroes.rewind();
        while (checkForZeroes.hasRemaining()) {
            final byte b = checkForZeroes.get();
            if (b != 0) {
                fileWasZero = false;
            }
        }
        if (fileWasZero) {
            LOGGER.debug("saved some resources by not writing zeroes");
            return true;
        }
    }
    return false;
}
 
Example 3
Project: simulacron   File: CqlMapper.java   View Source Code Vote up 6 votes
@Override
Map<K, V> decodeInternal(ByteBuffer input) {
  if (input == null || input.remaining() == 0) {
    return new LinkedHashMap<>();
  }
  try {
    ByteBuffer bytes = input.duplicate();
    int n = readSize(bytes);
    Map<K, V> m = new LinkedHashMap<>(n);
    for (int i = 0; i < n; i++) {
      ByteBuffer kbb = readValue(bytes);
      ByteBuffer vbb = readValue(bytes);
      m.put(keyCodec.decode(kbb), valueCodec.decode(vbb));
    }
    return m;
  } catch (BufferUnderflowException | IllegalArgumentException e) {
    throw new InvalidTypeException("Not enough bytes to deserialize a map", e);
  }
}
 
Example 4
Project: simulacron   File: CqlMapper.java   View Source Code Vote up 6 votes
@Override
Tuple decodeInternal(ByteBuffer input) {
  if (input == null) {
    return null;
  }
  ByteBuffer bytes = input.duplicate();
  int numberOfValues = tupleType.fieldTypes.size();
  List<Object> values = new ArrayList<>(tupleType.fieldTypes.size());
  try {
    for (int i = 0; bytes.hasRemaining() && i < numberOfValues; i++) {
      int n = bytes.getInt();
      ByteBuffer element = n < 0 ? null : readBytes(bytes, n);
      values.add(elementCodecs.get(i).decode(element));
    }
  } catch (BufferUnderflowException | IllegalArgumentException e) {
    throw new InvalidTypeException("Not enough bytes top deserialize a tuple", e);
  }
  return new Tuple(tupleType, values);
}
 
Example 5
Project: sstable-adaptor   File: ListSerializer.java   View Source Code Vote up 6 votes
public void validateForNativeProtocol(ByteBuffer bytes, ProtocolVersion version)
{
    try
    {
        ByteBuffer input = bytes.duplicate();
        int n = readCollectionSize(input, version);
        for (int i = 0; i < n; i++)
            elements.validate(readValue(input, version));

        if (input.hasRemaining())
            throw new MarshalException("Unexpected extraneous bytes after list value");
    }
    catch (BufferUnderflowException e)
    {
        throw new MarshalException("Not enough bytes to read a list");
    }
}
 
Example 6
Project: elasticsearch_my   File: ChannelsTests.java   View Source Code Vote up 5 votes
@Override
public int read(ByteBuffer dst) throws IOException {
    // delay buffer read..
    int willActuallyRead = randomInt(dst.remaining());
    ByteBuffer mockDst = dst.duplicate();
    mockDst.limit(mockDst.position() + willActuallyRead);
    try {
        return delegate.read(mockDst);
    } finally {
        dst.position(mockDst.position());
    }
}
 
Example 7
Project: kafka-0.11.0.0-src-with-comment   File: Utils.java   View Source Code Vote up 5 votes
/**
 * Read a size-delimited byte buffer starting at the given offset.
 * @param buffer Buffer containing the size and data
 * @param start Offset in the buffer to read from
 * @return A slice of the buffer containing only the delimited data (excluding the size)
 */
public static ByteBuffer sizeDelimited(ByteBuffer buffer, int start) {
    int size = buffer.getInt(start);
    if (size < 0) {
        return null;
    } else {
        ByteBuffer b = buffer.duplicate();
        b.position(start + 4);
        b = b.slice();
        b.limit(size);
        b.rewind();
        return b;
    }
}
 
Example 8
Project: memory   File: BufferInvariantsTest.java   View Source Code Vote up 5 votes
@Test
  public void testBB() {
    int n = 25;
    ByteBuffer bb = ByteBuffer.allocate(n);
    for (byte i = 0; i < n; i++) { bb.put(i, i); }
    assertEquals(bb.position(), 0);
    assertEquals(bb.limit(), n);
    assertEquals(bb.get(0), 0);
//    print("Orig : ");
//    printbb(bb);

    bb.limit(20);
    bb.position(5);
    assertEquals(bb.remaining(), 15);
//    print("Set  : ");
//    printbb(bb);

    ByteBuffer dup = bb.duplicate();
    assertEquals(dup.position(), 5);
    assertEquals(dup.limit(), 20);
    assertEquals(dup.capacity(), 25);
//    print("Dup  : ");
//    printbb(dup);

    ByteBuffer sl = bb.slice();
    assertEquals(sl.position(), 0);
    assertEquals(sl.limit(), 15);
    assertEquals(sl.capacity(), 15);
//    print("Slice: ");
//    printbb(sl);
  }
 
Example 9
Project: rtmp-rtsp-stream-client-java   File: RtspCamera2.java   View Source Code Vote up 5 votes
@Override
protected void onSPSandPPSRtp(ByteBuffer sps, ByteBuffer pps) {
  ByteBuffer newSps = sps.duplicate();
  ByteBuffer newPps = pps.duplicate();
  rtspClient.setSPSandPPS(newSps, newPps);
  rtspClient.connect();
}
 
Example 10
Project: sstable-adaptor   File: ByteBufferUtil.java   View Source Code Vote up 5 votes
public static ByteBuffer readBytes(ByteBuffer bb, int length)
{
    ByteBuffer copy = bb.duplicate();
    copy.limit(copy.position() + length);
    bb.position(bb.position() + length);
    return copy;
}
 
Example 11
Project: sstable-adaptor   File: DecimalSerializer.java   View Source Code Vote up 5 votes
public BigDecimal deserialize(ByteBuffer bytes)
{
    if (bytes == null || bytes.remaining() == 0)
        return null;

    // do not consume the contents of the ByteBuffer
    bytes = bytes.duplicate();
    int scale = bytes.getInt();
    byte[] bibytes = new byte[bytes.remaining()];
    bytes.get(bibytes);

    BigInteger bi = new BigInteger(bibytes);
    return new BigDecimal(bi, scale);
}
 
Example 12
Project: jdk8u-jdk   File: SameBuffer.java   View Source Code Vote up 5 votes
private void runGCMWithSameBuffer(int mode, ByteBuffer buffer,
        int txtOffset, int length, AlgorithmParameters params)
        throws Exception {

    // allocate a separate buffer
    Cipher cipher = createCipher(mode, params);
    ByteBuffer outBB = ByteBuffer.allocateDirect(
            cipher.getOutputSize(length));

    // first, generate the cipher text at an allocated buffer
    buffer.flip();
    buffer.limit(AADLength);
    cipher.updateAAD(buffer);
    buffer.limit(AADLength + txtOffset + length);
    buffer.position(AADLength + txtOffset);
    cipher.doFinal(buffer, outBB);
    outBB.flip(); // cipher text in outBB

    // next, generate cipherText again in the same buffer
    Cipher anotherCipher = createCipher(mode, params);
    buffer.flip();
    buffer.limit(AADLength);
    anotherCipher.updateAAD(buffer);
    buffer.limit(AADLength + txtOffset + length);
    buffer.position(AADLength + txtOffset);

    // share textBuf context
    ByteBuffer buf2 = buffer.duplicate();
    buf2.limit(AADLength + txtOffset + anotherCipher.getOutputSize(length));
    int dataProcessed2 = anotherCipher.doFinal(buffer, buf2);
    buf2.position(AADLength + txtOffset);
    buf2.limit(AADLength + txtOffset + dataProcessed2);

    if (!buf2.equals(outBB)) {
        throw new RuntimeException(
                "Two results are not equal, mode:" + mode);
    }
}
 
Example 13
Project: live_master   File: SrsEncoder.java   View Source Code Vote up 5 votes
private void onEncodedAnnexbFrame(ByteBuffer es, MediaCodec.BufferInfo bi) {
    try {
        ByteBuffer record = es.duplicate();
        mp4Muxer.writeSampleData(videoMp4Track, record, bi);
        flvMuxer.writeSampleData(videoFlvTrack, es, bi);
    } catch (Exception e) {
        Log.e(TAG, "muxer write video sample failed.");
        e.printStackTrace();
    }
}
 
Example 14
Project: rtmp-rtsp-stream-client-java   File: RtspCamera1.java   View Source Code Vote up 5 votes
@Override
protected void onSPSandPPSRtp(ByteBuffer sps, ByteBuffer pps) {
  ByteBuffer newSps = sps.duplicate();
  ByteBuffer newPps = pps.duplicate();
  rtspClient.setSPSandPPS(newSps, newPps);
  rtspClient.connect();
}
 
Example 15
Project: sstable-adaptor   File: CompositeType.java   View Source Code Vote up 5 votes
public static List<ByteBuffer> splitName(ByteBuffer name)
{
    List<ByteBuffer> l = new ArrayList<>();
    ByteBuffer bb = name.duplicate();
    readStatic(bb);
    while (bb.remaining() > 0)
    {
        l.add(ByteBufferUtil.readBytesWithShortLength(bb));
        bb.get(); // skip end-of-component
    }
    return l;
}
 
Example 16
Project: sstable-adaptor   File: MapSerializer.java   View Source Code Vote up 5 votes
public Map<K, V> deserializeForNativeProtocol(ByteBuffer bytes, ProtocolVersion version)
{
    try
    {
        ByteBuffer input = bytes.duplicate();
        int n = readCollectionSize(input, version);

        if (n < 0)
            throw new MarshalException("The data cannot be deserialized as a map");

        // If the received bytes are not corresponding to a map, n might be a huge number.
        // In such a case we do not want to initialize the map with that initialCapacity as it can result
        // in an OOM when put is called (see CASSANDRA-12618). On the other hand we do not want to have to resize
        // the map if we can avoid it, so we put a reasonable limit on the initialCapacity.
        Map<K, V> m = new LinkedHashMap<K, V>(Math.min(n, 256));
        for (int i = 0; i < n; i++)
        {
            ByteBuffer kbb = readValue(input, version);
            keys.validate(kbb);

            ByteBuffer vbb = readValue(input, version);
            values.validate(vbb);

            m.put(keys.deserialize(kbb), values.deserialize(vbb));
        }
        if (input.hasRemaining())
            throw new MarshalException("Unexpected extraneous bytes after map value");
        return m;
    }
    catch (BufferUnderflowException e)
    {
        throw new MarshalException("Not enough bytes to read a map");
    }
}
 
Example 17
Project: airgram   File: NalUnitUtil.java   View Source Code Vote up 5 votes
/**
 * Discards data from the buffer up to the first SPS, where {@code data.position()} is interpreted
 * as the length of the buffer.
 * <p>
 * When the method returns, {@code data.position()} will contain the new length of the buffer. If
 * the buffer is not empty it is guaranteed to start with an SPS.
 *
 * @param data Buffer containing start code delimited NAL units.
 */
public static void discardToSps(ByteBuffer data) {
  int length = data.position();
  int consecutiveZeros = 0;
  int offset = 0;
  while (offset + 1 < length) {
    int value = data.get(offset) & 0xFF;
    if (consecutiveZeros == 3) {
      if (value == 1 && (data.get(offset + 1) & 0x1F) == NAL_UNIT_TYPE_SPS) {
        // Copy from this NAL unit onwards to the start of the buffer.
        ByteBuffer offsetData = data.duplicate();
        offsetData.position(offset - 3);
        offsetData.limit(length);
        data.position(0);
        data.put(offsetData);
        return;
      }
    } else if (value == 0) {
      consecutiveZeros++;
    }
    if (value != 0) {
      consecutiveZeros = 0;
    }
    offset++;
  }
  // Empty the buffer if the SPS NAL unit was not found.
  data.clear();
}
 
Example 18
Project: dble   File: ByteBufferUtil.java   View Source Code Vote up 4 votes
public static ByteBuffer readBytes(ByteBuffer bb, int length) {
    ByteBuffer copy = bb.duplicate();
    copy.limit(copy.position() + length);
    bb.position(bb.position() + length);
    return copy;
}
 
Example 19
Project: simulacron   File: CqlMapper.java   View Source Code Vote up 4 votes
@Override
ByteBuffer encodeInternal(ByteBuffer input) {
  return input.duplicate();
}
 
Example 20
Project: mycat-src-1.6.1-RELEASE   File: BytesTools.java   View Source Code Vote up 2 votes
/**
 * Returns a new byte array, copied from the given {@code buf},
 * from the index 0 (inclusive) to the limit (exclusive),
 * regardless of the current position.
 * The position and the other index parameters are not changed.
 *
 * @param buf a byte buffer
 * @return the byte array
 */
public static byte[] toBytes(ByteBuffer buf) {
    ByteBuffer dup = buf.duplicate();
    dup.position(0);
    return readBytes(dup);
}