Java Examples for java.nio.ReadOnlyBufferException

The following java examples will help you to understand the usage of java.nio.ReadOnlyBufferException. These source code samples are taken from different open source projects.

Example 1
Project: android-libcore64-master  File: FileChannelTest.java View source code
/**
     * @tests java.nio.channels.FileChannel#map(MapMode,long,long)
     */
public void test_map_ReadOnly() throws IOException {
    MappedByteBuffer mapped = null;
    // try put something to readonly map
    writeDataToFile(fileOfReadOnlyFileChannel);
    mapped = readOnlyFileChannel.map(MapMode.READ_ONLY, 0, CONTENT_LENGTH);
    try {
        mapped.put(TEST_BYTES);
        fail("should throw ReadOnlyBufferException.");
    } catch (ReadOnlyBufferException ex) {
    }
    assertEquals(CONTENT_LENGTH, mapped.limit());
    assertEquals(CONTENT_LENGTH, mapped.capacity());
    assertEquals(0, mapped.position());
    // try to get a readonly map from read/write channel
    writeDataToFile(fileOfReadWriteFileChannel);
    mapped = readWriteFileChannel.map(MapMode.READ_ONLY, 0, CONTENT.length());
    assertEquals(CONTENT_LENGTH, mapped.limit());
    assertEquals(CONTENT_LENGTH, mapped.capacity());
    assertEquals(0, mapped.position());
    // map not change channel's position
    assertEquals(0, readOnlyFileChannel.position());
    assertEquals(0, readWriteFileChannel.position());
}
Example 2
Project: android_platform_libcore-master  File: SSLEngineTest.java View source code
/**
     * javax.net.ssl.SSLEngine#unwrap(ByteBuffer src, ByteBuffer[] dsts,
     *                                       int offset, int length)
     * Exception case: ReadOnlyBufferException should be thrown.
     */
@KnownFailure("Fixed on DonutBurger, Wrong Exception thrown")
public void test_unwrap_03() {
    String host = "new host";
    int port = 8080;
    ByteBuffer bbR = ByteBuffer.allocate(100).asReadOnlyBuffer();
    ByteBuffer[] bbA = { bbR, ByteBuffer.allocate(10), ByteBuffer.allocate(100) };
    ByteBuffer bb = ByteBuffer.allocate(10);
    SSLEngine sse = getEngine(host, port);
    sse.setUseClientMode(true);
    try {
        sse.unwrap(bb, bbA, 0, bbA.length);
        fail("ReadOnlyBufferException wasn't thrown");
    } catch (ReadOnlyBufferException iobe) {
    } catch (Exception e) {
        fail(e + " was thrown instead of ReadOnlyBufferException");
    }
}
Example 3
Project: ARTPart-master  File: FileChannelTest.java View source code
/**
     * @tests java.nio.channels.FileChannel#map(MapMode,long,long)
     */
public void test_map_ReadOnly() throws IOException {
    MappedByteBuffer mapped = null;
    // try put something to readonly map
    writeDataToFile(fileOfReadOnlyFileChannel);
    mapped = readOnlyFileChannel.map(MapMode.READ_ONLY, 0, CONTENT_LENGTH);
    try {
        mapped.put(TEST_BYTES);
        fail("should throw ReadOnlyBufferException.");
    } catch (ReadOnlyBufferException ex) {
    }
    assertEquals(CONTENT_LENGTH, mapped.limit());
    assertEquals(CONTENT_LENGTH, mapped.capacity());
    assertEquals(0, mapped.position());
    // try to get a readonly map from read/write channel
    writeDataToFile(fileOfReadWriteFileChannel);
    mapped = readWriteFileChannel.map(MapMode.READ_ONLY, 0, CONTENT.length());
    assertEquals(CONTENT_LENGTH, mapped.limit());
    assertEquals(CONTENT_LENGTH, mapped.capacity());
    assertEquals(0, mapped.position());
    // map not change channel's position
    assertEquals(0, readOnlyFileChannel.position());
    assertEquals(0, readWriteFileChannel.position());
}
Example 4
Project: es6draft-master  File: UnsafeHolder.java View source code
private static long offsetOrMemoryAddress(ByteBuffer buffer, int index, int size) {
    if (index < 0 || size > buffer.limit() - index) {
        throw new IndexOutOfBoundsException(indexOutOfBoundsMessage(buffer, index, size));
    }
    if (buffer.isReadOnly()) {
        throw new ReadOnlyBufferException();
    }
    if (buffer.hasArray()) {
        return BYTE_ARRAY_BASE_OFFSET + buffer.arrayOffset() + index;
    }
    assert buffer.isDirect();
    return ((DirectBuffer) buffer).address() + index;
}
Example 5
Project: j2objc-master  File: Cipher.java View source code
/**
     * 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();
    }
    updateProviderIfNeeded();
    return spi.engineUpdate(input, output);
}
Example 6
Project: robovm-master  File: FileChannelTest.java View source code
/**
     * @tests java.nio.channels.FileChannel#map(MapMode,long,long)
     */
public void test_map_ReadOnly() throws IOException {
    MappedByteBuffer mapped = null;
    // try put something to readonly map
    writeDataToFile(fileOfReadOnlyFileChannel);
    mapped = readOnlyFileChannel.map(MapMode.READ_ONLY, 0, CONTENT_LENGTH);
    try {
        mapped.put(TEST_BYTES);
        fail("should throw ReadOnlyBufferException.");
    } catch (ReadOnlyBufferException ex) {
    }
    assertEquals(CONTENT_LENGTH, mapped.limit());
    assertEquals(CONTENT_LENGTH, mapped.capacity());
    assertEquals(0, mapped.position());
    // try to get a readonly map from read/write channel
    writeDataToFile(fileOfReadWriteFileChannel);
    mapped = readWriteFileChannel.map(MapMode.READ_ONLY, 0, CONTENT.length());
    assertEquals(CONTENT_LENGTH, mapped.limit());
    assertEquals(CONTENT_LENGTH, mapped.capacity());
    assertEquals(0, mapped.position());
    // map not change channel's position
    assertEquals(0, readOnlyFileChannel.position());
    assertEquals(0, readWriteFileChannel.position());
}
Example 7
Project: ohc-master  File: DirectAccessTest.java View source code
@Test
public void testDirectPutGet() throws Exception {
    try (OHCache<Integer, String> cache = OHCacheBuilder.<Integer, String>newBuilder().keySerializer(TestUtils.intSerializer).valueSerializer(TestUtils.stringSerializer).capacity(64 * 1024 * 1024).build()) {
        for (int i = 0; i < 100; i++) {
            String s = "";
            for (int c = 0; c < i + 10; c++) s = s + "42";
            cache.put(i, s);
        }
        for (int i = 0; i < 100; i++) {
            Assert.assertTrue(cache.containsKey(i));
            try (DirectValueAccess direct = cache.getDirect(i)) {
                String s = "";
                for (int c = 0; c < i + 10; c++) s = s + "42";
                byte[] bytes = s.getBytes(Charsets.UTF_8);
                Assert.assertEquals(direct.buffer().capacity(), bytes.length + 2);
                Assert.assertEquals(direct.buffer().limit(), bytes.length + 2);
                Assert.assertEquals(TestUtils.stringSerializer.deserialize(direct.buffer()), s);
                try {
                    direct.buffer().get();
                    Assert.fail();
                } catch (BufferUnderflowException e) {
                }
                try {
                    direct.buffer().put(0, (byte) 0);
                    Assert.fail();
                } catch (ReadOnlyBufferException e) {
                }
            }
        }
    }
}
Example 8
Project: VCom4j-master  File: URLEncoder.java View source code
public static long _encode(CharSequence obj, ByteBuffer buf) {
    long cnt = 0;
    for (int i = 0; i < obj.length(); i++) {
        try {
            int c = obj.charAt(i);
            //                } else
            if (c < 0x80) {
                if (isUnreserved(c)) {
                    buf.put((byte) c);
                    cnt++;
                } else {
                    buf.put((byte) '%');
                    buf.put(toByte((c & 0x70) >>> 4));
                    buf.put(toByte((c & 0x0F)));
                    cnt += 3;
                }
            } else if (c < 0x800) {
                final int b1 = 0x80 | (0xBF & c);
                final int b2 = 0xC0 | (0x1F & (c >>> 6));
                buf.put((byte) '%');
                buf.put(toByte((b2 & 0xF0) >>> 4));
                buf.put(toByte(b2 & 0x0F));
                buf.put((byte) '%');
                buf.put(toByte((b1 & 0xF0) >>> 4));
                buf.put(toByte(b1 & 0x0F));
                cnt += 6;
            } else if (c < 0x10000) {
                final int b1 = 0x80 | (0xBF & c);
                final int b2 = 0x80 | (0x3F & (c >>> 6));
                final int b3 = 0xE0 | (0x0F & (c >>> 12));
                buf.put((byte) '%');
                buf.put(toByte((b3 & 0xF0) >>> 4));
                buf.put(toByte(b3 & 0x0F));
                buf.put((byte) '%');
                buf.put(toByte((b2 & 0xF0) >>> 4));
                buf.put(toByte(b2 & 0x0F));
                buf.put((byte) '%');
                buf.put(toByte((b1 & 0xF0) >>> 4));
                buf.put(toByte(b1 & 0x0F));
                cnt += 9;
            } else {
                final int b1 = 0x80 | (0x3F & c);
                final int b2 = 0x80 | (0x3F & (c >>> 6));
                final int b3 = 0x80 | (0x3F & (c >>> 12));
                final int b4 = 0xF0 | (0x07 & (c >>> 18));
                buf.put((byte) '%');
                buf.put(toByte((b4 & 0xF0) >>> 4));
                buf.put(toByte(b4 & 0x0F));
                buf.put((byte) '%');
                buf.put(toByte((b3 & 0xF0) >>> 4));
                buf.put(toByte(b3 & 0x0F));
                buf.put((byte) '%');
                buf.put(toByte((b2 & 0xF0) >>> 4));
                buf.put(toByte(b2 & 0x0F));
                buf.put((byte) '%');
                buf.put(toByte((b1 & 0xF0) >>> 4));
                buf.put(toByte(b1 & 0x0F));
                cnt += 12;
            }
        } catch (BufferOverflowException e) {
            throw new EncodingException(e);
        } catch (ReadOnlyBufferException e) {
            throw new EncodingException(e);
        }
    }
    return cnt;
}
Example 9
Project: android-sdk-sources-for-api-level-23-master  File: FileChannelTest.java View source code
/**
     * @tests java.nio.channels.FileChannel#map(MapMode,long,long)
     */
public void test_map_ReadOnly() throws IOException {
    MappedByteBuffer mapped = null;
    // try put something to readonly map
    writeDataToFile(fileOfReadOnlyFileChannel);
    mapped = readOnlyFileChannel.map(MapMode.READ_ONLY, 0, CONTENT_LENGTH);
    try {
        mapped.put(TEST_BYTES);
        fail("should throw ReadOnlyBufferException.");
    } catch (ReadOnlyBufferException ex) {
    }
    assertEquals(CONTENT_LENGTH, mapped.limit());
    assertEquals(CONTENT_LENGTH, mapped.capacity());
    assertEquals(0, mapped.position());
    // try to get a readonly map from read/write channel
    writeDataToFile(fileOfReadWriteFileChannel);
    mapped = readWriteFileChannel.map(MapMode.READ_ONLY, 0, CONTENT.length());
    assertEquals(CONTENT_LENGTH, mapped.limit());
    assertEquals(CONTENT_LENGTH, mapped.capacity());
    assertEquals(0, mapped.position());
    // map not change channel's position
    assertEquals(0, readOnlyFileChannel.position());
    assertEquals(0, readWriteFileChannel.position());
}
Example 10
Project: termd-master  File: EventQueueTest.java View source code
@Test
public void testBuffer() {
    EventQueue queue = new EventQueue(new Keymap());
    assertEquals(0, queue.getBuffer().capacity());
    queue.append('h', 'e', 'l', 'l', 'o');
    IntBuffer buffer = queue.getBuffer();
    buffer.mark();
    assertEquals(5, buffer.capacity());
    assertEquals('h', buffer.get());
    assertEquals('e', buffer.get());
    assertEquals('l', buffer.get());
    assertEquals('l', buffer.get());
    assertEquals('o', buffer.get());
    buffer.reset();
    try {
        buffer.put(0, 'p');
        fail();
    } catch (ReadOnlyBufferException ignore) {
    }
}
Example 11
Project: ambry-master  File: ByteBufferInputStreamTest.java View source code
@Test
public void byteBufferStreamTest() throws IOException {
    byte[] buf = new byte[1024];
    new Random().nextBytes(buf);
    ByteBufferInputStream stream = new ByteBufferInputStream(ByteBuffer.wrap(buf));
    for (int i = 0; i < 1024; i++) {
        Assert.assertEquals(stream.read(), (buf[i] & 0xFF));
    }
    ByteBufferInputStream stream1 = new ByteBufferInputStream(ByteBuffer.wrap(buf));
    byte[] outputBuf = new byte[500];
    stream1.read(outputBuf, 0, 500);
    for (int i = 0; i < 500; i++) {
        Assert.assertEquals(outputBuf[i], buf[i]);
    }
    stream1.read(outputBuf, 0, 500);
    for (int i = 500; i < 1000; i++) {
        Assert.assertEquals(outputBuf[i - 500], buf[i]);
    }
    ByteBufferInputStream stream2 = new ByteBufferInputStream(ByteBuffer.wrap(buf));
    ByteBufferInputStream stream3 = new ByteBufferInputStream(stream2, 1024);
    byte[] output = new byte[1001];
    output[0] = (byte) stream3.read();
    Assert.assertEquals(output[0], buf[0]);
    stream3.read(output, 1, 1000);
    for (int i = 0; i < 1001; i++) {
        Assert.assertEquals(output[i], buf[i]);
    }
    output = new byte[23];
    stream3.read(output);
    for (int i = 0; i < 23; i++) {
        Assert.assertEquals(output[i], buf[i + 1001]);
    }
    Assert.assertEquals(stream3.read(), -1);
    ByteBuffer byteBuf = ByteBuffer.wrap(buf);
    ByteBufferInputStream stream4 = new ByteBufferInputStream(byteBuf.duplicate());
    // ByteBuffer class overrides equal() to do content comparison.
    Assert.assertEquals("The returned byte buffer must have the same content as the one initialized with", byteBuf, stream4.getByteBuffer());
    byteBuf.rewind();
    ByteBufferInputStream stream5 = new ByteBufferInputStream(byteBuf.duplicate());
    ByteBufferInputStream stream6 = new ByteBufferInputStream(stream5, 1024);
    Assert.assertEquals("The returned byte buffer must have the same content as the one initialized with", byteBuf, stream6.getByteBuffer());
    try {
        stream6.getByteBuffer().put((byte) 0);
        Assert.fail("Returned ByteBuffer from a ByteBufferInputStream must be read-only");
    } catch (ReadOnlyBufferException e) {
    }
}
Example 12
Project: android_libcore-master  File: FileChannelTest.java View source code
/**
     * @tests java.nio.channels.FileChannel#map(MapMode,long,long)
     */
@TestTargetNew(level = TestLevel.PARTIAL_COMPLETE, notes = "", method = "map", args = { java.nio.channels.FileChannel.MapMode.class, long.class, long.class })
public void test_map_ReadOnly() throws IOException {
    MappedByteBuffer mapped = null;
    // try put something to readonly map
    writeDataToFile(fileOfReadOnlyFileChannel);
    mapped = readOnlyFileChannel.map(MapMode.READ_ONLY, 0, CONTENT_LENGTH);
    try {
        mapped.put(TEST_BYTES);
        fail("should throw ReadOnlyBufferException.");
    } catch (ReadOnlyBufferException ex) {
    }
    assertEquals(CONTENT_LENGTH, mapped.limit());
    assertEquals(CONTENT_LENGTH, mapped.capacity());
    assertEquals(0, mapped.position());
    // try to get a readonly map from read/write channel
    writeDataToFile(fileOfReadWriteFileChannel);
    mapped = readWriteFileChannel.map(MapMode.READ_ONLY, 0, CONTENT.length());
    assertEquals(CONTENT_LENGTH, mapped.limit());
    assertEquals(CONTENT_LENGTH, mapped.capacity());
    assertEquals(0, mapped.position());
    // map not change channel's position
    assertEquals(0, readOnlyFileChannel.position());
    assertEquals(0, readWriteFileChannel.position());
}
Example 13
Project: open-mika-master  File: FileChannelTest.java View source code
/**
     * @tests java.nio.channels.FileChannel#map(MapMode,long,long)
    @TestTargetNew(
        level = TestLevel.PARTIAL_COMPLETE,
        notes = "",
        method = "map",
        args = {java.nio.channels.FileChannel.MapMode.class, long.class, long.class}
    )
     */
public void test_map_ReadOnly() throws IOException {
    MappedByteBuffer mapped = null;
    // try put something to readonly map
    writeDataToFile(fileOfReadOnlyFileChannel);
    mapped = readOnlyFileChannel.map(MapMode.READ_ONLY, 0, CONTENT_LENGTH);
    try {
        mapped.put(TEST_BYTES);
        fail("should throw ReadOnlyBufferException.");
    } catch (ReadOnlyBufferException ex) {
    }
    assertEquals(CONTENT_LENGTH, mapped.limit());
    assertEquals(CONTENT_LENGTH, mapped.capacity());
    assertEquals(0, mapped.position());
    // try to get a readonly map from read/write channel
    writeDataToFile(fileOfReadWriteFileChannel);
    mapped = readWriteFileChannel.map(MapMode.READ_ONLY, 0, CONTENT.length());
    assertEquals(CONTENT_LENGTH, mapped.limit());
    assertEquals(CONTENT_LENGTH, mapped.capacity());
    assertEquals(0, mapped.position());
    // map not change channel's position
    assertEquals(0, readOnlyFileChannel.position());
    assertEquals(0, readWriteFileChannel.position());
}
Example 14
Project: openjdk-master  File: Cipher.java View source code
/**
     * Continues a multiple-part encryption or decryption operation
     * (depending on how this cipher was initialized), processing another data
     * part.
     *
     * <p>All {@code input.remaining()} bytes starting at
     * {@code input.position()} 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()} 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>Note: this method should be copy-safe, which means the
     * {@code input} and {@code output} 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}
     *
     * @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
Project: fluo-master  File: BytesTest.java View source code
@Test
public void testToByteBuffer() {
    Bytes b1 = Bytes.of("fluofluo");
    ByteBuffer buffer = b1.toByteBuffer();
    Assert.assertFalse(buffer.hasArray());
    Assert.assertEquals(buffer.remaining(), 8);
    byte[] copy = new byte[8];
    buffer.duplicate().get(copy);
    Assert.assertEquals("fluofluo", new String(copy, StandardCharsets.UTF_8));
    try {
        buffer.put((byte) 6);
        Assert.fail();
    } catch (ReadOnlyBufferException e) {
    }
}
Example 16
Project: irma_future_id-master  File: ChannelImpl.java View source code
public int transmit(ByteBuffer command, ByteBuffer response) throws CardException {
    checkClosed();
    card.checkExclusive();
    if ((command == null) || (response == null)) {
        throw new NullPointerException();
    }
    if (response.isReadOnly()) {
        throw new ReadOnlyBufferException();
    }
    if (command == response) {
        throw new IllegalArgumentException("command and response must not be the same object");
    }
    if (response.remaining() < 258) {
        throw new IllegalArgumentException("Insufficient space in response buffer");
    }
    byte[] commandBytes = new byte[command.remaining()];
    command.get(commandBytes);
    byte[] responseBytes = doTransmit(commandBytes);
    response.put(responseBytes);
    return responseBytes.length;
}
Example 17
Project: netty-master  File: ReferenceCountedOpenSslEngine.java View source code
@Override
public final SSLEngineResult wrap(final ByteBuffer[] srcs, int offset, final int length, final ByteBuffer dst) throws SSLException {
    // Throw required runtime exceptions
    if (srcs == null) {
        throw new IllegalArgumentException("srcs is null");
    }
    if (dst == null) {
        throw new IllegalArgumentException("dst is null");
    }
    if (offset >= srcs.length || offset + length > srcs.length) {
        throw new IndexOutOfBoundsException("offset: " + offset + ", length: " + length + " (expected: offset <= offset + length <= srcs.length (" + srcs.length + "))");
    }
    if (dst.isReadOnly()) {
        throw new ReadOnlyBufferException();
    }
    synchronized (this) {
        if (isOutboundDone()) {
            // All drained in the outbound buffer
            return isInboundDone() || isDestroyed() ? CLOSED_NOT_HANDSHAKING : NEED_UNWRAP_CLOSED;
        }
        int bytesProduced = 0;
        ByteBuf bioReadCopyBuf = null;
        try {
            // Setup the BIO buffer so that we directly write the encryption results into dst.
            if (dst.isDirect()) {
                SSL.bioSetByteBuffer(networkBIO, Buffer.address(dst) + dst.position(), dst.remaining(), true);
            } else {
                bioReadCopyBuf = alloc.directBuffer(dst.remaining());
                SSL.bioSetByteBuffer(networkBIO, memoryAddress(bioReadCopyBuf), bioReadCopyBuf.writableBytes(), true);
            }
            int bioLengthBefore = SSL.bioLengthByteBuffer(networkBIO);
            // Explicit use outboundClosed as we want to drain any bytes that are still present.
            if (outboundClosed) {
                // There is something left to drain.
                // See https://github.com/netty/netty/issues/6260
                bytesProduced = SSL.bioFlushByteBuffer(networkBIO);
                if (bytesProduced <= 0) {
                    return newResultMayFinishHandshake(NOT_HANDSHAKING, 0, 0);
                }
                // OpenSSL can give us.
                if (!doSSLShutdown()) {
                    return newResultMayFinishHandshake(NOT_HANDSHAKING, 0, bytesProduced);
                }
                bytesProduced = bioLengthBefore - SSL.bioLengthByteBuffer(networkBIO);
                return newResultMayFinishHandshake(NEED_WRAP, 0, bytesProduced);
            }
            // Flush any data that may be implicitly generated by OpenSSL (handshake, close, etc..).
            SSLEngineResult.HandshakeStatus status = NOT_HANDSHAKING;
            // Prepare OpenSSL to work in server mode and receive handshake
            if (handshakeState != HandshakeState.FINISHED) {
                if (handshakeState != HandshakeState.STARTED_EXPLICITLY) {
                    // Update accepted so we know we triggered the handshake via wrap
                    handshakeState = HandshakeState.STARTED_IMPLICITLY;
                }
                // Flush any data that may have been written implicitly during the handshake by OpenSSL.
                bytesProduced = SSL.bioFlushByteBuffer(networkBIO);
                if (bytesProduced > 0 && handshakeException != null) {
                    // we allow handshake() to throw the handshake exception.
                    return newResult(NEED_WRAP, 0, bytesProduced);
                }
                status = handshake();
                if (renegotiationPending && status == FINISHED) {
                    // If renegotiationPending is true that means when we attempted to start renegotiation
                    // the BIO buffer didn't have enough space to hold the HelloRequest which prompts the
                    // client to initiate a renegotiation. At this point the HelloRequest has been written
                    // so we can actually start the handshake process.
                    renegotiationPending = false;
                    SSL.setState(ssl, SSL.SSL_ST_ACCEPT);
                    handshakeState = HandshakeState.STARTED_EXPLICITLY;
                    status = handshake();
                }
                // Handshake may have generated more data, for example if the internal SSL buffer is small
                // we may have freed up space by flushing above.
                bytesProduced = bioLengthBefore - SSL.bioLengthByteBuffer(networkBIO);
                if (bytesProduced > 0) {
                    // It's important we call this before wrapStatus() as wrapStatus() may shutdown the engine.
                    return newResult(mayFinishHandshake(status != FINISHED ? getHandshakeStatus(SSL.bioLengthNonApplication(networkBIO)) : FINISHED), 0, bytesProduced);
                }
                if (status == NEED_UNWRAP) {
                    // Signal if the outbound is done or not.
                    return isOutboundDone() ? NEED_UNWRAP_CLOSED : NEED_UNWRAP_OK;
                }
                // still present.
                if (outboundClosed) {
                    bytesProduced = SSL.bioFlushByteBuffer(networkBIO);
                    return newResultMayFinishHandshake(status, 0, bytesProduced);
                }
            }
            int srcsLen = 0;
            final int endOffset = offset + length;
            for (int i = offset; i < endOffset; ++i) {
                final ByteBuffer src = srcs[i];
                if (src == null) {
                    throw new IllegalArgumentException("srcs[" + i + "] is null");
                }
                if (srcsLen == MAX_PLAINTEXT_LENGTH) {
                    continue;
                }
                srcsLen += src.remaining();
                if (srcsLen > MAX_PLAINTEXT_LENGTH || srcsLen < 0) {
                    // If srcLen > MAX_PLAINTEXT_LENGTH or secLen < 0 just set it to MAX_PLAINTEXT_LENGTH.
                    // This also help us to guard against overflow.
                    // We not break out here as we still need to check for null entries in srcs[].
                    srcsLen = MAX_PLAINTEXT_LENGTH;
                }
            }
            // so we always fix the number of buffers to 1 when checking if the dst buffer is large enough.
            if (dst.remaining() < calculateOutNetBufSize(srcsLen, 1)) {
                return new SSLEngineResult(BUFFER_OVERFLOW, getHandshakeStatus(), 0, 0);
            }
            // There was no pending data in the network BIO -- encrypt any application data
            int bytesConsumed = 0;
            // Flush any data that may have been written implicitly by OpenSSL in case a shutdown/alert occurs.
            bytesProduced = SSL.bioFlushByteBuffer(networkBIO);
            for (; offset < endOffset; ++offset) {
                final ByteBuffer src = srcs[offset];
                final int remaining = src.remaining();
                if (remaining == 0) {
                    continue;
                }
                // Write plaintext application data to the SSL engine
                int bytesWritten = writePlaintextData(src, min(remaining, MAX_PLAINTEXT_LENGTH - bytesConsumed));
                if (bytesWritten > 0) {
                    bytesConsumed += bytesWritten;
                    // Determine how much encrypted data was generated:
                    final int pendingNow = SSL.bioLengthByteBuffer(networkBIO);
                    bytesProduced += bioLengthBefore - pendingNow;
                    bioLengthBefore = pendingNow;
                    return newResultMayFinishHandshake(status, bytesConsumed, bytesProduced);
                } else {
                    int sslError = SSL.getError(ssl, bytesWritten);
                    if (sslError == SSL.SSL_ERROR_ZERO_RETURN) {
                        // This means the connection was shutdown correctly, close inbound and outbound
                        if (!receivedShutdown) {
                            closeAll();
                            bytesProduced += bioLengthBefore - SSL.bioLengthByteBuffer(networkBIO);
                            SSLEngineResult.HandshakeStatus hs = mayFinishHandshake(status != FINISHED ? getHandshakeStatus(SSL.bioLengthNonApplication(networkBIO)) : FINISHED);
                            return newResult(hs, bytesConsumed, bytesProduced);
                        }
                        return newResult(NOT_HANDSHAKING, bytesConsumed, bytesProduced);
                    } else if (sslError == SSL.SSL_ERROR_WANT_READ) {
                        // been closed. [1] https://www.openssl.org/docs/manmaster/ssl/SSL_write.html
                        return newResult(NEED_UNWRAP, bytesConsumed, bytesProduced);
                    } else if (sslError == SSL.SSL_ERROR_WANT_WRITE) {
                        // [1] https://www.openssl.org/docs/manmaster/ssl/SSL_write.html
                        return newResult(NEED_WRAP, bytesConsumed, bytesProduced);
                    } else {
                        // Everything else is considered as error
                        throw shutdownWithError("SSL_write");
                    }
                }
            }
            return newResultMayFinishHandshake(status, bytesConsumed, bytesProduced);
        } finally {
            SSL.bioClearByteBuffer(networkBIO);
            if (bioReadCopyBuf == null) {
                dst.position(dst.position() + bytesProduced);
            } else {
                assert bioReadCopyBuf.readableBytes() <= dst.remaining() : "The destination buffer " + dst + " didn't have enough remaining space to hold the encrypted content in " + bioReadCopyBuf;
                dst.put(bioReadCopyBuf.internalNioBuffer(bioReadCopyBuf.readerIndex(), bytesProduced));
                bioReadCopyBuf.release();
            }
        }
    }
}
Example 18
Project: open-ecard-master  File: ChannelImpl.java View source code
public int transmit(ByteBuffer command, ByteBuffer response) throws CardException {
    checkClosed();
    card.checkExclusive();
    if ((command == null) || (response == null)) {
        throw new NullPointerException();
    }
    if (response.isReadOnly()) {
        throw new ReadOnlyBufferException();
    }
    if (command == response) {
        throw new IllegalArgumentException("command and response must not be the same object");
    }
    if (response.remaining() < 258) {
        throw new IllegalArgumentException("Insufficient space in response buffer");
    }
    byte[] commandBytes = new byte[command.remaining()];
    command.get(commandBytes);
    byte[] responseBytes = doTransmit(commandBytes);
    response.put(responseBytes);
    return responseBytes.length;
}
Example 19
Project: silent-text-android-master  File: CryptoUtils.java View source code
public static CharSequence randomize(CharSequence sequence) {
    if (sequence instanceof CharBuffer) {
        return randomize((CharBuffer) sequence);
    } else if (sequence instanceof StringBuffer) {
        return randomize((StringBuffer) sequence);
    } else if (sequence instanceof StringBuilder) {
        return randomize((StringBuilder) sequence);
    } else {
        throw new ReadOnlyBufferException();
    }
}
Example 20
Project: activemq-artemis-master  File: UnpooledUnsafeDirectByteBufWrapper.java View source code
private static void getBytes(byte[] array, int idx, ByteBuffer dst) {
    if (dst.remaining() == 0) {
        return;
    }
    if (dst.isDirect()) {
        if (dst.isReadOnly()) {
            // We need to check if dst is ready-only so we not write something in it by using Unsafe.
            throw new ReadOnlyBufferException();
        }
        // Copy to direct memory
        final long dstAddress = PlatformDependent.directBufferAddress(dst);
        PlatformDependent.copyMemory(array, idx, dstAddress + dst.position(), dst.remaining());
        dst.position(dst.position() + dst.remaining());
    } else if (dst.hasArray()) {
        // Copy to array
        System.arraycopy(array, idx, dst.array(), dst.arrayOffset() + dst.position(), dst.remaining());
        dst.position(dst.position() + dst.remaining());
    } else {
        dst.put(array, idx, dst.remaining());
    }
}
Example 21
Project: netx-master  File: WsURLConnectionImpl.java View source code
public void sendCloseIfNecessary(Frame closeFrame) throws IOException {
    if (outputState == CLOSED) {
        return;
    }
    int closePayloadLength = closeFrame.payloadLength();
    int code = 0;
    int reasonOffset = 0;
    int reasonLength = 0;
    if (closePayloadLength >= 2) {
        code = uint16Get(closeFrame.buffer(), closeFrame.payloadOffset());
        if (closePayloadLength > 2) {
            reasonOffset = closeFrame.payloadOffset() + 2;
            reasonLength = closePayloadLength - 2;
        }
    }
    // java.nio.ReadOnlyBufferException as we will be getting RO flyweight.
    for (int i = 0; i < reasonLength; i++) {
        commandFramePayload[i] = closeFrame.buffer().get(reasonOffset + i);
    }
    sendClose(code, commandFramePayload, 0, reasonLength);
}
Example 22
Project: voltdb-master  File: UnsafeByteBufUtil.java View source code
static void getBytes(AbstractByteBuf buf, long addr, int index, ByteBuffer dst) {
    buf.checkIndex(index, dst.remaining());
    if (dst.remaining() == 0) {
        return;
    }
    if (dst.isDirect()) {
        if (dst.isReadOnly()) {
            // We need to check if dst is ready-only so we not write something in it by using Unsafe.
            throw new ReadOnlyBufferException();
        }
        // Copy to direct memory
        long dstAddress = PlatformDependent.directBufferAddress(dst);
        PlatformDependent.copyMemory(addr, dstAddress + dst.position(), dst.remaining());
        dst.position(dst.position() + dst.remaining());
    } else if (dst.hasArray()) {
        // Copy to array
        PlatformDependent.copyMemory(addr, dst.array(), dst.arrayOffset() + dst.position(), dst.remaining());
        dst.position(dst.position() + dst.remaining());
    } else {
        dst.put(buf.nioBuffer());
    }
}
Example 23
Project: android-15-master  File: CipherTest.java View source code
public void test_doFinalLjava_nio_ByteBufferLjava_nio_ByteBuffer() throws Exception {
    byte[] b = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
    ByteBuffer bInput = ByteBuffer.allocate(64);
    ByteBuffer bOutput = ByteBuffer.allocate(64);
    Cipher c = Cipher.getInstance("DES/CBC/NoPadding");
    c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
    bInput.put(b, 0, 10);
    try {
        c.doFinal(bInput, bOutput);
        fail();
    } catch (IllegalBlockSizeException expected) {
    }
    c = Cipher.getInstance("DES/CBC/NoPadding");
    try {
        c.doFinal(bInput, bOutput);
        fail();
    } catch (IllegalStateException expected) {
    }
    c = Cipher.getInstance("DES/CBC/NoPadding");
    c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
    bInput = ByteBuffer.allocate(16);
    bInput.put(b, 0, 16);
    c.doFinal(bInput, bOutput);
    SecureRandom sr = new SecureRandom();
    byte[] iv = new byte[8];
    sr.nextBytes(iv);
    AlgorithmParameterSpec ap = new IvParameterSpec(iv);
    c = Cipher.getInstance("DES/CBC/PKCS5Padding");
    c.init(Cipher.DECRYPT_MODE, cipherKeyDES, ap);
    bInput = ByteBuffer.allocate(64);
    try {
        c.doFinal(bOutput, bInput);
        fail();
    } catch (BadPaddingException expected) {
    }
    c = Cipher.getInstance("DES/CBC/NoPadding");
    c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
    bInput.put(b, 0, 16);
    try {
        c.doFinal(bInput, bInput);
        fail();
    } catch (IllegalArgumentException expected) {
    }
    c = Cipher.getInstance("DES/CBC/NoPadding");
    c.init(Cipher.ENCRYPT_MODE, cipherKeyDES);
    bInput.put(b, 0, 16);
    try {
        c.doFinal(bInput, bOutput.asReadOnlyBuffer());
        fail();
    } catch (ReadOnlyBufferException expected) {
    }
    bInput.rewind();
    bInput.put(b, 0, 16);
    bOutput = ByteBuffer.allocate(8);
    c = Cipher.getInstance("DESede");
    c.init(Cipher.ENCRYPT_MODE, cipherKey);
    try {
        c.doFinal(bInput, bOutput);
        fail();
    } catch (ShortBufferException expected) {
    }
}
Example 24
Project: bugvm-master  File: SSLEngineImpl.java View source code
/**
     * Decodes one complete SSL/TLS record provided in the source buffer.
     * If decoded record contained application data, this data will
     * be placed in the destination buffers.
     * For more information about TLS record fragmentation see
     * TLS v 1 specification (http://www.ietf.org/rfc/rfc2246.txt) p 6.2.
     * @param src source buffer containing SSL/TLS record.
     * @param dsts destination buffers to place received application data.
     * @see javax.net.ssl.SSLEngine#unwrap(ByteBuffer,ByteBuffer[],int,int)
     * method documentation for more information
     */
@Override
public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts, int offset, int length) throws SSLException {
    if (engine_was_shutteddown) {
        return new SSLEngineResult(SSLEngineResult.Status.CLOSED, SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, 0, 0);
    }
    if ((src == null) || (dsts == null)) {
        throw new IllegalStateException("Some of the input parameters are null");
    }
    if (!handshake_started) {
        beginHandshake();
    }
    SSLEngineResult.HandshakeStatus handshakeStatus = getHandshakeStatus();
    // check if this call was made in spite of handshake status
    if ((session == null || engine_was_closed) && (handshakeStatus.equals(SSLEngineResult.HandshakeStatus.NEED_WRAP) || handshakeStatus.equals(SSLEngineResult.HandshakeStatus.NEED_TASK))) {
        return new SSLEngineResult(getEngineStatus(), handshakeStatus, 0, 0);
    }
    if (src.remaining() < recordProtocol.getMinRecordSize()) {
        return new SSLEngineResult(SSLEngineResult.Status.BUFFER_UNDERFLOW, getHandshakeStatus(), 0, 0);
    }
    try {
        src.mark();
        // check the destination buffers and count their capacity
        int capacity = 0;
        for (int i = offset; i < offset + length; i++) {
            if (dsts[i] == null) {
                throw new IllegalStateException("Some of the input parameters are null");
            }
            if (dsts[i].isReadOnly()) {
                throw new ReadOnlyBufferException();
            }
            capacity += dsts[i].remaining();
        }
        if (capacity < recordProtocol.getDataSize(src.remaining())) {
            return new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW, getHandshakeStatus(), 0, 0);
        }
        recProtIS.setSourceBuffer(src);
        // unwrap the record contained in source buffer, pass it
        // to appropriate client protocol (alert, handshake, or app)
        // and retrieve the type of unwrapped data
        int type = recordProtocol.unwrap();
        // process the data and return the result
        switch(type) {
            case ContentType.HANDSHAKE:
            case ContentType.CHANGE_CIPHER_SPEC:
                if (handshakeProtocol.getStatus().equals(SSLEngineResult.HandshakeStatus.FINISHED)) {
                    session = recordProtocol.getSession();
                }
                break;
            case ContentType.APPLICATION_DATA:
                break;
            case ContentType.ALERT:
                if (alertProtocol.isFatalAlert()) {
                    alertProtocol.setProcessed();
                    if (session != null) {
                        session.invalidate();
                    }
                    String description = "Fatal alert received " + alertProtocol.getAlertDescription();
                    shutdown();
                    throw new SSLException(description);
                } else {
                    if (logger != null) {
                        logger.println("Warning allert has been received: " + alertProtocol.getAlertDescription());
                    }
                    switch(alertProtocol.getDescriptionCode()) {
                        case AlertProtocol.CLOSE_NOTIFY:
                            alertProtocol.setProcessed();
                            close_notify_was_received = true;
                            if (!close_notify_was_sent) {
                                closeOutbound();
                                closeInbound();
                            } else {
                                closeInbound();
                                shutdown();
                            }
                            break;
                        case AlertProtocol.NO_RENEGOTIATION:
                            alertProtocol.setProcessed();
                            if (session == null) {
                                // handshake
                                throw new AlertException(AlertProtocol.HANDSHAKE_FAILURE, new SSLHandshakeException("Received no_renegotiation " + "during the initial handshake"));
                            } else {
                                // just stop the handshake
                                handshakeProtocol.stop();
                            }
                            break;
                        default:
                            alertProtocol.setProcessed();
                    }
                }
                break;
        }
        return new SSLEngineResult(getEngineStatus(), getHandshakeStatus(), recProtIS.consumed(), // and get the number of produced bytes:
        appData.placeTo(dsts, offset, length));
    } catch (BufferUnderflowException e) {
        src.reset();
        return new SSLEngineResult(SSLEngineResult.Status.BUFFER_UNDERFLOW, getHandshakeStatus(), 0, 0);
    } catch (AlertException e) {
        alertProtocol.alert(AlertProtocol.FATAL, e.getDescriptionCode());
        engine_was_closed = true;
        src.reset();
        if (session != null) {
            session.invalidate();
        }
        throw e.getReason();
    } catch (SSLException e) {
        throw e;
    } catch (IOException e) {
        alertProtocol.alert(AlertProtocol.FATAL, AlertProtocol.INTERNAL_ERROR);
        engine_was_closed = true;
        throw new SSLException(e.getMessage());
    }
}
Example 25
Project: diceros-master  File: BaseBlockCipher.java View source code
@Override
protected int engineUpdate(ByteBuffer input, ByteBuffer output) throws ShortBufferException {
    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();
    }
    return cipher.processByteBuffer(input, output);
}
Example 26
Project: ibis-ipl-master  File: BufferedArrayInputStream.java View source code
@Override
public void readByteBuffer(ByteBuffer value) throws IOException, ReadOnlyBufferException {
    int len = value.limit() - value.position();
    if (buffered_bytes >= len) {
        value.put(buffer, index, len);
        index += len;
        buffered_bytes -= len;
    } else {
        if (buffered_bytes != 0) {
            value.put(buffer, index, buffered_bytes);
            len -= buffered_bytes;
            buffered_bytes = 0;
        }
        index = 0;
        if (value.hasArray()) {
            in.read(value.array(), value.arrayOffset(), len);
            value.position(value.limit());
            bytes += len;
        } else {
            do {
                int toread = Math.min(len, BUF_SIZE);
                fillBuffer(toread);
                if (len < buffered_bytes) {
                    toread = len;
                } else {
                    toread = buffered_bytes;
                }
                value.put(buffer, index, toread);
                len -= toread;
                index += toread;
                buffered_bytes -= toread;
            } while (len > 0);
        }
    }
}
Example 27
Project: MINA-master  File: IoBuffer.java View source code
/**
     * @see ByteBuffer#put(ByteBuffer)
     */
public IoBuffer put(IoBuffer src) {
    if (src == this) {
        // NOSONAR, checking the instance
        throw new IllegalArgumentException();
    }
    if (remaining() < src.remaining()) {
        throw new BufferOverflowException();
    }
    if (isReadOnly()) {
        throw new ReadOnlyBufferException();
    }
    while (src.hasRemaining()) {
        put(src.get());
    }
    return this;
}
Example 28
Project: property-db-master  File: Cipher.java View source code
/** {@collect.stats}
     * 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 29
Project: XobotOS-master  File: SSLEngineImpl.java View source code
/**
     * Decodes one complete SSL/TLS record provided in the source buffer.
     * If decoded record contained application data, this data will
     * be placed in the destination buffers.
     * For more information about TLS record fragmentation see
     * TLS v 1 specification (http://www.ietf.org/rfc/rfc2246.txt) p 6.2.
     * @param src source buffer containing SSL/TLS record.
     * @param dsts destination buffers to place received application data.
     * @see javax.net.ssl.SSLEngine#unwrap(ByteBuffer,ByteBuffer[],int,int)
     * method documentation for more information
     */
@Override
public SSLEngineResult unwrap(ByteBuffer src, ByteBuffer[] dsts, int offset, int length) throws SSLException {
    if (engine_was_shutteddown) {
        return new SSLEngineResult(SSLEngineResult.Status.CLOSED, SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, 0, 0);
    }
    if ((src == null) || (dsts == null)) {
        throw new IllegalStateException("Some of the input parameters are null");
    }
    if (!handshake_started) {
        beginHandshake();
    }
    SSLEngineResult.HandshakeStatus handshakeStatus = getHandshakeStatus();
    // check if this call was made in spite of handshake status
    if ((session == null || engine_was_closed) && (handshakeStatus.equals(SSLEngineResult.HandshakeStatus.NEED_WRAP) || handshakeStatus.equals(SSLEngineResult.HandshakeStatus.NEED_TASK))) {
        return new SSLEngineResult(getEngineStatus(), handshakeStatus, 0, 0);
    }
    if (src.remaining() < recordProtocol.getMinRecordSize()) {
        return new SSLEngineResult(SSLEngineResult.Status.BUFFER_UNDERFLOW, getHandshakeStatus(), 0, 0);
    }
    try {
        src.mark();
        // check the destination buffers and count their capacity
        int capacity = 0;
        for (int i = offset; i < offset + length; i++) {
            if (dsts[i] == null) {
                throw new IllegalStateException("Some of the input parameters are null");
            }
            if (dsts[i].isReadOnly()) {
                throw new ReadOnlyBufferException();
            }
            capacity += dsts[i].remaining();
        }
        if (capacity < recordProtocol.getDataSize(src.remaining())) {
            return new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW, getHandshakeStatus(), 0, 0);
        }
        recProtIS.setSourceBuffer(src);
        // unwrap the record contained in source buffer, pass it
        // to appropriate client protocol (alert, handshake, or app)
        // and retrieve the type of unwrapped data
        int type = recordProtocol.unwrap();
        // process the data and return the result
        switch(type) {
            case ContentType.HANDSHAKE:
            case ContentType.CHANGE_CIPHER_SPEC:
                if (handshakeProtocol.getStatus().equals(SSLEngineResult.HandshakeStatus.FINISHED)) {
                    session = recordProtocol.getSession();
                }
                break;
            case ContentType.APPLICATION_DATA:
                break;
            case ContentType.ALERT:
                if (alertProtocol.isFatalAlert()) {
                    alertProtocol.setProcessed();
                    if (session != null) {
                        session.invalidate();
                    }
                    String description = "Fatal alert received " + alertProtocol.getAlertDescription();
                    shutdown();
                    throw new SSLException(description);
                } else {
                    if (logger != null) {
                        logger.println("Warning allert has been received: " + alertProtocol.getAlertDescription());
                    }
                    switch(alertProtocol.getDescriptionCode()) {
                        case AlertProtocol.CLOSE_NOTIFY:
                            alertProtocol.setProcessed();
                            close_notify_was_received = true;
                            if (!close_notify_was_sent) {
                                closeOutbound();
                                closeInbound();
                            } else {
                                closeInbound();
                                shutdown();
                            }
                            break;
                        case AlertProtocol.NO_RENEGOTIATION:
                            alertProtocol.setProcessed();
                            if (session == null) {
                                // handshake
                                throw new AlertException(AlertProtocol.HANDSHAKE_FAILURE, new SSLHandshakeException("Received no_renegotiation " + "during the initial handshake"));
                            } else {
                                // just stop the handshake
                                handshakeProtocol.stop();
                            }
                            break;
                        default:
                            alertProtocol.setProcessed();
                    }
                }
                break;
        }
        return new SSLEngineResult(getEngineStatus(), getHandshakeStatus(), recProtIS.consumed(), // and get the number of produced bytes:
        appData.placeTo(dsts, offset, length));
    } catch (BufferUnderflowException e) {
        src.reset();
        return new SSLEngineResult(SSLEngineResult.Status.BUFFER_UNDERFLOW, getHandshakeStatus(), 0, 0);
    } catch (AlertException e) {
        alertProtocol.alert(AlertProtocol.FATAL, e.getDescriptionCode());
        engine_was_closed = true;
        src.reset();
        if (session != null) {
            session.invalidate();
        }
        throw e.getReason();
    } catch (SSLException e) {
        throw e;
    } catch (IOException e) {
        alertProtocol.alert(AlertProtocol.FATAL, AlertProtocol.INTERNAL_ERROR);
        engine_was_closed = true;
        throw new SSLException(e.getMessage());
    }
}
Example 30
Project: asyn4j-master  File: IoBufferTest.java View source code
@Test
public void testReadOnlyBuffer() throws Exception {
    IoBuffer original;
    IoBuffer duplicate;
    // Test if the buffer is duplicated correctly.
    original = IoBuffer.allocate(16).sweep();
    original.position(4);
    original.limit(10);
    duplicate = original.asReadOnlyBuffer();
    original.put(4, (byte) 127);
    assertEquals(4, duplicate.position());
    assertEquals(10, duplicate.limit());
    assertEquals(16, duplicate.capacity());
    assertNotSame(original.buf(), duplicate.buf());
    assertEquals(127, duplicate.get(4));
    // Try to expand.
    try {
        original = IoBuffer.allocate(16);
        duplicate = original.asReadOnlyBuffer();
        duplicate.putString("A very very very very looooooong string", Charset.forName("ISO-8859-1").newEncoder());
        fail("ReadOnly buffer's can't be expanded");
    } catch (ReadOnlyBufferException e) {
        assertTrue(true);
    }
}
Example 31
Project: gecko-master  File: IoBufferTest.java View source code
@Test
public void testReadOnlyBuffer() throws Exception {
    IoBuffer original;
    IoBuffer duplicate;
    // Test if the buffer is duplicated correctly.
    original = IoBuffer.allocate(16).sweep();
    original.position(4);
    original.limit(10);
    duplicate = original.asReadOnlyBuffer();
    original.put(4, (byte) 127);
    assertEquals(4, duplicate.position());
    assertEquals(10, duplicate.limit());
    assertEquals(16, duplicate.capacity());
    assertNotSame(original.buf(), duplicate.buf());
    assertEquals(127, duplicate.get(4));
    // Try to expand.
    try {
        original = IoBuffer.allocate(16);
        duplicate = original.asReadOnlyBuffer();
        duplicate.putString("A very very very very looooooong string", Charset.forName("ISO-8859-1").newEncoder());
        fail("ReadOnly buffer's can't be expanded");
    } catch (ReadOnlyBufferException e) {
        assertTrue(true);
    }
}
Example 32
Project: ISAAC-master  File: ByteArrayDataBuffer.java View source code
/**
    * Trim to size.
    */
public void trimToSize() {
    if (this.readOnly) {
        throw new ReadOnlyBufferException();
    }
    final long lockStamp = this.sl.writeLock();
    try {
        if ((this.position < this.data.length) && (this.used < this.data.length)) {
            final int newSize = Math.max(this.position, this.used);
            final byte[] newData = new byte[newSize];
            System.arraycopy(this.data, 0, newData, 0, newSize);
            this.data = newData;
        }
    } finally {
        this.sl.unlockWrite(lockStamp);
    }
}
Example 33
Project: memcached-master  File: IoBufferTest.java View source code
@Test
public void testReadOnlyBuffer() throws Exception {
    IoBuffer original;
    IoBuffer duplicate;
    // Test if the buffer is duplicated correctly.
    original = IoBuffer.allocate(16).sweep();
    original.position(4);
    original.limit(10);
    duplicate = original.asReadOnlyBuffer();
    original.put(4, (byte) 127);
    assertEquals(4, duplicate.position());
    assertEquals(10, duplicate.limit());
    assertEquals(16, duplicate.capacity());
    assertNotSame(original.buf(), duplicate.buf());
    assertEquals(127, duplicate.get(4));
    // Try to expand.
    try {
        original = IoBuffer.allocate(16);
        duplicate = original.asReadOnlyBuffer();
        duplicate.putString("A very very very very looooooong string", Charset.forName("ISO-8859-1").newEncoder());
        fail("ReadOnly buffer's can't be expanded");
    } catch (ReadOnlyBufferException e) {
        assertTrue(true);
    }
}
Example 34
Project: mina-ja-master  File: IoBufferTest.java View source code
@Test
public void testReadOnlyBuffer() throws Exception {
    IoBuffer original;
    IoBuffer duplicate;
    // Test if the buffer is duplicated correctly.
    original = IoBuffer.allocate(16).sweep();
    original.position(4);
    original.limit(10);
    duplicate = original.asReadOnlyBuffer();
    original.put(4, (byte) 127);
    assertEquals(4, duplicate.position());
    assertEquals(10, duplicate.limit());
    assertEquals(16, duplicate.capacity());
    assertNotSame(original.buf(), duplicate.buf());
    assertEquals(127, duplicate.get(4));
    // Try to expand.
    try {
        original = IoBuffer.allocate(16);
        duplicate = original.asReadOnlyBuffer();
        duplicate.putString("A very very very very looooooong string", Charset.forName("ISO-8859-1").newEncoder());
        fail("ReadOnly buffer's can't be expanded");
    } catch (ReadOnlyBufferException e) {
        assertTrue(true);
    }
}
Example 35
Project: Tomcat-master  File: OpenSSLEngine.java View source code
@Override
public synchronized SSLEngineResult wrap(final ByteBuffer[] srcs, final int offset, final int length, final ByteBuffer dst) throws SSLException {
    // Check to make sure the engine has not been closed
    if (destroyed) {
        return new SSLEngineResult(SSLEngineResult.Status.CLOSED, SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, 0, 0);
    }
    // Throw required runtime exceptions
    if (srcs == null || dst == null) {
        throw new IllegalArgumentException(sm.getString("engine.nullBuffer"));
    }
    if (offset >= srcs.length || offset + length > srcs.length) {
        throw new IndexOutOfBoundsException(sm.getString("engine.invalidBufferArray", Integer.toString(offset), Integer.toString(length), Integer.toString(srcs.length)));
    }
    if (dst.isReadOnly()) {
        throw new ReadOnlyBufferException();
    }
    // Prepare OpenSSL to work in server mode and receive handshake
    if (accepted == 0) {
        beginHandshakeImplicitly();
    }
    // In handshake or close_notify stages, check if call to wrap was made
    // without regard to the handshake status.
    SSLEngineResult.HandshakeStatus handshakeStatus = getHandshakeStatus();
    if ((!handshakeFinished || engineClosed) && handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_UNWRAP) {
        return new SSLEngineResult(getEngineStatus(), SSLEngineResult.HandshakeStatus.NEED_UNWRAP, 0, 0);
    }
    int bytesProduced = 0;
    int pendingNet;
    // Check for pending data in the network BIO
    pendingNet = SSL.pendingWrittenBytesInBIO(networkBIO);
    if (pendingNet > 0) {
        // Do we have enough room in destination to write encrypted data?
        int capacity = dst.remaining();
        if (capacity < pendingNet) {
            return new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW, handshakeStatus, 0, 0);
        }
        // Write the pending data from the network BIO into the dst buffer
        try {
            bytesProduced = readEncryptedData(dst, pendingNet);
        } catch (Exception e) {
            throw new SSLException(e);
        }
        // for the receipt the peer's close_notify message -- shutdown.
        if (isOutboundDone) {
            shutdown();
        }
        return new SSLEngineResult(getEngineStatus(), getHandshakeStatus(), 0, bytesProduced);
    }
    // There was no pending data in the network BIO -- encrypt any application data
    int bytesConsumed = 0;
    int endOffset = offset + length;
    for (int i = offset; i < endOffset; ++i) {
        final ByteBuffer src = srcs[i];
        if (src == null) {
            throw new IllegalArgumentException(sm.getString("engine.nullBufferInArray"));
        }
        while (src.hasRemaining()) {
            // Write plain text application data to the SSL engine
            try {
                bytesConsumed += writePlaintextData(src);
            } catch (Exception e) {
                throw new SSLException(e);
            }
            // Check to see if the engine wrote data into the network BIO
            pendingNet = SSL.pendingWrittenBytesInBIO(networkBIO);
            if (pendingNet > 0) {
                // Do we have enough room in dst to write encrypted data?
                int capacity = dst.remaining();
                if (capacity < pendingNet) {
                    return new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW, getHandshakeStatus(), bytesConsumed, bytesProduced);
                }
                // Write the pending data from the network BIO into the dst buffer
                try {
                    bytesProduced += readEncryptedData(dst, pendingNet);
                } catch (Exception e) {
                    throw new SSLException(e);
                }
                return new SSLEngineResult(getEngineStatus(), getHandshakeStatus(), bytesConsumed, bytesProduced);
            }
        }
    }
    return new SSLEngineResult(getEngineStatus(), getHandshakeStatus(), bytesConsumed, bytesProduced);
}
Example 36
Project: xmemcached-master  File: IoBufferTest.java View source code
@Test
public void testReadOnlyBuffer() throws Exception {
    IoBuffer original;
    IoBuffer duplicate;
    // Test if the buffer is duplicated correctly.
    original = IoBuffer.allocate(16).sweep();
    original.position(4);
    original.limit(10);
    duplicate = original.asReadOnlyBuffer();
    original.put(4, (byte) 127);
    assertEquals(4, duplicate.position());
    assertEquals(10, duplicate.limit());
    assertEquals(16, duplicate.capacity());
    assertNotSame(original.buf(), duplicate.buf());
    assertEquals(127, duplicate.get(4));
    // Try to expand.
    try {
        original = IoBuffer.allocate(16);
        duplicate = original.asReadOnlyBuffer();
        duplicate.putString("A very very very very looooooong string", Charset.forName("ISO-8859-1").newEncoder());
        fail("ReadOnly buffer's can't be expanded");
    } catch (ReadOnlyBufferException e) {
        assertTrue(true);
    }
}
Example 37
Project: xnio-native-master  File: Native.java View source code
static int readSingle(final int fd, ByteBuffer buf1, Object keepAlive) throws IOException {
    if (buf1.isReadOnly()) {
        throw new ReadOnlyBufferException();
    }
    final int cnt;
    final int pos1 = buf1.position();
    final int lim1 = buf1.limit();
    if (pos1 == lim1)
        return 0;
    if (buf1.isDirect()) {
        cnt = testAndThrowRead(readD(fd, buf1, pos1, lim1, keepAlive));
        if (EXTRA_TRACE)
            log.tracef("Read(%d): %d", fd, cnt);
    } else {
        cnt = testAndThrowRead(readH(fd, buf1.array(), pos1 + buf1.arrayOffset(), lim1 + buf1.arrayOffset(), keepAlive));
        if (EXTRA_TRACE)
            log.tracef("Read(%d): %d", fd, cnt);
    }
    if (cnt > 0) {
        buf1.position(pos1 + cnt);
    }
    return cnt;
}
Example 38
Project: bazel-master  File: CodedOutputByteBufferNano.java View source code
/**
   * Encodes {@code sequence} into UTF-8, in {@code byteBuffer}. For a string, this method is
   * equivalent to {@code buffer.put(string.getBytes(UTF_8))}, but is more efficient in both time
   * and space. Bytes are written starting at the current position. This method requires paired
   * surrogates, and therefore does not support chunking.
   *
   * <p>To ensure sufficient space in the output buffer, either call {@link #encodedLength} to
   * compute the exact amount needed, or leave room for {@code 3 * sequence.length()}, which is the
   * largest possible number of bytes that any input can be encoded to.
   *
   * @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired
   *     surrogates)
   * @throws BufferOverflowException if {@code sequence} encoded in UTF-8 does not fit in
   *     {@code byteBuffer}'s remaining space.
   * @throws ReadOnlyBufferException if {@code byteBuffer} is a read-only buffer.
   */
private static void encode(CharSequence sequence, ByteBuffer byteBuffer) {
    if (byteBuffer.isReadOnly()) {
        throw new ReadOnlyBufferException();
    } else if (byteBuffer.hasArray()) {
        try {
            int encoded = encode(sequence, byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(), byteBuffer.remaining());
            byteBuffer.position(encoded - byteBuffer.arrayOffset());
        } catch (ArrayIndexOutOfBoundsException e) {
            BufferOverflowException boe = new BufferOverflowException();
            boe.initCause(e);
            throw boe;
        }
    } else {
        encodeDirect(sequence, byteBuffer);
    }
}
Example 39
Project: Correct-master  File: CodedOutputByteBufferNano.java View source code
/**
   * Encodes {@code sequence} into UTF-8, in {@code byteBuffer}. For a string, this method is
   * equivalent to {@code buffer.put(string.getBytes(UTF_8))}, but is more efficient in both time
   * and space. Bytes are written starting at the current position. This method requires paired
   * surrogates, and therefore does not support chunking.
   *
   * <p>To ensure sufficient space in the output buffer, either call {@link #encodedLength} to
   * compute the exact amount needed, or leave room for {@code 3 * sequence.length()}, which is the
   * largest possible number of bytes that any input can be encoded to.
   *
   * @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired
   *     surrogates)
   * @throws BufferOverflowException if {@code sequence} encoded in UTF-8 does not fit in
   *     {@code byteBuffer}'s remaining space.
   * @throws ReadOnlyBufferException if {@code byteBuffer} is a read-only buffer.
   */
private static void encode(CharSequence sequence, ByteBuffer byteBuffer) {
    if (byteBuffer.isReadOnly()) {
        throw new ReadOnlyBufferException();
    } else if (byteBuffer.hasArray()) {
        try {
            int encoded = encode(sequence, byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(), byteBuffer.remaining());
            byteBuffer.position(encoded - byteBuffer.arrayOffset());
        } catch (ArrayIndexOutOfBoundsException e) {
            BufferOverflowException boe = new BufferOverflowException();
            boe.initCause(e);
            throw boe;
        }
    } else {
        encodeDirect(sequence, byteBuffer);
    }
}
Example 40
Project: craft-atom-master  File: TestAdaptiveBuffer.java View source code
@Test
public void testReadOnlyBuffer() throws Exception {
    AdaptiveByteBuffer original;
    AdaptiveByteBuffer duplicate;
    // Test if the buffer is duplicated correctly.
    original = AdaptiveByteBuffer.allocate(16).sweep();
    original.position(4);
    original.limit(10);
    duplicate = original.asReadOnlyBuffer();
    original.put(4, (byte) 127);
    assertEquals(4, duplicate.position());
    assertEquals(10, duplicate.limit());
    assertEquals(16, duplicate.capacity());
    assertNotSame(original.buf(), duplicate.buf());
    assertEquals(127, duplicate.get(4));
    // Try to expand.
    try {
        original = AdaptiveByteBuffer.allocate(16);
        duplicate = original.asReadOnlyBuffer();
        duplicate.putString("A very very very very looooooong string", Charset.forName("ISO-8859-1").newEncoder());
        fail("ReadOnly buffer's can't be expanded");
    } catch (ReadOnlyBufferException e) {
        assertTrue(true);
    }
    System.out.println(String.format("[CRAFT-ATOM-UTIL] (^_^)  <%s>  Case -> test read only buffer. ", CaseCounter.incr(7)));
}
Example 41
Project: diskusage-master  File: CodedOutputByteBufferNano.java View source code
/**
   * Encodes {@code sequence} into UTF-8, in {@code byteBuffer}. For a string, this method is
   * equivalent to {@code buffer.put(string.getBytes(UTF_8))}, but is more efficient in both time
   * and space. Bytes are written starting at the current position. This method requires paired
   * surrogates, and therefore does not support chunking.
   *
   * <p>To ensure sufficient space in the output buffer, either call {@link #encodedLength} to
   * compute the exact amount needed, or leave room for {@code 3 * sequence.length()}, which is the
   * largest possible number of bytes that any input can be encoded to.
   *
   * @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired
   *     surrogates)
   * @throws BufferOverflowException if {@code sequence} encoded in UTF-8 does not fit in
   *     {@code byteBuffer}'s remaining space.
   * @throws ReadOnlyBufferException if {@code byteBuffer} is a read-only buffer.
   */
private static void encode(CharSequence sequence, ByteBuffer byteBuffer) {
    if (byteBuffer.isReadOnly()) {
        throw new ReadOnlyBufferException();
    } else if (byteBuffer.hasArray()) {
        try {
            int encoded = encode(sequence, byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(), byteBuffer.remaining());
            byteBuffer.position(encoded - byteBuffer.arrayOffset());
        } catch (ArrayIndexOutOfBoundsException e) {
            BufferOverflowException boe = new BufferOverflowException();
            boe.initCause(e);
            throw boe;
        }
    } else {
        encodeDirect(sequence, byteBuffer);
    }
}
Example 42
Project: JamVM-PH-master  File: Cipher.java View source code
/**
   * Finishes a multi-part transformation with, or completely
   * transforms, a byte buffer, and stores the result into the output
   * buffer.
   *
   * @param input  The input buffer.
   * @param output The output buffer.
   * @return The number of bytes stored into the output buffer.
   * @throws IllegalArgumentException If the input and output buffers
   *  are the same object.
   * @throws IllegalStateException If this cipher was not initialized
   *  for encryption or decryption.
   * @throws ReadOnlyBufferException If the output buffer is not
   *  writable.
   * @throws IllegalBlockSizeException If this cipher requires a total
   *  input that is a multiple of its block size to complete this
   *  transformation.
   * @throws ShortBufferException If the output buffer is not large
   *  enough to hold the transformed bytes.
   * @throws BadPaddingException If the cipher is a block cipher with
   *  a padding scheme, and the decrypted bytes do not end with a
   *  valid padding.
   * @since 1.5
   */
public final int doFinal(ByteBuffer input, ByteBuffer output) throws ReadOnlyBufferException, ShortBufferException, BadPaddingException, IllegalBlockSizeException {
    if (input == output)
        throw new IllegalArgumentException("input and output buffers cannot be the same");
    if (state != ENCRYPT_MODE && state != DECRYPT_MODE)
        throw new IllegalStateException("not initialized for encrypting or decrypting");
    return cipherSpi.engineDoFinal(input, output);
}
Example 43
Project: netty4.0.27Learn-master  File: OpenSslEngine.java View source code
@Override
public synchronized SSLEngineResult wrap(final ByteBuffer[] srcs, final int offset, final int length, final ByteBuffer dst) throws SSLException {
    // Check to make sure the engine has not been closed
    if (destroyed != 0) {
        return new SSLEngineResult(CLOSED, NOT_HANDSHAKING, 0, 0);
    }
    // Throw required runtime exceptions
    if (srcs == null) {
        throw new IllegalArgumentException("srcs is null");
    }
    if (dst == null) {
        throw new IllegalArgumentException("dst is null");
    }
    if (offset >= srcs.length || offset + length > srcs.length) {
        throw new IndexOutOfBoundsException("offset: " + offset + ", length: " + length + " (expected: offset <= offset + length <= srcs.length (" + srcs.length + "))");
    }
    if (dst.isReadOnly()) {
        throw new ReadOnlyBufferException();
    }
    // Prepare OpenSSL to work in server mode and receive handshake
    if (accepted == 0) {
        beginHandshakeImplicitly();
    }
    // In handshake or close_notify stages, check if call to wrap was made
    // without regard to the handshake status.
    SSLEngineResult.HandshakeStatus handshakeStatus = getHandshakeStatus();
    if ((!handshakeFinished || engineClosed) && handshakeStatus == NEED_UNWRAP) {
        return new SSLEngineResult(getEngineStatus(), NEED_UNWRAP, 0, 0);
    }
    int bytesProduced = 0;
    int pendingNet;
    // Check for pending data in the network BIO
    pendingNet = SSL.pendingWrittenBytesInBIO(networkBIO);
    if (pendingNet > 0) {
        // Do we have enough room in dst to write encrypted data?
        int capacity = dst.remaining();
        if (capacity < pendingNet) {
            return new SSLEngineResult(BUFFER_OVERFLOW, handshakeStatus, 0, bytesProduced);
        }
        // Write the pending data from the network BIO into the dst buffer
        try {
            bytesProduced += readEncryptedData(dst, pendingNet);
        } catch (Exception e) {
            throw new SSLException(e);
        }
        // for the receipt the peer's close_notify message -- shutdown.
        if (isOutboundDone) {
            shutdown();
        }
        return new SSLEngineResult(getEngineStatus(), getHandshakeStatus(), 0, bytesProduced);
    }
    // There was no pending data in the network BIO -- encrypt any application data
    int bytesConsumed = 0;
    int endOffset = offset + length;
    for (int i = offset; i < endOffset; ++i) {
        final ByteBuffer src = srcs[i];
        if (src == null) {
            throw new IllegalArgumentException("srcs[" + i + "] is null");
        }
        while (src.hasRemaining()) {
            // Write plaintext application data to the SSL engine
            try {
                bytesConsumed += writePlaintextData(src);
            } catch (Exception e) {
                throw new SSLException(e);
            }
            // Check to see if the engine wrote data into the network BIO
            pendingNet = SSL.pendingWrittenBytesInBIO(networkBIO);
            if (pendingNet > 0) {
                // Do we have enough room in dst to write encrypted data?
                int capacity = dst.remaining();
                if (capacity < pendingNet) {
                    return new SSLEngineResult(BUFFER_OVERFLOW, getHandshakeStatus(), bytesConsumed, bytesProduced);
                }
                // Write the pending data from the network BIO into the dst buffer
                try {
                    bytesProduced += readEncryptedData(dst, pendingNet);
                } catch (Exception e) {
                    throw new SSLException(e);
                }
                return new SSLEngineResult(getEngineStatus(), getHandshakeStatus(), bytesConsumed, bytesProduced);
            }
        }
    }
    return new SSLEngineResult(getEngineStatus(), getHandshakeStatus(), bytesConsumed, bytesProduced);
}
Example 44
Project: test-master  File: CodedOutputByteBufferNano.java View source code
/**
   * Encodes {@code sequence} into UTF-8, in {@code byteBuffer}. For a string, this method is
   * equivalent to {@code buffer.put(string.getBytes(UTF_8))}, but is more efficient in both time
   * and space. Bytes are written starting at the current position. This method requires paired
   * surrogates, and therefore does not support chunking.
   *
   * <p>To ensure sufficient space in the output buffer, either call {@link #encodedLength} to
   * compute the exact amount needed, or leave room for {@code 3 * sequence.length()}, which is the
   * largest possible number of bytes that any input can be encoded to.
   *
   * @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired
   *     surrogates)
   * @throws BufferOverflowException if {@code sequence} encoded in UTF-8 does not fit in
   *     {@code byteBuffer}'s remaining space.
   * @throws ReadOnlyBufferException if {@code byteBuffer} is a read-only buffer.
   */
private static void encode(CharSequence sequence, ByteBuffer byteBuffer) {
    if (byteBuffer.isReadOnly()) {
        throw new ReadOnlyBufferException();
    } else if (byteBuffer.hasArray()) {
        try {
            int encoded = encode(sequence, byteBuffer.array(), byteBuffer.arrayOffset() + byteBuffer.position(), byteBuffer.remaining());
            byteBuffer.position(encoded - byteBuffer.arrayOffset());
        } catch (ArrayIndexOutOfBoundsException e) {
            BufferOverflowException boe = new BufferOverflowException();
            boe.initCause(e);
            throw boe;
        }
    } else {
        encodeDirect(sequence, byteBuffer);
    }
}
Example 45
Project: classlib6-master  File: Cipher.java View source code
/**
     * 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 46
Project: ikvm-openjdk-master  File: Cipher.java View source code
/**
     * 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 47
Project: jdk7u-jdk-master  File: Cipher.java View source code
/**
     * 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 48
Project: ManagedRuntimeInitiative-master  File: Cipher.java View source code
/**
     * 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 49
Project: openjdk8-jdk-master  File: Cipher.java View source code
/**
     * 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 50
Project: xnio-master  File: BuffersTestCase.java View source code
public void testAssertWritable() {
    final ByteBuffer buffer = ByteBuffer.allocate(10);
    final ByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();
    Buffers.assertWritable(new ByteBuffer[] { buffer });
    Buffers.assertWritable(new ByteBuffer[] { buffer, buffer, buffer, buffer });
    Buffers.assertWritable(new ByteBuffer[] { buffer, buffer, buffer }, 0, 2);
    Buffers.assertWritable(new ByteBuffer[] { readOnlyBuffer, readOnlyBuffer, buffer, buffer, buffer, buffer, buffer, readOnlyBuffer }, 2, 5);
    ReadOnlyBufferException expected = null;
    try {
        Buffers.assertWritable(new ByteBuffer[] { readOnlyBuffer });
    } catch (ReadOnlyBufferException e) {
        expected = e;
    }
    assertNotNull(expected);
    expected = null;
    try {
        Buffers.assertWritable(new ByteBuffer[] { buffer, buffer, buffer, readOnlyBuffer });
    } catch (ReadOnlyBufferException e) {
        expected = e;
    }
    assertNotNull(expected);
    expected = null;
    try {
        Buffers.assertWritable(new ByteBuffer[] { readOnlyBuffer, readOnlyBuffer, readOnlyBuffer }, 1, 1);
    } catch (ReadOnlyBufferException e) {
        expected = e;
    }
    assertNotNull(expected);
    expected = null;
    try {
        Buffers.assertWritable(new ByteBuffer[] { readOnlyBuffer, readOnlyBuffer, buffer, readOnlyBuffer }, 2, 2);
    } catch (ReadOnlyBufferException e) {
        expected = e;
    }
    assertNotNull(expected);
}
Example 51
Project: RankCapes-master  File: PacketServer.java View source code
// "implement" this so child classes don't have to.
@Override
public final void read(ByteBuffer data) throws BufferOverflowException, ReadOnlyBufferException {
}
Example 52
Project: disunity-master  File: ByteBufferUtils.java View source code
public static void checkNotReadOnly(ByteBuffer buffer) {
    if (buffer.isReadOnly()) {
        throw new ReadOnlyBufferException();
    }
}
Example 53
Project: jboss-marshalling-master  File: ByteBufferOutput.java View source code
/** {@inheritDoc} */
public void write(final int b) throws IOException {
    try {
        buffer.put((byte) b);
    } catch (BufferOverflowException e) {
        throw writePastEnd();
    } catch (ReadOnlyBufferException e) {
        throw readOnlyBuffer();
    }
}
Example 54
Project: catalyst-master  File: ReadOnlyBuffer.java View source code
@Override
public Buffer compact() {
    throw new ReadOnlyBufferException();
}
Example 55
Project: netty-learning-master  File: ReadOnlyChannelBuffer.java View source code
public byte[] array() {
    throw new ReadOnlyBufferException();
}
Example 56
Project: netty.book.kor-master  File: ReadOnlyDirectByteBufferBufTest.java View source code
@Test(expected = ReadOnlyBufferException.class)
public void testSetByte() {
    ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
    buffers.add(buf);
    buf.setByte(0, 1);
}
Example 57
Project: netty3.9-note-master  File: ReadOnlyChannelBuffer.java View source code
public byte[] array() {
    throw new ReadOnlyBufferException();
}
Example 58
Project: netty4study-master  File: ReadOnlyDirectByteBufferBufTest.java View source code
@Test(expected = ReadOnlyBufferException.class)
public void testSetByte() {
    ByteBuf buf = buffer(allocate(8).asReadOnlyBuffer());
    buffers.add(buf);
    buf.setByte(0, 1);
}
Example 59
Project: NLiveRoid-master  File: ReadOnlyChannelBuffer.java View source code
public byte[] array() {
    throw new ReadOnlyBufferException();
}
Example 60
Project: OpenRQ-master  File: FECParametersReadWriteTest.java View source code
@Test(expected = ReadOnlyBufferException.class)
public void testWriteToBufferExceptionReadOnlyBuffer() {
    final ByteBuffer buffer = ByteBuffer.allocate(12);
    PARAMS.writeTo(buffer.asReadOnlyBuffer());
}
Example 61
Project: streamline-master  File: ReadOnlyChannelBuffer.java View source code
public byte[] array() {
    throw new ReadOnlyBufferException();
}
Example 62
Project: constellation-master  File: Table.java View source code
/**
     * Modifie la valeur pour la ligne et colonne spécifiées. La colonne 0 correspond au vecteur
     * des <var>x</var>. Toutes les autres colonnes correspondent aux vecteurs des <var>y</var>.
     * La plupart du temps, les valeurs de la colonne 0 ne sont pas modifiables.
     *
     * @param  row    La ligne désirée, de 0 inclusivement jusqu'à {@link #getNumRow} exclusivement.
     * @param  column La colonne désirée, de 0 inclusivement jusqu'à {@link #getNumCol} exclusivement.
     * @param  value  La nouvelle valeur à affecter à la position spécifiée.
     * @throws IndexOutOfBoundsException si l'index de la ligne ou de la colonne est en dehors des
     *         limites permises.
     * @throws ReadOnlyBufferException si les valeurs de la colonne spécifiée ne sont pas modifiables.
     */
public final void setElement(final int row, final int column, final double value) throws IndexOutOfBoundsException, ReadOnlyBufferException {
    if (column == 0) {
        throw new ReadOnlyBufferException();
    }
    y[column - 1].put(row, value);
}
Example 63
Project: android_frameworks_base-master  File: MediaCodec.java View source code
/**
         * Set the crop rectangle associated with this frame.
         * <p>
         * The crop rectangle specifies the region of valid pixels in the image,
         * using coordinates in the largest-resolution plane.
         */
@Override
public void setCropRect(@Nullable Rect cropRect) {
    if (mIsReadOnly) {
        throw new ReadOnlyBufferException();
    }
    super.setCropRect(cropRect);
}
Example 64
Project: platform_frameworks_base-master  File: MediaCodec.java View source code
/**
         * Set the crop rectangle associated with this frame.
         * <p>
         * The crop rectangle specifies the region of valid pixels in the image,
         * using coordinates in the largest-resolution plane.
         */
@Override
public void setCropRect(@Nullable Rect cropRect) {
    if (mIsReadOnly) {
        throw new ReadOnlyBufferException();
    }
    super.setCropRect(cropRect);
}