java.nio.ByteBuffer#isReadOnly ( )源码实例Demo

下面列出了java.nio.ByteBuffer#isReadOnly ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: dragonwell8_jdk   文件: IOUtil.java
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);
    }
}
 
/**
 * 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);
  }
}
 
源代码3 项目: openjdk-jdk8u   文件: IOUtil.java
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);
    }
}
 
源代码4 项目: craft-atom   文件: CachedBufferAllocator.java
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));
    }
}
 
源代码5 项目: jdk8u_jdk   文件: IOUtil.java
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);
    }
}
 
源代码6 项目: freehealth-connector   文件: ChannelImpl.java
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();
   }
}
 
源代码7 项目: hadoop-ozone   文件: Checksum.java
/**
 * 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));
}
 
源代码8 项目: openjdk-8   文件: AsynchronousSocketChannelImpl.java
@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);
}
 
源代码9 项目: jdk8u60   文件: AsynchronousSocketChannelImpl.java
@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);
}
 
@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);
}
 
源代码11 项目: dubbox   文件: DirectChannelBufferFactory.java
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;
}
 
源代码12 项目: Bytecoder   文件: IOUtil.java
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);
    }
}
 
源代码13 项目: Mundus   文件: HeightMapGenerator.java
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;
}
 
@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;
}
 
源代码15 项目: jdk8u-jdk   文件: AsynchronousSocketChannelImpl.java
@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);
}
 
源代码16 项目: Flink-CEPplus   文件: HybridMemorySegment.java
@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++));
		}
	}
}
 
源代码17 项目: TencentKona-8   文件: Cipher.java
/**
 * 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);
}
 
源代码18 项目: jdk8u-dev-jdk   文件: Cipher.java
/**
 * 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);
}
 
源代码19 项目: openjdk-8-source   文件: Cipher.java
/**
 * 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);
}
 
源代码20 项目: openjdk-8   文件: Cipher.java
/**
 * 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);
}