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

The following examples show how to use java.nio.ByteBuffer#isReadOnly() . 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: ChannelImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public int transmit(ByteBuffer command, ByteBuffer response) throws CardException {
   this.checkClosed();
   this.card.checkExclusive();
   if (command != null && response != null) {
      if (response.isReadOnly()) {
         throw new ReadOnlyBufferException();
      } else if (command == response) {
         throw new IllegalArgumentException("command and response must not be the same object");
      } else if (response.remaining() < 258) {
         throw new IllegalArgumentException("Insufficient space in response buffer");
      } else {
         byte[] commandBytes = new byte[command.remaining()];
         command.get(commandBytes);
         byte[] responseBytes = this.doTransmit(commandBytes);
         response.put(responseBytes);
         return responseBytes.length;
      }
   } else {
      throw new NullPointerException();
   }
}
 
Example 2
Source File: IOUtil.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
static int read(FileDescriptor fd, ByteBuffer dst, long position,
                NativeDispatcher nd)
    throws IOException
{
    if (dst.isReadOnly())
        throw new IllegalArgumentException("Read-only buffer");
    if (dst instanceof DirectBuffer)
        return readIntoNativeBuffer(fd, dst, position, nd);

    // Substitute a native buffer
    ByteBuffer bb = Util.getTemporaryDirectBuffer(dst.remaining());
    try {
        int n = readIntoNativeBuffer(fd, bb, position, nd);
        bb.flip();
        if (n > 0)
            dst.put(bb);
        return n;
    } finally {
        Util.offerFirstTemporaryDirectBuffer(bb);
    }
}
 
Example 3
Source File: IOUtil.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
static int read(FileDescriptor fd, ByteBuffer dst, long position,
                NativeDispatcher nd)
    throws IOException
{
    if (dst.isReadOnly())
        throw new IllegalArgumentException("Read-only buffer");
    if (dst instanceof DirectBuffer)
        return readIntoNativeBuffer(fd, dst, position, nd);

    // Substitute a native buffer
    ByteBuffer bb = Util.getTemporaryDirectBuffer(dst.remaining());
    try {
        int n = readIntoNativeBuffer(fd, bb, position, nd);
        bb.flip();
        if (n > 0)
            dst.put(bb);
        return n;
    } finally {
        Util.offerFirstTemporaryDirectBuffer(bb);
    }
}
 
Example 4
Source File: AccessByteBuffer.java    From incubator-datasketches-memory with Apache License 2.0 6 votes vote down vote up
/**
 * The given ByteBuffer may be either readOnly or writable
 * @param byteBuf the given ByteBuffer
 */
AccessByteBuffer(final ByteBuffer byteBuf) {
  capacityBytes = byteBuf.capacity();
  resourceReadOnly = byteBuf.isReadOnly();
  byteOrder = byteBuf.order();
  final boolean direct = byteBuf.isDirect();
  if (direct) {
    nativeBaseOffset = ((sun.nio.ch.DirectBuffer) byteBuf).address();
    unsafeObj = null;
    regionOffset = 0L; //address() is already adjusted for direct slices, so regionOffset = 0
  } else {
    nativeBaseOffset = 0L;
    // ByteBuffer.arrayOffset() and ByteBuffer.array() throw ReadOnlyBufferException if
    // ByteBuffer is read-only. This uses reflection for both writable and read-only cases.
    // Includes the slice() offset for heap.
    regionOffset = unsafe.getInt(byteBuf, BYTE_BUFFER_OFFSET_FIELD_OFFSET);
    unsafeObj = unsafe.getObject(byteBuf, BYTE_BUFFER_HB_FIELD_OFFSET);
  }
}
 
Example 5
Source File: IOUtil.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
static int read(FileDescriptor fd, ByteBuffer dst, long position,
                NativeDispatcher nd)
    throws IOException
{
    if (dst.isReadOnly())
        throw new IllegalArgumentException("Read-only buffer");
    if (dst instanceof DirectBuffer)
        return readIntoNativeBuffer(fd, dst, position, nd);

    // Substitute a native buffer
    ByteBuffer bb = Util.getTemporaryDirectBuffer(dst.remaining());
    try {
        int n = readIntoNativeBuffer(fd, bb, position, nd);
        bb.flip();
        if (n > 0)
            dst.put(bb);
        return n;
    } finally {
        Util.offerFirstTemporaryDirectBuffer(bb);
    }
}
 
Example 6
Source File: CachedBufferAllocator.java    From craft-atom with MIT License 6 votes vote down vote up
private void free(ByteBuffer oldBuf) {
    if ((oldBuf == null) || ((maxCachedBufferSize != 0) && (oldBuf.capacity() > maxCachedBufferSize))
            || oldBuf.isReadOnly() || isDerived() || (Thread.currentThread() != ownerThread)) {
        return;
    }

    // Add to the cache.
    Queue<CachedBuffer> pool;

    if (oldBuf.isDirect()) {
        pool = directBuffers.get().get(oldBuf.capacity());
    } else {
        pool = heapBuffers.get().get(oldBuf.capacity());
    }

    if (pool == null) {
        return;
    }

    // Restrict the size of the pool to prevent OOM.
    if ((maxPoolSize == 0) || (pool.size() < maxPoolSize)) {
        pool.offer(new CachedBuffer(oldBuf));
    }
}
 
Example 7
Source File: HeightMapGenerator.java    From Mundus with Apache License 2.0 5 votes vote down vote up
private float[] heightColorsToMap(final ByteBuffer data, final Pixmap.Format format, int width, int height,
        float maxHeight) {
    final int bytesPerColor = (format == Pixmap.Format.RGB888 ? 3 : (format == Pixmap.Format.RGBA8888 ? 4 : 0));
    if (bytesPerColor == 0) throw new GdxRuntimeException("Unsupported format, should be either RGB8 or RGBA8");
    if (data.remaining() < (width * height * bytesPerColor)) throw new GdxRuntimeException("Incorrect map size");

    final int startPos = data.position();
    byte[] source = null;
    int sourceOffset = 0;
    if (data.hasArray() && !data.isReadOnly()) {
        source = data.array();
        sourceOffset = data.arrayOffset() + startPos;
    } else {
        source = new byte[width * height * bytesPerColor];
        data.get(source);
        data.position(startPos);
    }

    float[] dest = new float[width * height];
    for (int i = 0; i < dest.length; ++i) {
        int v = source[sourceOffset + i * bytesPerColor];
        v = v < 0 ? 256 + v : v;
        dest[i] = maxHeight * ((float) v / 255f);
    }

    return dest;
}
 
Example 8
Source File: AsynchronousSocketChannelImpl.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final <A> void read(ByteBuffer dst,
                           long timeout,
                           TimeUnit unit,
                           A attachment,
                           CompletionHandler<Integer,? super A> handler)
{
    if (handler == null)
        throw new NullPointerException("'handler' is null");
    if (dst.isReadOnly())
        throw new IllegalArgumentException("Read-only buffer");
    read(false, dst, null, timeout, unit, attachment, handler);
}
 
Example 9
Source File: AsynchronousSocketChannelImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final <A> void read(ByteBuffer dst,
                           long timeout,
                           TimeUnit unit,
                           A attachment,
                           CompletionHandler<Integer,? super A> handler)
{
    if (handler == null)
        throw new NullPointerException("'handler' is null");
    if (dst.isReadOnly())
        throw new IllegalArgumentException("Read-only buffer");
    read(false, dst, null, timeout, unit, attachment, handler);
}
 
Example 10
Source File: AsynchronousSocketChannelImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final <A> void read(ByteBuffer dst,
                           long timeout,
                           TimeUnit unit,
                           A attachment,
                           CompletionHandler<Integer,? super A> handler)
{
    if (handler == null)
        throw new NullPointerException("'handler' is null");
    if (dst.isReadOnly())
        throw new IllegalArgumentException("Read-only buffer");
    read(false, dst, null, timeout, unit, attachment, handler);
}
 
Example 11
Source File: DirectChannelBufferFactory.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public ChannelBuffer getBuffer(ByteBuffer nioBuffer) {
    if (!nioBuffer.isReadOnly() && nioBuffer.isDirect()) {
        return ChannelBuffers.wrappedBuffer(nioBuffer);
    }

    ChannelBuffer buf = getBuffer(nioBuffer.remaining());
    int pos = nioBuffer.position();
    buf.writeBytes(nioBuffer);
    nioBuffer.position(pos);
    return buf;
}
 
Example 12
Source File: Checksum.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
/**
 * Computes checksum for give data.
 * @param data input data.
 * @return ChecksumData computed for input data.
 * @throws OzoneChecksumException thrown when ChecksumType is not recognized
 */
public ChecksumData computeChecksum(ByteBuffer data)
    throws OzoneChecksumException {
  if (!data.isReadOnly()) {
    data = data.asReadOnlyBuffer();
  }
  return computeChecksum(ChunkBuffer.wrap(data));
}
 
Example 13
Source File: IOUtil.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
static int read(FileDescriptor fd, ByteBuffer dst, long position,
                boolean directIO, int alignment, NativeDispatcher nd)
    throws IOException
{
    if (dst.isReadOnly())
        throw new IllegalArgumentException("Read-only buffer");
    if (dst instanceof DirectBuffer)
        return readIntoNativeBuffer(fd, dst, position, directIO, alignment, nd);

    // Substitute a native buffer
    ByteBuffer bb;
    int rem = dst.remaining();
    if (directIO) {
        Util.checkRemainingBufferSizeAligned(rem, alignment);
        bb = Util.getTemporaryAlignedDirectBuffer(rem, alignment);
    } else {
        bb = Util.getTemporaryDirectBuffer(rem);
    }
    try {
        int n = readIntoNativeBuffer(fd, bb, position, directIO, alignment,nd);
        bb.flip();
        if (n > 0)
            dst.put(bb);
        return n;
    } finally {
        Util.offerFirstTemporaryDirectBuffer(bb);
    }
}
 
Example 14
Source File: Cipher.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Continues a multiple-part encryption or decryption operation
 * (depending on how this cipher was initialized), processing another data
 * part.
 *
 * <p>All <code>input.remaining()</code> bytes starting at
 * <code>input.position()</code> are processed. The result is stored
 * in the output buffer.
 * 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, 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.
 * In this case, repeat this call with a larger output buffer. Use
 * {@link #getOutputSize(int) getOutputSize} to determine how big
 * the output buffer should be.
 *
 * <p>Note: this method should be copy-safe, which means the
 * <code>input</code> and <code>output</code> buffers can reference
 * the same block of memory and no unprocessed input data is overwritten
 * when the result is copied into the output buffer.
 *
 * @param input the input ByteBuffer
 * @param output the output ByteByffer
 *
 * @return the number of bytes stored in <code>output</code>
 *
 * @exception IllegalStateException if this cipher is in a wrong state
 * (e.g., has not been initialized)
 * @exception IllegalArgumentException if input and output are the
 *   same object
 * @exception ReadOnlyBufferException if the output buffer is read-only
 * @exception ShortBufferException if there is insufficient space in the
 * output buffer
 * @since 1.5
 */
public final int update(ByteBuffer input, ByteBuffer output)
        throws ShortBufferException {
    checkCipherState();

    if ((input == null) || (output == null)) {
        throw new IllegalArgumentException("Buffers must not be null");
    }
    if (input == output) {
        throw new IllegalArgumentException("Input and output buffers must "
            + "not be the same object, consider using buffer.duplicate()");
    }
    if (output.isReadOnly()) {
        throw new ReadOnlyBufferException();
    }

    chooseFirstProvider();
    return spi.engineUpdate(input, output);
}
 
Example 15
Source File: Cipher.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Continues a multiple-part encryption or decryption operation
 * (depending on how this cipher was initialized), processing another data
 * part.
 *
 * <p>All <code>input.remaining()</code> bytes starting at
 * <code>input.position()</code> are processed. The result is stored
 * in the output buffer.
 * 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, 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.
 * In this case, repeat this call with a larger output buffer. Use
 * {@link #getOutputSize(int) getOutputSize} to determine how big
 * the output buffer should be.
 *
 * <p>Note: this method should be copy-safe, which means the
 * <code>input</code> and <code>output</code> buffers can reference
 * the same block of memory and no unprocessed input data is overwritten
 * when the result is copied into the output buffer.
 *
 * @param input the input ByteBuffer
 * @param output the output ByteByffer
 *
 * @return the number of bytes stored in <code>output</code>
 *
 * @exception IllegalStateException if this cipher is in a wrong state
 * (e.g., has not been initialized)
 * @exception IllegalArgumentException if input and output are the
 *   same object
 * @exception ReadOnlyBufferException if the output buffer is read-only
 * @exception ShortBufferException if there is insufficient space in the
 * output buffer
 * @since 1.5
 */
public final int update(ByteBuffer input, ByteBuffer output)
        throws ShortBufferException {
    checkCipherState();

    if ((input == null) || (output == null)) {
        throw new IllegalArgumentException("Buffers must not be null");
    }
    if (input == output) {
        throw new IllegalArgumentException("Input and output buffers must "
            + "not be the same object, consider using buffer.duplicate()");
    }
    if (output.isReadOnly()) {
        throw new ReadOnlyBufferException();
    }

    chooseFirstProvider();
    return spi.engineUpdate(input, output);
}
 
Example 16
Source File: Cipher.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Continues a multiple-part encryption or decryption operation
 * (depending on how this cipher was initialized), processing another data
 * part.
 *
 * <p>All <code>input.remaining()</code> bytes starting at
 * <code>input.position()</code> are processed. The result is stored
 * in the output buffer.
 * 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, 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.
 * In this case, repeat this call with a larger output buffer. Use
 * {@link #getOutputSize(int) getOutputSize} to determine how big
 * the output buffer should be.
 *
 * <p>Note: this method should be copy-safe, which means the
 * <code>input</code> and <code>output</code> buffers can reference
 * the same block of memory and no unprocessed input data is overwritten
 * when the result is copied into the output buffer.
 *
 * @param input the input ByteBuffer
 * @param output the output ByteByffer
 *
 * @return the number of bytes stored in <code>output</code>
 *
 * @exception IllegalStateException if this cipher is in a wrong state
 * (e.g., has not been initialized)
 * @exception IllegalArgumentException if input and output are the
 *   same object
 * @exception ReadOnlyBufferException if the output buffer is read-only
 * @exception ShortBufferException if there is insufficient space in the
 * output buffer
 * @since 1.5
 */
public final int update(ByteBuffer input, ByteBuffer output)
        throws ShortBufferException {
    checkCipherState();

    if ((input == null) || (output == null)) {
        throw new IllegalArgumentException("Buffers must not be null");
    }
    if (input == output) {
        throw new IllegalArgumentException("Input and output buffers must "
            + "not be the same object, consider using buffer.duplicate()");
    }
    if (output.isReadOnly()) {
        throw new ReadOnlyBufferException();
    }

    chooseFirstProvider();
    return spi.engineUpdate(input, output);
}
 
Example 17
Source File: Cipher.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Encrypts or decrypts data in a single-part operation, or finishes a
 * multiple-part operation. The data is encrypted or decrypted,
 * depending on how this cipher was initialized.
 *
 * <p>All {@code input.remaining()} bytes starting at
 * {@code input.position()} are processed.
 * If an AEAD mode such as GCM/CCM is being used, the authentication
 * tag is appended in the case of encryption, or verified in the
 * case of decryption.
 * The result is stored in the output buffer.
 * 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, where n is the value returned
 * by this method; the output buffer's limit will not have changed.
 *
 * <p>If {@code output.remaining()} bytes are insufficient to
 * hold the result, a {@code ShortBufferException} is thrown.
 * In this case, repeat this call with a larger output buffer. Use
 * {@link #getOutputSize(int) getOutputSize} to determine how big
 * the output buffer should be.
 *
 * <p>Upon finishing, this method resets this cipher object to the state
 * it was in when previously initialized via a call to {@code init}.
 * That is, the object is reset and available to encrypt or decrypt
 * (depending on the operation mode that was specified in the call to
 * {@code init}) more data.
 *
 * <p>Note: if any exception is thrown, this cipher object may need to
 * be reset before it can be used again.
 *
 * <p>Note: this method should be copy-safe, which means the
 * {@code input} and {@code output} buffers can reference
 * the same byte array and no unprocessed input data is overwritten
 * when the result is copied into the output buffer.
 *
 * @param input the input ByteBuffer
 * @param output the output ByteBuffer
 *
 * @return the number of bytes stored in {@code output}
 *
 * @exception IllegalStateException if this cipher is in a wrong state
 * (e.g., has not been initialized)
 * @exception IllegalArgumentException if input and output are the
 *   same object
 * @exception ReadOnlyBufferException if the output buffer is read-only
 * @exception IllegalBlockSizeException if this cipher is a block cipher,
 * no padding has been requested (only in encryption mode), and the total
 * input length of the data processed by this cipher is not a multiple of
 * block size; or if this encryption algorithm is unable to
 * process the input data provided.
 * @exception ShortBufferException if there is insufficient space in the
 * output buffer
 * @exception BadPaddingException if this cipher is in decryption mode,
 * and (un)padding has been requested, but the decrypted data is not
 * bounded by the appropriate padding bytes
 * @exception AEADBadTagException if this cipher is decrypting in an
 * AEAD mode (such as GCM/CCM), and the received authentication tag
 * does not match the calculated value
 *
 * @since 1.5
 */
public final int doFinal(ByteBuffer input, ByteBuffer output)
        throws ShortBufferException, IllegalBlockSizeException,
        BadPaddingException {
    checkCipherState();

    if ((input == null) || (output == null)) {
        throw new IllegalArgumentException("Buffers must not be null");
    }
    if (input == output) {
        throw new IllegalArgumentException("Input and output buffers must "
            + "not be the same object, consider using buffer.duplicate()");
    }
    if (output.isReadOnly()) {
        throw new ReadOnlyBufferException();
    }

    chooseFirstProvider();
    return spi.engineDoFinal(input, output);
}
 
Example 18
Source File: HybridMemorySegment.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
@Override
public final void get(int offset, ByteBuffer target, int numBytes) {
	// check the byte array offset and length
	if ((offset | numBytes | (offset + numBytes)) < 0) {
		throw new IndexOutOfBoundsException();
	}

	final int targetOffset = target.position();
	final int remaining = target.remaining();

	if (remaining < numBytes) {
		throw new BufferOverflowException();
	}

	if (target.isDirect()) {
		if (target.isReadOnly()) {
			throw new ReadOnlyBufferException();
		}

		// copy to the target memory directly
		final long targetPointer = getAddress(target) + targetOffset;
		final long sourcePointer = address + offset;

		if (sourcePointer <= addressLimit - numBytes) {
			UNSAFE.copyMemory(heapMemory, sourcePointer, null, targetPointer, numBytes);
			target.position(targetOffset + numBytes);
		}
		else if (address > addressLimit) {
			throw new IllegalStateException("segment has been freed");
		}
		else {
			throw new IndexOutOfBoundsException();
		}
	}
	else if (target.hasArray()) {
		// move directly into the byte array
		get(offset, target.array(), targetOffset + target.arrayOffset(), numBytes);

		// this must be after the get() call to ensue that the byte buffer is not
		// modified in case the call fails
		target.position(targetOffset + numBytes);
	}
	else {
		// neither heap buffer nor direct buffer
		while (target.hasRemaining()) {
			target.put(get(offset++));
		}
	}
}
 
Example 19
Source File: AsynchronousSocketChannelImpl.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
@Override
public final Future<Integer> read(ByteBuffer dst) {
    if (dst.isReadOnly())
        throw new IllegalArgumentException("Read-only buffer");
    return read(false, dst, null, 0L, TimeUnit.MILLISECONDS, null, null);
}
 
Example 20
Source File: WindowsAsynchronousFileChannelImpl.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
@Override
<A> Future<Integer> implRead(ByteBuffer dst,
                             long position,
                             A attachment,
                             CompletionHandler<Integer,? super A> handler)
{
    if (!reading)
        throw new NonReadableChannelException();
    if (position < 0)
        throw new IllegalArgumentException("Negative position");
    if (dst.isReadOnly())
        throw new IllegalArgumentException("Read-only buffer");

    // check if channel is closed
    if (!isOpen()) {
        Throwable exc = new ClosedChannelException();
        if (handler == null)
            return CompletedFuture.withFailure(exc);
        Invoker.invoke(this, handler, attachment, null, exc);
        return null;
    }

    int pos = dst.position();
    int lim = dst.limit();
    assert (pos <= lim);
    int rem = (pos <= lim ? lim - pos : 0);

    // no space remaining
    if (rem == 0) {
        if (handler == null)
            return CompletedFuture.withResult(0);
        Invoker.invoke(this, handler, attachment, 0, null);
        return null;
    }

    // create Future and task that initiates read
    PendingFuture<Integer,A> result =
        new PendingFuture<Integer,A>(this, handler, attachment);
    ReadTask<A> readTask = new ReadTask<A>(dst, pos, rem, position, result);
    result.setContext(readTask);

    // initiate I/O
    if (Iocp.supportsThreadAgnosticIo()) {
        readTask.run();
    } else {
        Invoker.invokeOnThreadInThreadPool(this, readTask);
    }
    return result;
}