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

The following examples show how to use java.nio.ByteBuffer#asReadOnlyBuffer() . 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: AesGcmTest.java    From wycheproof with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadOnlyByteBuffer() throws Exception {
  for (GcmTestVector test : getTestVectors()) {
    // Encryption
    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    ByteBuffer ptBuffer = ByteBuffer.wrap(test.pt).asReadOnlyBuffer();
    cipher.init(Cipher.ENCRYPT_MODE, test.key, test.parameters);
    int outputSize = cipher.getOutputSize(test.pt.length);
    ByteBuffer ctBuffer = ByteBuffer.allocate(outputSize);
    cipher.updateAAD(test.aad);
    cipher.doFinal(ptBuffer, ctBuffer);
    assertEquals(test.ctHex, TestUtil.byteBufferToHex(ctBuffer));

    // Decryption
    ctBuffer.flip();
    ctBuffer = ctBuffer.asReadOnlyBuffer();
    cipher.init(Cipher.DECRYPT_MODE, test.key, test.parameters);
    outputSize = cipher.getOutputSize(test.ct.length);
    ByteBuffer decrypted = ByteBuffer.allocate(outputSize);
    cipher.updateAAD(test.aad);
    cipher.doFinal(ctBuffer, decrypted);
    assertEquals(test.ptHex, TestUtil.byteBufferToHex(decrypted));
  }
}
 
Example 2
Source File: WritableBufferImplTest.java    From incubator-datasketches-memory with Apache License 2.0 6 votes vote down vote up
@Test
public void checkWrapWithDirectBBReadonly() {
  int memCapacity = 64;
  ByteBuffer byteBuf = ByteBuffer.allocateDirect(memCapacity);
  byteBuf.order(ByteOrder.nativeOrder());

  for (int i = 0; i < memCapacity; i++) {
    byteBuf.put(i, (byte) i);
  }
  ByteBuffer byteBufRO = byteBuf.asReadOnlyBuffer();
  byteBufRO.order(ByteOrder.nativeOrder());

  Buffer buf = Buffer.wrap(byteBufRO);

  for (int i = 0; i < memCapacity; i++) {
    assertEquals(buf.getByte(), byteBuf.get(i));
  }

  //println(mem.toHexString("HeapBB", 0, memCapacity));
}
 
Example 3
Source File: AbstractByteBufTest.java    From flink with Apache License 2.0 6 votes vote down vote up
private void testGetReadOnlyDst(boolean direct) {
    byte[] bytes = { 'a', 'b', 'c', 'd' };

    ByteBuf buffer = newBuffer(bytes.length);
    buffer.writeBytes(bytes);

    ByteBuffer dst = direct ? ByteBuffer.allocateDirect(bytes.length) : ByteBuffer.allocate(bytes.length);
    ByteBuffer readOnlyDst = dst.asReadOnlyBuffer();
    try {
        buffer.getBytes(0, readOnlyDst);
        fail();
    } catch (ReadOnlyBufferException e) {
        // expected
    }
    assertEquals(0, readOnlyDst.position());
    buffer.release();
}
 
Example 4
Source File: BinaryUtils.java    From markdown-image-kit with MIT License 6 votes vote down vote up
/**
 * Returns a copy of all the bytes from the given <code>ByteBuffer</code>, from the beginning to
 * the buffer's limit; or null if the input is null.
 * <p>
 * The internal states of the given byte buffer will be restored when this method completes
 * execution.
 * <p>
 * When handling <code>ByteBuffer</code> from user's input, it's typical to call the
 * {@link #copyBytesFrom(ByteBuffer)} instead of {@link #copyAllBytesFrom(ByteBuffer)} so as to
 * account for the position of the input <code>ByteBuffer</code>. The opposite is typically
 * true, however, when handling <code>ByteBuffer</code> from withint the unmarshallers of the
 * low-level clients.
 */
public static byte[] copyAllBytesFrom(ByteBuffer bb) {
    if (bb == null) {
        return null;
    }

    if (bb.hasArray()) {
        return Arrays.copyOfRange(bb.array(), bb.arrayOffset(), bb.arrayOffset() + bb.limit());
    }

    ByteBuffer copy = bb.asReadOnlyBuffer();
    copy.rewind();

    byte[] dst = new byte[copy.remaining()];
    copy.get(dst);
    return dst;
}
 
Example 5
Source File: TofinoPipelineProgrammable.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public ByteBuffer createDeviceDataBuffer(PiPipeconf pipeconf) {
    List<ByteBuffer> buffers = Lists.newLinkedList();

    if (pipeconf.extension(RAW_DEVICE_CONFIG).isPresent()) {
        buffers.add(rawDeviceConfig(pipeconf));
    } else {
        try {
            buffers.add(nameBuffer(pipeconf));
            buffers.add(extensionBuffer(pipeconf, TOFINO_BIN));
            buffers.add(extensionBuffer(pipeconf, TOFINO_CONTEXT_JSON));
        } catch (ExtensionException e) {
            return null;
        }
    }

    // Concatenate buffers (flip so they can be read).
    int len = buffers.stream().mapToInt(Buffer::limit).sum();
    ByteBuffer deviceData = ByteBuffer.allocate(len);
    buffers.forEach(b -> deviceData.put((ByteBuffer) b.flip()));
    deviceData.flip();

    return deviceData.asReadOnlyBuffer();
}
 
Example 6
Source File: BuffersTestingKit.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Relocates a {@code [position, limit)} region of the given buffer to
 * corresponding region in a new buffer starting with provided {@code
 * newPosition}.
 *
 * <p> Might be useful to make sure ByteBuffer's users do not rely on any
 * absolute positions, but solely on what's reported by position(), limit().
 *
 * <p> The contents between the given buffer and the returned one are not
 * shared.
 */
public static ByteBuffer relocate(ByteBuffer buffer, int newPosition,
                                  int newCapacity) {
    int oldPosition = buffer.position();
    int oldLimit = buffer.limit();

    if (newPosition + oldLimit - oldPosition > newCapacity) {
        throw new IllegalArgumentException();
    }

    ByteBuffer result;
    if (buffer.isDirect()) {
        result = ByteBuffer.allocateDirect(newCapacity);
    } else {
        result = allocate(newCapacity);
    }

    result.position(newPosition);
    result.put(buffer).limit(result.position()).position(newPosition);
    buffer.position(oldPosition);

    if (buffer.isReadOnly()) {
        return result.asReadOnlyBuffer();
    }
    return result;
}
 
Example 7
Source File: AbstractByteBufTest.java    From flink with Apache License 2.0 6 votes vote down vote up
private void testGetReadOnlyDst(boolean direct) {
    byte[] bytes = { 'a', 'b', 'c', 'd' };

    ByteBuf buffer = newBuffer(bytes.length);
    buffer.writeBytes(bytes);

    ByteBuffer dst = direct ? ByteBuffer.allocateDirect(bytes.length) : ByteBuffer.allocate(bytes.length);
    ByteBuffer readOnlyDst = dst.asReadOnlyBuffer();
    try {
        buffer.getBytes(0, readOnlyDst);
        fail();
    } catch (ReadOnlyBufferException e) {
        // expected
    }
    assertEquals(0, readOnlyDst.position());
    buffer.release();
}
 
Example 8
Source File: MessageBase.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static Message readGIOPBody(ORB orb,
                                   CorbaConnection connection,
                                   Message msg)
{
    ReadTimeouts readTimeouts =
                       orb.getORBData().getTransportTCPReadTimeouts();
    ByteBuffer buf = msg.getByteBuffer();

    buf.position(MessageBase.GIOPMessageHeaderLength);
    int msgSizeMinusHeader =
        msg.getSize() - MessageBase.GIOPMessageHeaderLength;
    try {
        buf = connection.read(buf,
                      GIOPMessageHeaderLength, msgSizeMinusHeader,
                      readTimeouts.get_max_time_to_wait());
    } catch (IOException e) {
        throw wrapper.ioexceptionWhenReadingConnection(e);
    }

    msg.setByteBuffer(buf);

    if (orb.giopDebugFlag) {
        dprint(".readGIOPBody: received message:");
        ByteBuffer viewBuffer = buf.asReadOnlyBuffer();
        viewBuffer.position(0).limit(msg.getSize());
        ByteBufferWithInfo bbwi = new ByteBufferWithInfo(orb, viewBuffer);
        CDRInputStream_1_0.printBuffer(bbwi);
    }

    return msg;
}
 
Example 9
Source File: GifHeaderParser.java    From clevertap-android-sdk with MIT License 5 votes vote down vote up
public GifHeaderParser setData(ByteBuffer data) {
    reset();
    rawData = data.asReadOnlyBuffer();
    rawData.position(0);
    rawData.order(ByteOrder.LITTLE_ENDIAN);
    return this;
}
 
Example 10
Source File: FakeKMS.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
public DecryptMapKey(ByteBuffer ctBuff, Map<String, String> ec) {
    cipherText = ctBuff.asReadOnlyBuffer();
    if (ec != null) {
        this.ec = Collections.unmodifiableMap(new HashMap<>(ec));
    } else {
        this.ec = Collections.emptyMap();
    }
}
 
Example 11
Source File: AttributeValueMarshaller.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
/**
 * @see #marshall(AttributeValue)
 */
public static AttributeValue unmarshall(final ByteBuffer plainText) {
    try (final DataInputStream in = new DataInputStream(
            new ByteBufferInputStream(plainText.asReadOnlyBuffer()))) {
        return unmarshall(in);
    } catch (IOException ex) {
        // Due to the objects in use, an IOException is not possible.
        throw new RuntimeException("Unexpected exception", ex);
    }
}
 
Example 12
Source File: ChainUtils.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
public static SequencedElement getElement(final long sequence, final ByteBuffer payload) {
  return new SequencedElement() {
    @Override
    public long getSequenceNumber() {
      return sequence;
    }

    @Override
    public ByteBuffer getPayload() {
      return payload.asReadOnlyBuffer();
    }
  };
}
 
Example 13
Source File: WritableBufferImplTest.java    From incubator-datasketches-memory with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = ReadOnlyException.class)
public void checkWrapWithBBReadonly2() {
  int memCapacity = 64;
  ByteBuffer byteBuf = ByteBuffer.allocate(memCapacity);
  byteBuf.order(ByteOrder.nativeOrder());
  ByteBuffer byteBufRO = byteBuf.asReadOnlyBuffer();

  WritableBuffer.wrap(byteBufRO);
}
 
Example 14
Source File: AttributeValueMarshaller.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
private static void writeBytes(ByteBuffer value, final DataOutputStream out) throws IOException {
    value = value.asReadOnlyBuffer();
    value.rewind();
    out.writeInt(value.remaining());
    while (value.hasRemaining()) {
        out.writeByte(value.get());
    }
}
 
Example 15
Source File: ReadOnlyByteBuffer.java    From servicetalk with Apache License 2.0 4 votes vote down vote up
private static ByteBuffer asReadOnlyByteBuffer(ByteBuffer buffer) {
    return buffer.isReadOnly() ? buffer : buffer.asReadOnlyBuffer();
}
 
Example 16
Source File: ByteString.java    From protostuff with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs a new read-only {@code java.nio.ByteBuffer} with the same backing byte array.
 */
public ByteBuffer asReadOnlyByteBuffer()
{
    final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
    return byteBuffer.asReadOnlyBuffer();
}
 
Example 17
Source File: AuthOutput.java    From hivemq-community-edition with Apache License 2.0 4 votes vote down vote up
public void continueAuthentication(final @NotNull ByteBuffer authenticationData) {
    Preconditions.checkNotNull(authenticationData, "Authentication data must never be null");
    continueAuthentication();
    this.authenticationData = authenticationData.asReadOnlyBuffer();
}
 
Example 18
Source File: WrappedImmutableConciseBitmap.java    From bytebuffer-collections with Apache License 2.0 4 votes vote down vote up
public WrappedImmutableConciseBitmap(ByteBuffer byteBuffer)
{
  this.bitmap = new ImmutableConciseSet(byteBuffer.asReadOnlyBuffer());
}
 
Example 19
Source File: BufferTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
private void testByteBufferByteOrder(ByteBuffer b, boolean readOnly) throws Exception {
    if (readOnly) {
        b = b.asReadOnlyBuffer();
    }
    // allocate/allocateDirect/map always returns a big-endian buffer.
    assertEquals(ByteOrder.BIG_ENDIAN, b.order());

    // wrap always returns a big-endian buffer.
    assertEquals(ByteOrder.BIG_ENDIAN, b.wrap(new byte[10]).order());

    // duplicate always returns a big-endian buffer.
    b.order(ByteOrder.BIG_ENDIAN);
    assertEquals(ByteOrder.BIG_ENDIAN, b.duplicate().order());
    b.order(ByteOrder.LITTLE_ENDIAN);
    assertEquals(ByteOrder.BIG_ENDIAN, b.duplicate().order());

    // slice always returns a big-endian buffer.
    b.order(ByteOrder.BIG_ENDIAN);
    assertEquals(ByteOrder.BIG_ENDIAN, b.slice().order());
    b.order(ByteOrder.LITTLE_ENDIAN);
    assertEquals(ByteOrder.BIG_ENDIAN, b.slice().order());

    // asXBuffer always returns a current-endian buffer.
    b.order(ByteOrder.BIG_ENDIAN);
    assertEquals(ByteOrder.BIG_ENDIAN, b.asCharBuffer().order());
    assertEquals(ByteOrder.BIG_ENDIAN, b.asDoubleBuffer().order());
    assertEquals(ByteOrder.BIG_ENDIAN, b.asFloatBuffer().order());
    assertEquals(ByteOrder.BIG_ENDIAN, b.asIntBuffer().order());
    assertEquals(ByteOrder.BIG_ENDIAN, b.asLongBuffer().order());
    assertEquals(ByteOrder.BIG_ENDIAN, b.asShortBuffer().order());
    assertEquals(ByteOrder.BIG_ENDIAN, b.asReadOnlyBuffer().order());
    b.order(ByteOrder.LITTLE_ENDIAN);
    assertEquals(ByteOrder.LITTLE_ENDIAN, b.asCharBuffer().order());
    assertEquals(ByteOrder.LITTLE_ENDIAN, b.asDoubleBuffer().order());
    assertEquals(ByteOrder.LITTLE_ENDIAN, b.asFloatBuffer().order());
    assertEquals(ByteOrder.LITTLE_ENDIAN, b.asIntBuffer().order());
    assertEquals(ByteOrder.LITTLE_ENDIAN, b.asLongBuffer().order());
    assertEquals(ByteOrder.LITTLE_ENDIAN, b.asShortBuffer().order());
    // ...except for asReadOnlyBuffer, which always returns a big-endian buffer.
    assertEquals(ByteOrder.BIG_ENDIAN, b.asReadOnlyBuffer().order());
}
 
Example 20
Source File: CharsetDecoderTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
private ByteBuffer readOnly(ByteBuffer b) {
    if (null == b) {
        return null;
    }
    return b.asReadOnlyBuffer();
}