summaryrefslogtreecommitdiffstats
path: root/harmony-tests
diff options
context:
space:
mode:
authorElliott Hughes <enh@google.com>2013-04-26 16:15:14 -0700
committerElliott Hughes <enh@google.com>2013-04-26 16:15:14 -0700
commitdce2b2fa9d6b26414a8d5a55918e4d7ca2ab1baa (patch)
treecf95e9a88fac620c56f4a43a54df923051000f39 /harmony-tests
parentae662ed06a79610f18f973fe2a0e25ece2dfab52 (diff)
downloadlibcore-dce2b2fa9d6b26414a8d5a55918e4d7ca2ab1baa.zip
libcore-dce2b2fa9d6b26414a8d5a55918e4d7ca2ab1baa.tar.gz
libcore-dce2b2fa9d6b26414a8d5a55918e4d7ca2ab1baa.tar.bz2
Add the harmony nio tests.
Change-Id: I8a6d167743b20f31e769fe57d3aba89e16de24c3
Diffstat (limited to 'harmony-tests')
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/AbstractBufferTest.java306
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferOverflowExceptionTest.java52
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferUnderflowExceptionTest.java55
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteBufferTest.java2177
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java40
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/CharBufferTest.java1081
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectByteBufferTest.java60
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectCharBufferTest.java61
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectDoubleBufferTest.java60
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectFloatBufferTest.java61
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectIntBufferTest.java61
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectLongBufferTest.java62
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectShortBufferTest.java61
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DoubleBufferTest.java664
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateDirectByteBufferTest.java31
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateHeapByteBufferTest.java32
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateWrappedByteBufferTest.java32
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/FloatBufferTest.java674
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapByteBufferTest.java60
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapCharBufferTest.java44
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapDoubleBufferTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapFloatBufferTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapIntBufferTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapLongBufferTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapShortBufferTest.java42
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/IntBufferTest.java650
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/InvalidMarkExceptionTest.java51
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/LongBufferTest.java657
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/MappedByteBufferTest.java231
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyBufferExceptionTest.java51
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyCharBufferTest.java209
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDirectByteBufferTest.java44
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDoubleBufferTest.java160
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyFloatBufferTest.java161
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapByteBufferTest.java43
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapCharBufferTest.java35
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapDoubleBufferTest.java34
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapFloatBufferTest.java32
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapIntBufferTest.java32
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapLongBufferTest.java32
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapShortBufferTest.java32
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyIntBufferTest.java161
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyLongBufferTest.java161
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyShortBufferTest.java161
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedByteBufferTest.java45
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedCharBufferTest1.java34
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedDoubleBufferTest.java32
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedFloatBufferTest.java32
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedIntBufferTest.java32
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedLongBufferTest.java32
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedShortBufferTest.java32
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ShortBufferTest.java637
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceDirectByteBufferTest.java32
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceHeapByteBufferTest.java33
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceWrappedByteBufferTest.java33
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedByteBufferTest.java97
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest1.java84
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest2.java129
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedDoubleBufferTest.java87
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedFloatBufferTest.java87
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedIntBufferTest.java87
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedLongBufferTest.java87
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedShortBufferTest.java87
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AlreadyConnectedExceptionTest.java54
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AsynchronousCloseExceptionTest.java54
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/CancelledKeyExceptionTest.java54
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ChannelsTest.java622
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedByInterruptExceptionTest.java53
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedChannelExceptionTest.java54
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedSelectorExceptionTest.java54
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ConnectionPendingExceptionTest.java54
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileChannelLockingTest.java208
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileChannelTest.java3121
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockInterruptionExceptionTest.java55
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockTest.java199
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalBlockingModeExceptionTest.java55
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalSelectorExceptionTest.java54
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MapModeTest.java52
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockServerSocketChannel.java46
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockSocketChannel.java75
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NoConnectionPendingExceptionTest.java55
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonReadableChannelExceptionTest.java54
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonWritableChannelExceptionTest.java54
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetBoundExceptionTest.java54
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetConnectedExceptionTest.java54
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/OverlappingFileLockExceptionTest.java55
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/PipeTest.java59
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectableChannelTest.java89
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectionKeyTest.java321
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectorTest.java689
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ServerSocketChannelTest.java682
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SinkChannelTest.java505
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SocketChannelTest.java3628
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SourceChannelTest.java532
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnixSelectorTest.java130
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnresolvedAddressExceptionTest.java54
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.java55
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractInterruptibleChannelTest.java136
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectableChannelTest.java313
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectionKeyTest.java76
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectorTest.java160
-rw-r--r--harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/MockAbstractSelector.java89
102 files changed, 23248 insertions, 0 deletions
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/AbstractBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/AbstractBufferTest.java
new file mode 100644
index 0000000..eb48992
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/AbstractBufferTest.java
@@ -0,0 +1,306 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.Buffer;
+import java.nio.ByteBuffer;
+import java.nio.InvalidMarkException;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests a java.nio.Buffer instance.
+ */
+public class AbstractBufferTest extends TestCase {
+
+ protected Buffer baseBuf;
+
+ protected void setUp() throws Exception{
+ super.setUp();
+ baseBuf = ByteBuffer.allocate(10);
+ }
+
+ protected void tearDown() throws Exception{
+ super.tearDown();
+ }
+
+ public void testCapacity() {
+ assertTrue(0 <= baseBuf.position() && baseBuf.position() <= baseBuf.limit()
+ && baseBuf.limit() <= baseBuf.capacity());
+ }
+
+ public void testClear() {
+ // save state
+ int oldPosition = baseBuf.position();
+ int oldLimit = baseBuf.limit();
+
+ Buffer ret = baseBuf.clear();
+ assertSame(ret, baseBuf);
+ assertEquals(baseBuf.position(), 0);
+ assertEquals(baseBuf.limit(), baseBuf.capacity());
+ try {
+ baseBuf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$S
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // restore state
+ baseBuf.limit(oldLimit);
+ baseBuf.position(oldPosition);
+ }
+
+ public void testFlip() {
+ // save state
+ int oldPosition = baseBuf.position();
+ int oldLimit = baseBuf.limit();
+
+ Buffer ret = baseBuf.flip();
+ assertSame(ret, baseBuf);
+ assertEquals(baseBuf.position(), 0);
+ assertEquals(baseBuf.limit(), oldPosition);
+ try {
+ baseBuf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // restore state
+ baseBuf.limit(oldLimit);
+ baseBuf.position(oldPosition);
+ }
+
+ public void testHasRemaining() {
+ // save state
+ int oldPosition = baseBuf.position();
+ int oldLimit = baseBuf.limit();
+
+ assertEquals(baseBuf.hasRemaining(), baseBuf.position() < baseBuf.limit());
+ baseBuf.position(baseBuf.limit());
+ assertFalse(baseBuf.hasRemaining());
+
+ // restore state
+ baseBuf.limit(oldLimit);
+ baseBuf.position(oldPosition);
+ }
+
+ public void testIsReadOnly() {
+ baseBuf.isReadOnly();
+ }
+
+ /*
+ * Class under test for int limit()
+ */
+ public void testLimit() {
+ assertTrue(0 <= baseBuf.position() && baseBuf.position() <= baseBuf.limit()
+ && baseBuf.limit() <= baseBuf.capacity());
+ }
+
+ /*
+ * Class under test for Buffer limit(int)
+ */
+ public void testLimitint() {
+ // save state
+ int oldPosition = baseBuf.position();
+ int oldLimit = baseBuf.limit();
+
+ Buffer ret = baseBuf.limit(baseBuf.limit());
+ assertSame(ret, baseBuf);
+
+ baseBuf.mark();
+ baseBuf.limit(baseBuf.capacity());
+ assertEquals(baseBuf.limit(), baseBuf.capacity());
+ // position should not change
+ assertEquals(baseBuf.position(), oldPosition);
+ // mark should be valid
+ baseBuf.reset();
+
+ if (baseBuf.capacity() > 0) {
+ baseBuf.limit(baseBuf.capacity());
+ baseBuf.position(baseBuf.capacity());
+ baseBuf.mark();
+ baseBuf.limit(baseBuf.capacity() - 1);
+ // position should be the new limit
+ assertEquals(baseBuf.position(), baseBuf.limit());
+ // mark should be invalid
+ try {
+ baseBuf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+ }
+
+ try {
+ baseBuf.limit(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ baseBuf.limit(baseBuf.capacity() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ // restore state
+ baseBuf.limit(oldLimit);
+ baseBuf.position(oldPosition);
+ }
+
+ public void testMark() {
+ // save state
+ int oldPosition = baseBuf.position();
+ int oldLimit = baseBuf.limit();
+
+ Buffer ret = baseBuf.mark();
+ assertSame(ret, baseBuf);
+
+ baseBuf.mark();
+ baseBuf.position(baseBuf.limit());
+ baseBuf.reset();
+ assertEquals(baseBuf.position(), oldPosition);
+
+ baseBuf.mark();
+ baseBuf.position(baseBuf.limit());
+ baseBuf.reset();
+ assertEquals(baseBuf.position(), oldPosition);
+
+ // restore state
+ baseBuf.limit(oldLimit);
+ baseBuf.position(oldPosition);
+ }
+
+ /*
+ * Class under test for int position()
+ */
+ public void testPosition() {
+ assertTrue(0 <= baseBuf.position() && baseBuf.position() <= baseBuf.limit()
+ && baseBuf.limit() <= baseBuf.capacity());
+ }
+
+ /*
+ * Class under test for Buffer position(int)
+ */
+ public void testPositionint() {
+ // save state
+ int oldPosition = baseBuf.position();
+ int oldLimit = baseBuf.limit();
+
+ try {
+ baseBuf.position(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ baseBuf.position(baseBuf.limit() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ baseBuf.mark();
+ baseBuf.position(baseBuf.position());
+ baseBuf.reset();
+ assertEquals(baseBuf.position(), oldPosition);
+
+ baseBuf.position(0);
+ assertEquals(baseBuf.position(), 0);
+ baseBuf.position(baseBuf.limit());
+ assertEquals(baseBuf.position(), baseBuf.limit());
+
+ if (baseBuf.capacity() > 0) {
+ baseBuf.limit(baseBuf.capacity());
+ baseBuf.position(baseBuf.limit());
+ baseBuf.mark();
+ baseBuf.position(baseBuf.limit() - 1);
+ assertEquals(baseBuf.position(), baseBuf.limit() - 1);
+ // mark should be invalid
+ try {
+ baseBuf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+ }
+
+ Buffer ret = baseBuf.position(0);
+ assertSame(ret, baseBuf);
+
+ // restore state
+ baseBuf.limit(oldLimit);
+ baseBuf.position(oldPosition);
+ }
+
+ public void testRemaining() {
+ assertEquals(baseBuf.remaining(), baseBuf.limit() - baseBuf.position());
+ }
+
+ public void testReset() {
+ // save state
+ int oldPosition = baseBuf.position();
+ int oldLimit = baseBuf.limit();
+
+ baseBuf.mark();
+ baseBuf.position(baseBuf.limit());
+ baseBuf.reset();
+ assertEquals(baseBuf.position(), oldPosition);
+
+ baseBuf.mark();
+ baseBuf.position(baseBuf.limit());
+ baseBuf.reset();
+ assertEquals(baseBuf.position(), oldPosition);
+
+ Buffer ret = baseBuf.reset();
+ assertSame(ret, baseBuf);
+
+ baseBuf.clear();
+ try {
+ baseBuf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // restore state
+ baseBuf.limit(oldLimit);
+ baseBuf.position(oldPosition);
+ }
+
+ public void testRewind() {
+ // save state
+ int oldPosition = baseBuf.position();
+ int oldLimit = baseBuf.limit();
+
+ Buffer ret = baseBuf.rewind();
+ assertEquals(baseBuf.position(), 0);
+ assertSame(ret, baseBuf);
+ try {
+ baseBuf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // restore state
+ baseBuf.limit(oldLimit);
+ baseBuf.position(oldPosition);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferOverflowExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferOverflowExceptionTest.java
new file mode 100644
index 0000000..39059fe
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferOverflowExceptionTest.java
@@ -0,0 +1,52 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.BufferOverflowException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class BufferOverflowExceptionTest extends TestCase {
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new BufferOverflowException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new BufferOverflowException());
+ }
+
+ /**
+ *@tests {@link java.nio.BufferOverflowException#BufferOverflowException()}
+ */
+ public void test_Constructor() {
+ BufferOverflowException exception = new BufferOverflowException();
+ assertNull(exception.getMessage());
+ assertNull(exception.getLocalizedMessage());
+ assertNull(exception.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferUnderflowExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferUnderflowExceptionTest.java
new file mode 100644
index 0000000..a056ebf
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/BufferUnderflowExceptionTest.java
@@ -0,0 +1,55 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.BufferUnderflowException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for BufferUnderflowException
+ */
+public class BufferUnderflowExceptionTest extends TestCase {
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new BufferUnderflowException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new BufferUnderflowException());
+ }
+
+ /**
+ *@tests {@link java.nio.BufferUnderflowException#BufferUnderflowException()}
+ */
+ public void test_Constructor() {
+ BufferUnderflowException exception = new BufferUnderflowException();
+ assertNull(exception.getMessage());
+ assertNull(exception.getLocalizedMessage());
+ assertNull(exception.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteBufferTest.java
new file mode 100644
index 0000000..d6d8681
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteBufferTest.java
@@ -0,0 +1,2177 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.BufferOverflowException;
+import java.nio.BufferUnderflowException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.CharBuffer;
+import java.nio.DoubleBuffer;
+import java.nio.FloatBuffer;
+import java.nio.IntBuffer;
+import java.nio.InvalidMarkException;
+import java.nio.LongBuffer;
+import java.nio.ReadOnlyBufferException;
+import java.nio.ShortBuffer;
+import java.util.Arrays;
+
+/**
+ * Tests java.nio.ByteBuffer
+ *
+ */
+public class ByteBufferTest extends AbstractBufferTest {
+ protected static final int SMALL_TEST_LENGTH = 5;
+ protected static final int BUFFER_LENGTH = 250;
+
+ protected ByteBuffer buf;
+
+ protected void setUp() throws Exception {
+ buf = ByteBuffer.allocate(10);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testArray() {
+ if (buf.hasArray()) {
+ byte array[] = buf.array();
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+ } else {
+ if (buf.isReadOnly()) {
+ try {
+ buf.array();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ // expected
+ // Note:can not tell when to throw
+ // UnsupportedOperationException
+ // or ReadOnlyBufferException, so catch all.
+ }
+ } else {
+ try {
+ buf.array();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ }
+ }
+ }
+
+ public void testArrayOffset() {
+ if (buf.hasArray()) {
+ byte array[] = buf.array();
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+ } else {
+ if (buf.isReadOnly()) {
+ try {
+ buf.arrayOffset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ // expected
+ // Note:can not tell when to throw
+ // UnsupportedOperationException
+ // or ReadOnlyBufferException, so catch all.
+ }
+ } else {
+ try {
+ buf.arrayOffset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ }
+ }
+ }
+
+ public void testAsReadOnlyBuffer() {
+ buf.clear();
+ buf.mark();
+ buf.position(buf.limit());
+
+ // readonly's contents should be the same as buf
+ ByteBuffer readonly = buf.asReadOnlyBuffer();
+ assertNotSame(buf, readonly);
+ assertTrue(readonly.isReadOnly());
+ assertEquals(buf.position(), readonly.position());
+ assertEquals(buf.limit(), readonly.limit());
+ assertEquals(buf.isDirect(), readonly.isDirect());
+ assertEquals(buf.order(), readonly.order());
+ assertContentEquals(buf, readonly);
+
+ // readonly's position, mark, and limit should be independent to buf
+ readonly.reset();
+ assertEquals(readonly.position(), 0);
+ readonly.clear();
+ assertEquals(buf.position(), buf.limit());
+ buf.reset();
+ assertEquals(buf.position(), 0);
+ }
+
+ public void testCompact() {
+ if (buf.isReadOnly()) {
+ try {
+ buf.compact();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ // case: buffer is full
+ buf.clear();
+ buf.mark();
+ loadTestData1(buf);
+ ByteBuffer ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), buf.capacity());
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, (byte) 0, buf.capacity());
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // case: buffer is empty
+ buf.position(0);
+ buf.limit(0);
+ buf.mark();
+ ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), 0);
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, (byte) 0, buf.capacity());
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // case: normal
+ assertTrue(buf.capacity() > SMALL_TEST_LENGTH);
+ buf.position(1);
+ buf.limit(SMALL_TEST_LENGTH);
+ buf.mark();
+ ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), 4);
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, (byte) 1, 4);
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+ }
+
+ public void testCompareTo() {
+ // compare to self
+ assertEquals(0, buf.compareTo(buf));
+
+ // normal cases
+ if (!buf.isReadOnly()) {
+ assertTrue(buf.capacity() > SMALL_TEST_LENGTH);
+ buf.clear();
+ ByteBuffer other = ByteBuffer.allocate(buf.capacity());
+ loadTestData1(buf);
+ loadTestData1(other);
+ assertEquals(0, buf.compareTo(other));
+ assertEquals(0, other.compareTo(buf));
+ buf.position(1);
+ assertTrue(buf.compareTo(other) > 0);
+ assertTrue(other.compareTo(buf) < 0);
+ other.position(2);
+ assertTrue(buf.compareTo(other) < 0);
+ assertTrue(other.compareTo(buf) > 0);
+ buf.position(2);
+ other.limit(SMALL_TEST_LENGTH);
+ assertTrue(buf.compareTo(other) > 0);
+ assertTrue(other.compareTo(buf) < 0);
+ }
+
+ assertTrue(ByteBuffer.wrap(new byte[21]).compareTo(ByteBuffer.allocateDirect(21)) == 0);
+ }
+
+ public void testDuplicate() {
+ buf.clear();
+ buf.mark();
+ buf.position(buf.limit());
+
+ // duplicate's contents should be the same as buf
+ ByteBuffer duplicate = buf.duplicate();
+ assertNotSame(buf, duplicate);
+ assertEquals(buf.position(), duplicate.position());
+ assertEquals(buf.limit(), duplicate.limit());
+ assertEquals(buf.isReadOnly(), duplicate.isReadOnly());
+ assertEquals(buf.isDirect(), duplicate.isDirect());
+ assertEquals(buf.order(), duplicate.order());
+ assertContentEquals(buf, duplicate);
+
+ // duplicate's position, mark, and limit should be independent to buf
+ duplicate.reset();
+ assertEquals(duplicate.position(), 0);
+ duplicate.clear();
+ assertEquals(buf.position(), buf.limit());
+ buf.reset();
+ assertEquals(buf.position(), 0);
+
+ // duplicate share the same content with buf
+ if (!duplicate.isReadOnly()) {
+ loadTestData1(buf);
+ assertContentEquals(buf, duplicate);
+ loadTestData2(duplicate);
+ assertContentEquals(buf, duplicate);
+ }
+ }
+
+ public void testEquals() {
+ // equal to self
+ assertTrue(buf.equals(buf));
+ ByteBuffer readonly = buf.asReadOnlyBuffer();
+ assertTrue(buf.equals(readonly));
+ ByteBuffer duplicate = buf.duplicate();
+ assertTrue(buf.equals(duplicate));
+
+ // always false, if type mismatch
+ assertFalse(buf.equals(Boolean.TRUE));
+
+ assertTrue(buf.capacity() > SMALL_TEST_LENGTH);
+
+ buf.limit(buf.capacity()).position(0);
+ readonly.limit(readonly.capacity()).position(1);
+ assertFalse(buf.equals(readonly));
+
+ buf.limit(buf.capacity() - 1).position(0);
+ duplicate.limit(duplicate.capacity()).position(0);
+ assertFalse(buf.equals(duplicate));
+ }
+
+ /*
+ * Class under test for byte get()
+ */
+ public void testGet() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ assertEquals(buf.get(), buf.get(i));
+ }
+ try {
+ buf.get();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.ByteBuffer get(byte[])
+ */
+ public void testGetbyteArray() {
+ byte array[] = new byte[1];
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ ByteBuffer ret = buf.get(array);
+ assertEquals(array[0], buf.get(i));
+ assertSame(ret, buf);
+ }
+ try {
+ buf.get(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ try {
+ buf.get((byte[])null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.ByteBuffer get(byte[], int, int)
+ */
+ public void testGetbyteArrayintint() {
+ buf.clear();
+ byte array[] = new byte[buf.capacity()];
+
+ try {
+ buf.get(new byte[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.get(array, -1, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ buf.get(array, array.length, 0);
+ try {
+ buf.get(array, array.length + 1, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.get(array, 2, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get(array, 2, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get((byte[])null, -1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ buf.get(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+
+ buf.clear();
+ ByteBuffer ret = buf.get(array, 0, array.length);
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(buf, array, 0, array.length);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for byte get(int)
+ */
+ public void testGetint() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ assertEquals(buf.get(), buf.get(i));
+ }
+ try {
+ buf.get(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get(buf.limit());
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void testHasArray() {
+ if (buf.hasArray()) {
+ assertNotNull(buf.array());
+ } else {
+ if (buf.isReadOnly()) {
+ try {
+ buf.array();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ // expected
+ // Note:can not tell when to throw
+ // UnsupportedOperationException
+ // or ReadOnlyBufferException, so catch all.
+ }
+ } else {
+ try {
+ buf.array();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ }
+ }
+ }
+
+ public void testHashCode() {
+ buf.clear();
+ loadTestData1(buf);
+ ByteBuffer readonly = buf.asReadOnlyBuffer();
+ ByteBuffer duplicate = buf.duplicate();
+ assertTrue(buf.hashCode() == readonly.hashCode());
+ assertTrue(buf.capacity() > SMALL_TEST_LENGTH);
+ duplicate.position(buf.capacity()/2);
+ assertTrue(buf.hashCode()!= duplicate.hashCode());
+ }
+
+ //for the testHashCode() method of readonly subclasses
+ protected void readOnlyHashCode() {
+ //create a new buffer initiated with some data
+ ByteBuffer buf = ByteBuffer.allocate(BUFFER_LENGTH);
+ loadTestData1(buf);
+ buf = buf.asReadOnlyBuffer();
+ buf.clear();
+ ByteBuffer readonly = buf.asReadOnlyBuffer();
+ ByteBuffer duplicate = buf.duplicate();
+ assertEquals(buf.hashCode(),readonly.hashCode());
+ duplicate.position(buf.capacity()/2);
+ assertTrue(buf.hashCode()!= duplicate.hashCode());
+ }
+
+ public void testIsDirect() {
+ buf.isDirect();
+ }
+
+ public void testOrder() {
+ // BIG_ENDIAN is the default byte order
+ assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
+
+ buf.order(ByteOrder.LITTLE_ENDIAN);
+ assertEquals(ByteOrder.LITTLE_ENDIAN, buf.order());
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
+
+ // Regression test for HARMONY-798
+ buf.order((ByteOrder)null);
+ assertEquals(ByteOrder.LITTLE_ENDIAN, buf.order());
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ /*
+ * Class under test for java.nio.ByteBuffer put(byte)
+ */
+ public void testPutbyte() {
+ if (buf.isReadOnly()) {
+ try {
+ buf.clear();
+ buf.put((byte) 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ ByteBuffer ret = buf.put((byte) i);
+ assertEquals(buf.get(i), (byte) i);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put((byte) 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.ByteBuffer put(byte[])
+ */
+ public void testPutbyteArray() {
+ byte array[] = new byte[1];
+ if (buf.isReadOnly()) {
+ try {
+ buf.put(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ array[0] = (byte) i;
+ ByteBuffer ret = buf.put(array);
+ assertEquals(buf.get(i), (byte) i);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ try {
+ buf.put((byte[])null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.ByteBuffer put(byte[], int, int)
+ */
+ public void testPutbyteArrayintint() {
+ buf.clear();
+ byte array[] = new byte[buf.capacity()];
+ if (buf.isReadOnly()) {
+ try {
+ buf.put(array, 0, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ try {
+ buf.put(new byte[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.put(array, -1, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, array.length + 1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ buf.put(array, array.length, 0);
+ assertEquals(buf.position(), 0);
+ try {
+ buf.put(array, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, 2, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ buf.put(array, 2, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put((byte[])null, 2, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ assertEquals(buf.position(), 0);
+
+ loadTestData2(array, 0, array.length);
+ ByteBuffer ret = buf.put(array, 0, array.length);
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(buf, array, 0, array.length);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for java.nio.ByteBuffer put(java.nio.ByteBuffer)
+ */
+ public void testPutByteBuffer() {
+ ByteBuffer other = ByteBuffer.allocate(buf.capacity());
+ if (buf.isReadOnly()) {
+ try {
+ buf.clear();
+ buf.put(other);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.clear();
+ buf.put((ByteBuffer)null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ try {
+ buf.put(buf);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ buf.put(ByteBuffer.allocate(buf.capacity() + 1));
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+
+ try {
+ buf.put((ByteBuffer)null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ loadTestData2(other);
+ other.clear();
+ buf.clear();
+ ByteBuffer ret = buf.put(other);
+ assertEquals(other.position(), other.capacity());
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(other, buf);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for java.nio.ByteBuffer put(int, byte)
+ */
+ public void testPutintbyte() {
+ if (buf.isReadOnly()) {
+ try {
+ buf.put(0, (byte) 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), 0);
+ ByteBuffer ret = buf.put(i, (byte) i);
+ assertEquals(buf.get(i), (byte) i);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(-1, (byte) 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(buf.limit(), (byte) 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void testSlice() {
+ assertTrue(buf.capacity() > SMALL_TEST_LENGTH);
+ buf.position(1);
+ buf.limit(buf.capacity() - 1);
+
+ ByteBuffer slice = buf.slice();
+ assertEquals(buf.isReadOnly(), slice.isReadOnly());
+ assertEquals(buf.isDirect(), slice.isDirect());
+ assertEquals(buf.order(), slice.order());
+ assertEquals(slice.position(), 0);
+ assertEquals(slice.limit(), buf.remaining());
+ assertEquals(slice.capacity(), buf.remaining());
+ try {
+ slice.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // slice share the same content with buf
+ if (!slice.isReadOnly()) {
+ loadTestData1(slice);
+ assertContentLikeTestData1(buf, 1, (byte) 0, slice.capacity());
+ buf.put(2, (byte) 100);
+ assertEquals(slice.get(1), 100);
+ }
+ }
+
+ public void testToString() {
+ String str = buf.toString();
+ assertTrue(str.indexOf("Byte") >= 0 || str.indexOf("byte") >= 0);
+ assertTrue(str.indexOf("" + buf.position()) >= 0);
+ assertTrue(str.indexOf("" + buf.limit()) >= 0);
+ assertTrue(str.indexOf("" + buf.capacity()) >= 0);
+ }
+
+ public void testAsCharBuffer() {
+ CharBuffer charBuffer;
+ byte bytes[] = new byte[2];
+ char value;
+
+ // test BIG_ENDIAN char buffer, read
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ charBuffer = buf.asCharBuffer();
+ assertSame(ByteOrder.BIG_ENDIAN, charBuffer.order());
+ while (charBuffer.remaining() > 0) {
+ buf.get(bytes);
+ value = charBuffer.get();
+ assertEquals(bytes2char(bytes, buf.order()), value);
+ }
+
+ // test LITTLE_ENDIAN char buffer, read
+ buf.clear();
+ buf.order(ByteOrder.LITTLE_ENDIAN);
+ charBuffer = buf.asCharBuffer();
+ assertSame(ByteOrder.LITTLE_ENDIAN, charBuffer.order());
+ while (charBuffer.remaining() > 0) {
+ buf.get(bytes);
+ value = charBuffer.get();
+ assertEquals(bytes2char(bytes, buf.order()), value);
+ }
+
+ if (!buf.isReadOnly()) {
+ // test BIG_ENDIAN char buffer, write
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ charBuffer = buf.asCharBuffer();
+ assertSame(ByteOrder.BIG_ENDIAN, charBuffer.order());
+ while (charBuffer.remaining() > 0) {
+ value = (char) charBuffer.remaining();
+ charBuffer.put(value);
+ buf.get(bytes);
+ assertTrue(Arrays.equals(bytes, char2bytes(value, buf.order())));
+ }
+
+ // test LITTLE_ENDIAN char buffer, write
+ buf.clear();
+ buf.order(ByteOrder.LITTLE_ENDIAN);
+ charBuffer = buf.asCharBuffer();
+ assertSame(ByteOrder.LITTLE_ENDIAN, charBuffer.order());
+ while (charBuffer.remaining() > 0) {
+ value = (char) charBuffer.remaining();
+ charBuffer.put(value);
+ buf.get(bytes);
+ assertTrue(Arrays.equals(bytes, char2bytes(value, buf.order())));
+ }
+ }
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testAsDoubleBuffer() {
+ DoubleBuffer doubleBuffer;
+ byte bytes[] = new byte[8];
+ double value;
+
+ // test BIG_ENDIAN double buffer, read
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ doubleBuffer = buf.asDoubleBuffer();
+ assertSame(ByteOrder.BIG_ENDIAN, doubleBuffer.order());
+ while (doubleBuffer.remaining() > 0) {
+ buf.get(bytes);
+ value = doubleBuffer.get();
+ if (!(Double.isNaN(bytes2double(bytes, buf.order())) && Double
+ .isNaN(value))) {
+ assertEquals(bytes2double(bytes, buf.order()), value, 0.00);
+ }
+ }
+
+ // test LITTLE_ENDIAN double buffer, read
+ buf.clear();
+ buf.order(ByteOrder.LITTLE_ENDIAN);
+ doubleBuffer = buf.asDoubleBuffer();
+ assertSame(ByteOrder.LITTLE_ENDIAN, doubleBuffer.order());
+ while (doubleBuffer.remaining() > 0) {
+ buf.get(bytes);
+ value = doubleBuffer.get();
+ if (!(Double.isNaN(bytes2double(bytes, buf.order())) && Double
+ .isNaN(value))) {
+ assertEquals(bytes2double(bytes, buf.order()), value, 0.00);
+ }
+ }
+
+ if (!buf.isReadOnly()) {
+ // test BIG_ENDIAN double buffer, write
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ doubleBuffer = buf.asDoubleBuffer();
+ assertSame(ByteOrder.BIG_ENDIAN, doubleBuffer.order());
+ while (doubleBuffer.remaining() > 0) {
+ value = (double) doubleBuffer.remaining();
+ doubleBuffer.put(value);
+ buf.get(bytes);
+ assertTrue(Arrays.equals(bytes, double2bytes(value, buf.order())));
+ }
+
+ // test LITTLE_ENDIAN double buffer, write
+ buf.clear();
+ buf.order(ByteOrder.LITTLE_ENDIAN);
+ doubleBuffer = buf.asDoubleBuffer();
+ assertSame(ByteOrder.LITTLE_ENDIAN, doubleBuffer.order());
+ while (doubleBuffer.remaining() > 0) {
+ value = (double) doubleBuffer.remaining();
+ doubleBuffer.put(value);
+ buf.get(bytes);
+ assertTrue(Arrays.equals(bytes, double2bytes(value, buf.order())));
+ }
+ }
+
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testAsFloatBuffer() {
+ FloatBuffer floatBuffer;
+ byte bytes[] = new byte[4];
+ float value;
+
+ // test BIG_ENDIAN float buffer, read
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ floatBuffer = buf.asFloatBuffer();
+ assertSame(ByteOrder.BIG_ENDIAN, floatBuffer.order());
+ while (floatBuffer.remaining() > 0) {
+ buf.get(bytes);
+ value = floatBuffer.get();
+ if (!(Float.isNaN(bytes2float(bytes, buf.order())) && Float
+ .isNaN(value))) {
+ assertEquals(bytes2float(bytes, buf.order()), value, 0.00);
+ }
+ }
+
+ // test LITTLE_ENDIAN float buffer, read
+ buf.clear();
+ buf.order(ByteOrder.LITTLE_ENDIAN);
+ floatBuffer = buf.asFloatBuffer();
+ assertSame(ByteOrder.LITTLE_ENDIAN, floatBuffer.order());
+ while (floatBuffer.remaining() > 0) {
+ buf.get(bytes);
+ value = floatBuffer.get();
+ if (!(Float.isNaN(bytes2float(bytes, buf.order())) && Float
+ .isNaN(value))) {
+ assertEquals(bytes2float(bytes, buf.order()), value, 0.00);
+ }
+ }
+
+ if (!buf.isReadOnly()) {
+ // test BIG_ENDIAN float buffer, write
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ floatBuffer = buf.asFloatBuffer();
+ assertSame(ByteOrder.BIG_ENDIAN, floatBuffer.order());
+ while (floatBuffer.remaining() > 0) {
+ value = (float) floatBuffer.remaining();
+ floatBuffer.put(value);
+ buf.get(bytes);
+ assertTrue(Arrays.equals(bytes, float2bytes(value, buf.order())));
+ }
+
+ // test LITTLE_ENDIAN float buffer, write
+ buf.clear();
+ buf.order(ByteOrder.LITTLE_ENDIAN);
+ floatBuffer = buf.asFloatBuffer();
+ assertSame(ByteOrder.LITTLE_ENDIAN, floatBuffer.order());
+ while (floatBuffer.remaining() > 0) {
+ value = (float) floatBuffer.remaining();
+ floatBuffer.put(value);
+ buf.get(bytes);
+ assertTrue(Arrays.equals(bytes, float2bytes(value, buf.order())));
+ }
+ }
+
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testAsIntBuffer() {
+ IntBuffer intBuffer;
+ byte bytes[] = new byte[4];
+ int value;
+
+ // test BIG_ENDIAN int buffer, read
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ intBuffer = buf.asIntBuffer();
+ assertSame(ByteOrder.BIG_ENDIAN, intBuffer.order());
+ while (intBuffer.remaining() > 0) {
+ buf.get(bytes);
+ value = intBuffer.get();
+ assertEquals(bytes2int(bytes, buf.order()), value);
+ }
+
+ // test LITTLE_ENDIAN int buffer, read
+ buf.clear();
+ buf.order(ByteOrder.LITTLE_ENDIAN);
+ intBuffer = buf.asIntBuffer();
+ assertSame(ByteOrder.LITTLE_ENDIAN, intBuffer.order());
+ while (intBuffer.remaining() > 0) {
+ buf.get(bytes);
+ value = intBuffer.get();
+ assertEquals(bytes2int(bytes, buf.order()), value);
+ }
+
+ if (!buf.isReadOnly()) {
+ // test BIG_ENDIAN int buffer, write
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ intBuffer = buf.asIntBuffer();
+ assertSame(ByteOrder.BIG_ENDIAN, intBuffer.order());
+ while (intBuffer.remaining() > 0) {
+ value = (int) intBuffer.remaining();
+ intBuffer.put(value);
+ buf.get(bytes);
+ assertTrue(Arrays.equals(bytes, int2bytes(value, buf.order())));
+ }
+
+ // test LITTLE_ENDIAN int buffer, write
+ buf.clear();
+ buf.order(ByteOrder.LITTLE_ENDIAN);
+ intBuffer = buf.asIntBuffer();
+ assertSame(ByteOrder.LITTLE_ENDIAN, intBuffer.order());
+ while (intBuffer.remaining() > 0) {
+ value = (int) intBuffer.remaining();
+ intBuffer.put(value);
+ buf.get(bytes);
+ assertTrue(Arrays.equals(bytes, int2bytes(value, buf.order())));
+ }
+ }
+
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testAsLongBuffer() {
+ LongBuffer longBuffer;
+ byte bytes[] = new byte[8];
+ long value;
+
+ // test BIG_ENDIAN long buffer, read
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ longBuffer = buf.asLongBuffer();
+ assertSame(ByteOrder.BIG_ENDIAN, longBuffer.order());
+ while (longBuffer.remaining() > 0) {
+ buf.get(bytes);
+ value = longBuffer.get();
+ assertEquals(bytes2long(bytes, buf.order()), value);
+ }
+
+ // test LITTLE_ENDIAN long buffer, read
+ buf.clear();
+ buf.order(ByteOrder.LITTLE_ENDIAN);
+ longBuffer = buf.asLongBuffer();
+ assertSame(ByteOrder.LITTLE_ENDIAN, longBuffer.order());
+ while (longBuffer.remaining() > 0) {
+ buf.get(bytes);
+ value = longBuffer.get();
+ assertEquals(bytes2long(bytes, buf.order()), value);
+ }
+
+ if (!buf.isReadOnly()) {
+ // test BIG_ENDIAN long buffer, write
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ longBuffer = buf.asLongBuffer();
+ assertSame(ByteOrder.BIG_ENDIAN, longBuffer.order());
+ while (longBuffer.remaining() > 0) {
+ value = (long) longBuffer.remaining();
+ longBuffer.put(value);
+ buf.get(bytes);
+ assertTrue(Arrays.equals(bytes, long2bytes(value, buf.order())));
+ }
+
+ // test LITTLE_ENDIAN long buffer, write
+ buf.clear();
+ buf.order(ByteOrder.LITTLE_ENDIAN);
+ longBuffer = buf.asLongBuffer();
+ assertSame(ByteOrder.LITTLE_ENDIAN, longBuffer.order());
+ while (longBuffer.remaining() > 0) {
+ value = (long) longBuffer.remaining();
+ longBuffer.put(value);
+ buf.get(bytes);
+ assertTrue(Arrays.equals(bytes, long2bytes(value, buf.order())));
+ }
+ }
+
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testAsShortBuffer() {
+ ShortBuffer shortBuffer;
+ byte bytes[] = new byte[2];
+ short value;
+
+ // test BIG_ENDIAN short buffer, read
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ shortBuffer = buf.asShortBuffer();
+ assertSame(ByteOrder.BIG_ENDIAN, shortBuffer.order());
+ while (shortBuffer.remaining() > 0) {
+ buf.get(bytes);
+ value = shortBuffer.get();
+ assertEquals(bytes2short(bytes, buf.order()), value);
+ }
+
+ // test LITTLE_ENDIAN short buffer, read
+ buf.clear();
+ buf.order(ByteOrder.LITTLE_ENDIAN);
+ shortBuffer = buf.asShortBuffer();
+ assertSame(ByteOrder.LITTLE_ENDIAN, shortBuffer.order());
+ while (shortBuffer.remaining() > 0) {
+ buf.get(bytes);
+ value = shortBuffer.get();
+ assertEquals(bytes2short(bytes, buf.order()), value);
+ }
+
+ if (!buf.isReadOnly()) {
+ // test BIG_ENDIAN short buffer, write
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ shortBuffer = buf.asShortBuffer();
+ assertSame(ByteOrder.BIG_ENDIAN, shortBuffer.order());
+ while (shortBuffer.remaining() > 0) {
+ value = (short) shortBuffer.remaining();
+ shortBuffer.put(value);
+ buf.get(bytes);
+ assertTrue(Arrays.equals(bytes, short2bytes(value, buf.order())));
+ }
+
+ // test LITTLE_ENDIAN short buffer, write
+ buf.clear();
+ buf.order(ByteOrder.LITTLE_ENDIAN);
+ shortBuffer = buf.asShortBuffer();
+ assertSame(ByteOrder.LITTLE_ENDIAN, shortBuffer.order());
+ while (shortBuffer.remaining() > 0) {
+ value = (short) shortBuffer.remaining();
+ shortBuffer.put(value);
+ buf.get(bytes);
+ assertTrue(Arrays.equals(bytes, short2bytes(value, buf.order())));
+ }
+ }
+
+ buf.clear();
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testGetChar() {
+ int nbytes = 2;
+ byte bytes[] = new byte[nbytes];
+ char value;
+ buf.clear();
+ for (int i = 0; buf.remaining() >= nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ assertEquals(i * nbytes, buf.position());
+ buf.mark();
+ buf.get(bytes);
+ buf.reset();
+ value = buf.getChar();
+ assertEquals(bytes2char(bytes, buf.order()), value);
+ }
+
+ try {
+ buf.getChar();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testGetCharint() {
+ int nbytes = 2;
+ byte bytes[] = new byte[nbytes];
+ char value;
+ buf.clear();
+ for (int i = 0; i <= buf.limit() - nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ buf.position(i);
+ value = buf.getChar(i);
+ assertEquals(i, buf.position());
+ buf.get(bytes);
+ assertEquals(bytes2char(bytes, buf.order()), value);
+ }
+
+ try {
+ buf.getChar(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.getChar(buf.limit() - nbytes + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testPutChar() {
+ if (buf.isReadOnly()) {
+ try {
+ buf.clear();
+ buf.putChar((char) 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ int nbytes = 2;
+ byte bytes[] = new byte[nbytes];
+ char value = 0;
+ buf.clear();
+ for (int i = 0; buf.remaining() >= nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ value = (char) i;
+ buf.mark();
+ buf.putChar(value);
+ assertEquals((i + 1) * nbytes, buf.position());
+ buf.reset();
+ buf.get(bytes);
+ assertTrue(Arrays.equals(char2bytes(value, buf.order()), bytes));
+ }
+
+ try {
+ buf.putChar(value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testPutCharint() {
+ if (buf.isReadOnly()) {
+ try {
+ buf.putChar(0, (char) 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ int nbytes = 2;
+ byte bytes[] = new byte[nbytes];
+ char value = 0;
+ buf.clear();
+ for (int i = 0; i <= buf.limit() - nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ value = (char) i;
+ buf.position(i);
+ buf.putChar(i, value);
+ assertEquals(i, buf.position());
+ buf.get(bytes);
+ assertTrue(Arrays.equals(char2bytes(value, buf.order()), bytes));
+ }
+
+ try {
+ buf.putChar(-1, value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.putChar(buf.limit() - nbytes + 1, value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+
+ try {
+ ByteBuffer.allocateDirect(16).putChar(Integer.MAX_VALUE, 'h');
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ public void testGetDouble() {
+ int nbytes = 8;
+ byte bytes[] = new byte[nbytes];
+ double value;
+ buf.clear();
+ for (int i = 0; buf.remaining() >= nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ assertEquals(i * nbytes, buf.position());
+ buf.mark();
+ buf.get(bytes);
+ buf.reset();
+ value = buf.getDouble();
+ if (!(Double.isNaN(bytes2double(bytes, buf.order())) && Double
+ .isNaN(value))) {
+ assertEquals(bytes2double(bytes, buf.order()), value, 0.00);
+ }
+ }
+
+ try {
+ buf.getDouble();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testGetDoubleint() {
+ int nbytes = 8;
+ byte bytes[] = new byte[nbytes];
+ double value;
+ buf.clear();
+ for (int i = 0; i <= buf.limit() - nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ buf.position(i);
+ value = buf.getDouble(i);
+ assertEquals(i, buf.position());
+ buf.get(bytes);
+ if (!(Double.isNaN(bytes2double(bytes, buf.order())) && Double
+ .isNaN(value))) {
+ assertEquals(bytes2double(bytes, buf.order()), value, 0.00);
+ }
+ }
+
+ try {
+ buf.getDouble(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.getDouble(buf.limit() - nbytes + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+
+ try {
+ ByteBuffer.allocateDirect(16).getDouble(Integer.MAX_VALUE);
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ public void testPutDouble() {
+ if (buf.isReadOnly()) {
+ try {
+ buf.clear();
+ buf.putDouble((double) 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ int nbytes = 8;
+ byte bytes[] = new byte[nbytes];
+ double value = 0;
+ buf.clear();
+ for (int i = 0; buf.remaining() >= nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ value = (double) i;
+ buf.mark();
+ buf.putDouble(value);
+ assertEquals((i + 1) * nbytes, buf.position());
+ buf.reset();
+ buf.get(bytes);
+ assertTrue(Arrays.equals(double2bytes(value, buf.order()), bytes));
+ }
+
+ try {
+ buf.putDouble(value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testPutDoubleint() {
+ if (buf.isReadOnly()) {
+ try {
+ buf.putDouble(0, (double) 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ int nbytes = 8;
+ byte bytes[] = new byte[nbytes];
+ double value = 0;
+ buf.clear();
+ for (int i = 0; i <= buf.limit() - nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ value = (double) i;
+ buf.position(i);
+ buf.putDouble(i, value);
+ assertEquals(i, buf.position());
+ buf.get(bytes);
+ assertTrue(Arrays.equals(double2bytes(value, buf.order()), bytes));
+ }
+
+ try {
+ buf.putDouble(-1, value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.putDouble(buf.limit() - nbytes + 1, value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testGetFloat() {
+ int nbytes = 4;
+ byte bytes[] = new byte[nbytes];
+ float value;
+ buf.clear();
+ for (int i = 0; buf.remaining() >= nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ assertEquals(i * nbytes, buf.position());
+ buf.mark();
+ buf.get(bytes);
+ buf.reset();
+ value = buf.getFloat();
+ if (!(Float.isNaN(bytes2float(bytes, buf.order())) && Float
+ .isNaN(value))) {
+ assertEquals(bytes2float(bytes, buf.order()), value, 0.00);
+ }
+ }
+
+ try {
+ buf.getFloat();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testGetFloatint() {
+ int nbytes = 4;
+ byte bytes[] = new byte[nbytes];
+ float value;
+ buf.clear();
+ for (int i = 0; i <= buf.limit() - nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ buf.position(i);
+ value = buf.getFloat(i);
+ assertEquals(i, buf.position());
+ buf.get(bytes);
+ if (!(Float.isNaN(bytes2float(bytes, buf.order())) && Float
+ .isNaN(value))) {
+ assertEquals(bytes2float(bytes, buf.order()), value, 0.00);
+ }
+ }
+
+ try {
+ buf.getFloat(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.getFloat(buf.limit() - nbytes + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testPutFloat() {
+ if (buf.isReadOnly()) {
+ try {
+ buf.clear();
+ buf.putFloat((float) 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ int nbytes = 4;
+ byte bytes[] = new byte[nbytes];
+ float value = 0;
+ buf.clear();
+ for (int i = 0; buf.remaining() >= nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ value = (float) i;
+ buf.mark();
+ buf.putFloat(value);
+ assertEquals((i + 1) * nbytes, buf.position());
+ buf.reset();
+ buf.get(bytes);
+ assertTrue(Arrays.equals(float2bytes(value, buf.order()), bytes));
+ }
+
+ try {
+ buf.putFloat(value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testPutFloatint() {
+ if (buf.isReadOnly()) {
+ try {
+ buf.putFloat(0, (float) 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ int nbytes = 4;
+ byte bytes[] = new byte[nbytes];
+ float value = 0;
+ buf.clear();
+ for (int i = 0; i <= buf.limit() - nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ value = (float) i;
+ buf.position(i);
+ buf.putFloat(i, value);
+ assertEquals(i, buf.position());
+ buf.get(bytes);
+ assertTrue(Arrays.equals(float2bytes(value, buf.order()), bytes));
+ }
+
+ try {
+ buf.putFloat(-1, value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.putFloat(buf.limit() - nbytes + 1, value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testGetInt() {
+ int nbytes = 4;
+ byte bytes[] = new byte[nbytes];
+ int value;
+ buf.clear();
+ for (int i = 0; buf.remaining() >= nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ assertEquals(i * nbytes, buf.position());
+ buf.mark();
+ buf.get(bytes);
+ buf.reset();
+ value = buf.getInt();
+ assertEquals(bytes2int(bytes, buf.order()), value);
+ }
+
+ try {
+ buf.getInt();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testGetIntint() {
+ int nbytes = 4;
+ byte bytes[] = new byte[nbytes];
+ int value;
+ buf.clear();
+ for (int i = 0; i <= buf.limit() - nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ buf.position(i);
+ value = buf.getInt(i);
+ assertEquals(i, buf.position());
+ buf.get(bytes);
+ assertEquals(bytes2int(bytes, buf.order()), value);
+ }
+
+ try {
+ buf.getInt(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.getInt(buf.limit() - nbytes + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ try {
+ ByteBuffer.allocateDirect(16).getInt(Integer.MAX_VALUE);
+ } catch (IndexOutOfBoundsException e) {
+ //expected
+ }
+ }
+
+ public void testPutInt() {
+ if (buf.isReadOnly()) {
+ try {
+ buf.clear();
+ buf.putInt((int) 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ int nbytes = 4;
+ byte bytes[] = new byte[nbytes];
+ int value = 0;
+ buf.clear();
+ for (int i = 0; buf.remaining() >= nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ value = (int) i;
+ buf.mark();
+ buf.putInt(value);
+ assertEquals((i + 1) * nbytes, buf.position());
+ buf.reset();
+ buf.get(bytes);
+ assertTrue(Arrays.equals(int2bytes(value, buf.order()), bytes));
+ }
+
+ try {
+ buf.putInt(value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testPutIntint() {
+ if (buf.isReadOnly()) {
+ try {
+ buf.putInt(0, (int) 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ int nbytes = 4;
+ byte bytes[] = new byte[nbytes];
+ int value = 0;
+ buf.clear();
+ for (int i = 0; i <= buf.limit() - nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ value = (int) i;
+ buf.position(i);
+ buf.putInt(i, value);
+ assertEquals(i, buf.position());
+ buf.get(bytes);
+ assertTrue(Arrays.equals(int2bytes(value, buf.order()), bytes));
+ }
+
+ try {
+ buf.putInt(-1, value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.putInt(buf.limit() - nbytes + 1, value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testGetLong() {
+ int nbytes = 8;
+ byte bytes[] = new byte[nbytes];
+ long value;
+ buf.clear();
+ for (int i = 0; buf.remaining() >= nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ assertEquals(i * nbytes, buf.position());
+ buf.mark();
+ buf.get(bytes);
+ buf.reset();
+ value = buf.getLong();
+ assertEquals(bytes2long(bytes, buf.order()), value);
+ }
+
+ try {
+ buf.getLong();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testGetLongint() {
+ int nbytes = 8;
+ byte bytes[] = new byte[nbytes];
+ long value;
+ buf.clear();
+ for (int i = 0; i <= buf.limit() - nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ buf.position(i);
+ value = buf.getLong(i);
+ assertEquals(i, buf.position());
+ buf.get(bytes);
+ assertEquals(bytes2long(bytes, buf.order()), value);
+ }
+
+ try {
+ buf.getLong(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.getLong(buf.limit() - nbytes + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testPutLong() {
+ if (buf.isReadOnly()) {
+ try {
+ buf.clear();
+ buf.putLong((long) 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ int nbytes = 8;
+ byte bytes[] = new byte[nbytes];
+ long value = 0;
+ buf.clear();
+ for (int i = 0; buf.remaining() >= nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ value = (long) i;
+ buf.mark();
+ buf.putLong(value);
+ assertEquals((i + 1) * nbytes, buf.position());
+ buf.reset();
+ buf.get(bytes);
+ assertTrue(Arrays.equals(long2bytes(value, buf.order()), bytes));
+ }
+
+ try {
+ buf.putLong(value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testPutLongint() {
+ if (buf.isReadOnly()) {
+ try {
+ buf.putLong(0, (long) 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ int nbytes = 8;
+ byte bytes[] = new byte[nbytes];
+ long value = 0;
+ buf.clear();
+ for (int i = 0; i <= buf.limit() - nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ value = (long) i;
+ buf.position(i);
+ buf.putLong(i, value);
+ assertEquals(i, buf.position());
+ buf.get(bytes);
+ assertTrue(Arrays.equals(long2bytes(value, buf.order()), bytes));
+ }
+
+ try {
+ buf.putLong(-1, value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.putLong(buf.limit() - nbytes + 1, value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testGetShort() {
+ int nbytes = 2;
+ byte bytes[] = new byte[nbytes];
+ short value;
+ buf.clear();
+ for (int i = 0; buf.remaining() >= nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ assertEquals(i * nbytes, buf.position());
+ buf.mark();
+ buf.get(bytes);
+ buf.reset();
+ value = buf.getShort();
+ assertEquals(bytes2short(bytes, buf.order()), value);
+ }
+
+ try {
+ buf.getShort();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testGetShortint() {
+ int nbytes = 2;
+ byte bytes[] = new byte[nbytes];
+ short value;
+ buf.clear();
+ for (int i = 0; i <= buf.limit() - nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ buf.position(i);
+ value = buf.getShort(i);
+ assertEquals(i, buf.position());
+ buf.get(bytes);
+ assertEquals(bytes2short(bytes, buf.order()), value);
+ }
+
+ try {
+ buf.getShort(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.getShort(buf.limit() - nbytes + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testPutShort() {
+ if (buf.isReadOnly()) {
+ try {
+ buf.clear();
+ buf.putShort((short) 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ int nbytes = 2;
+ byte bytes[] = new byte[nbytes];
+ short value = 0;
+ buf.clear();
+ for (int i = 0; buf.remaining() >= nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ value = (short) i;
+ buf.mark();
+ buf.putShort(value);
+ assertEquals((i + 1) * nbytes, buf.position());
+ buf.reset();
+ buf.get(bytes);
+ assertTrue(Arrays.equals(short2bytes(value, buf.order()), bytes));
+ }
+
+ try {
+ buf.putShort(value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ public void testPutShortint() {
+ if (buf.isReadOnly()) {
+ try {
+ buf.putShort(0, (short) 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ return;
+ }
+
+ int nbytes = 2;
+ byte bytes[] = new byte[nbytes];
+ short value = 0;
+ buf.clear();
+ for (int i = 0; i <= buf.limit() - nbytes; i++) {
+ buf.order(i % 2 == 0 ? ByteOrder.BIG_ENDIAN
+ : ByteOrder.LITTLE_ENDIAN);
+ value = (short) i;
+ buf.position(i);
+ buf.putShort(i, value);
+ assertEquals(i, buf.position());
+ buf.get(bytes);
+ assertTrue(Arrays.equals(short2bytes(value, buf.order()), bytes));
+ }
+
+ try {
+ buf.putShort(-1, value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.putShort(buf.limit() - nbytes + 1, value);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ buf.order(ByteOrder.BIG_ENDIAN);
+ }
+
+ /**
+ * @tests java.nio.ByteBuffer.wrap(byte[],int,int)
+ */
+ public void testWrappedByteBuffer_null_array() {
+ // Regression for HARMONY-264
+ byte array[] = null;
+ try {
+ ByteBuffer.wrap(array, -1, 0);
+ fail("Should throw NPE"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ }
+ try {
+ ByteBuffer.wrap(new byte[10], Integer.MAX_VALUE, 2);
+ fail("Should throw IndexOutOfBoundsException"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ }
+ }
+
+ private void loadTestData1(byte array[], int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ array[offset + i] = (byte) i;
+ }
+ }
+
+ private void loadTestData2(byte array[], int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ array[offset + i] = (byte) (length - i);
+ }
+ }
+
+ private void loadTestData1(ByteBuffer buf) {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ buf.put(i, (byte) i);
+ }
+ }
+
+ private void loadTestData2(ByteBuffer buf) {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ buf.put(i, (byte) (buf.capacity() - i));
+ }
+ }
+
+ private void assertContentEquals(ByteBuffer buf, byte array[],
+ int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ assertEquals(buf.get(i), array[offset + i]);
+ }
+ }
+
+ private void assertContentEquals(ByteBuffer buf, ByteBuffer other) {
+ assertEquals(buf.capacity(), other.capacity());
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.get(i), other.get(i));
+ }
+ }
+
+ private void assertContentLikeTestData1(ByteBuffer buf,
+ int startIndex, byte startValue, int length) {
+ byte value = startValue;
+ for (int i = 0; i < length; i++) {
+ assertEquals(buf.get(startIndex + i), value);
+ value = (byte) (value + 1);
+ }
+ }
+
+ private int bytes2int(byte bytes[], ByteOrder order) {
+ int nbytes = 4, bigHead, step;
+ if (order == ByteOrder.BIG_ENDIAN) {
+ bigHead = 0;
+ step = 1;
+ } else {
+ bigHead = nbytes - 1;
+ step = -1;
+ }
+ int result = 0;
+ int p = bigHead;
+ for (int i = 0; i < nbytes; i++) {
+ result = result << 8;
+ result = result | (bytes[p] & 0xff);
+ p += step;
+ }
+ return result;
+ }
+
+ private long bytes2long(byte bytes[], ByteOrder order) {
+ int nbytes = 8, bigHead, step;
+ if (order == ByteOrder.BIG_ENDIAN) {
+ bigHead = 0;
+ step = 1;
+ } else {
+ bigHead = nbytes - 1;
+ step = -1;
+ }
+ long result = 0;
+ int p = bigHead;
+ for (int i = 0; i < nbytes; i++) {
+ result = result << 8;
+ result = result | (bytes[p] & 0xff);
+ p += step;
+ }
+ return result;
+ }
+
+ private short bytes2short(byte bytes[], ByteOrder order) {
+ int nbytes = 2, bigHead, step;
+ if (order == ByteOrder.BIG_ENDIAN) {
+ bigHead = 0;
+ step = 1;
+ } else {
+ bigHead = nbytes - 1;
+ step = -1;
+ }
+ short result = 0;
+ int p = bigHead;
+ for (int i = 0; i < nbytes; i++) {
+ result = (short) (result << 8);
+ result = (short) (result | (bytes[p] & 0xff));
+ p += step;
+ }
+ return result;
+ }
+
+ private char bytes2char(byte bytes[], ByteOrder order) {
+ return (char) bytes2short(bytes, order);
+ }
+
+ private float bytes2float(byte bytes[], ByteOrder order) {
+ return Float.intBitsToFloat(bytes2int(bytes, order));
+ }
+
+ private double bytes2double(byte bytes[], ByteOrder order) {
+ return Double.longBitsToDouble(bytes2long(bytes, order));
+ }
+
+ private byte[] int2bytes(int value, ByteOrder order) {
+ int nbytes = 4, smallHead, step;
+ if (order == ByteOrder.BIG_ENDIAN) {
+ smallHead = nbytes - 1;
+ step = -1;
+ } else {
+ smallHead = 0;
+ step = 1;
+ }
+ byte bytes[] = new byte[nbytes];
+ int p = smallHead;
+ for (int i = 0; i < nbytes; i++) {
+ bytes[p] = (byte) (value & 0xff);
+ value = value >> 8;
+ p += step;
+ }
+ return bytes;
+ }
+
+ private byte[] long2bytes(long value, ByteOrder order) {
+ int nbytes = 8, smallHead, step;
+ if (order == ByteOrder.BIG_ENDIAN) {
+ smallHead = nbytes - 1;
+ step = -1;
+ } else {
+ smallHead = 0;
+ step = 1;
+ }
+ byte bytes[] = new byte[nbytes];
+ int p = smallHead;
+ for (int i = 0; i < nbytes; i++) {
+ bytes[p] = (byte) (value & 0xff);
+ value = value >> 8;
+ p += step;
+ }
+ return bytes;
+ }
+
+ private byte[] short2bytes(short value, ByteOrder order) {
+ int nbytes = 2, smallHead, step;
+ if (order == ByteOrder.BIG_ENDIAN) {
+ smallHead = nbytes - 1;
+ step = -1;
+ } else {
+ smallHead = 0;
+ step = 1;
+ }
+ byte bytes[] = new byte[nbytes];
+ int p = smallHead;
+ for (int i = 0; i < nbytes; i++) {
+ bytes[p] = (byte) (value & 0xff);
+ value = (short) (value >> 8);
+ p += step;
+ }
+ return bytes;
+ }
+
+ private byte[] char2bytes(char value, ByteOrder order) {
+ return short2bytes((short) value, order);
+ }
+
+ private byte[] float2bytes(float value, ByteOrder order) {
+ return int2bytes(Float.floatToRawIntBits(value), order);
+ }
+
+ private byte[] double2bytes(double value, ByteOrder order) {
+ return long2bytes(Double.doubleToRawLongBits(value), order);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java
new file mode 100644
index 0000000..8f41904
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ByteOrderTest.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.ByteOrder;
+
+import junit.framework.TestCase;
+
+/**
+ * Test java.nio.ByteOrder
+ *
+ */
+public class ByteOrderTest extends TestCase {
+
+ public void testToString() {
+ assertEquals(ByteOrder.BIG_ENDIAN.toString(), "BIG_ENDIAN");
+ assertEquals(ByteOrder.LITTLE_ENDIAN.toString(), "LITTLE_ENDIAN");
+ }
+
+ public void testNativeOrder() {
+ ByteOrder o = ByteOrder.nativeOrder();
+ assertTrue(o == ByteOrder.BIG_ENDIAN || o == ByteOrder.LITTLE_ENDIAN);
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/CharBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/CharBufferTest.java
new file mode 100644
index 0000000..8a7c5f3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/CharBufferTest.java
@@ -0,0 +1,1081 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.io.IOException;
+import java.nio.BufferOverflowException;
+import java.nio.BufferUnderflowException;
+import java.nio.ByteOrder;
+import java.nio.CharBuffer;
+import java.nio.InvalidMarkException;
+import java.nio.ReadOnlyBufferException;
+
+/**
+ * Tests java.nio.CharBuffer
+ *
+ */
+public class CharBufferTest extends AbstractBufferTest {
+ protected static final int SMALL_TEST_LENGTH = 5;
+
+ protected static final int BUFFER_LENGTH = 20;
+
+ protected CharBuffer buf;
+
+ private static char[] chars = "123456789a".toCharArray();
+
+ protected void setUp() throws Exception{
+ char[] charscopy = new char[chars.length];
+ System.arraycopy(chars, 0, charscopy, 0, chars.length);
+ buf = CharBuffer.wrap(charscopy);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception{
+ buf = null;
+ baseBuf = null;
+ }
+
+ public void testArray() {
+ char array[] = buf.array();
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+ }
+
+ public void testArrayOffset() {
+ char array[] = buf.array();
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+ }
+
+ public void testAsReadOnlyBuffer() {
+ buf.clear();
+ buf.mark();
+ buf.position(buf.limit());
+
+ // readonly's contents should be the same as buf
+ CharBuffer readonly = buf.asReadOnlyBuffer();
+ assertNotSame(buf, readonly);
+ assertTrue(readonly.isReadOnly());
+ assertEquals(buf.position(), readonly.position());
+ assertEquals(buf.limit(), readonly.limit());
+ assertEquals(buf.isDirect(), readonly.isDirect());
+ assertEquals(buf.order(), readonly.order());
+ assertEquals(buf.capacity(), readonly.capacity());
+ assertContentEquals(buf, readonly);
+
+ // readonly's position, mark, and limit should be independent to buf
+ readonly.reset();
+ assertEquals(readonly.position(), 0);
+ readonly.clear();
+ assertEquals(buf.position(), buf.limit());
+ buf.reset();
+ assertEquals(buf.position(), 0);
+
+ buf.clear();
+ int originalPosition = (buf.position() + buf.limit()) / 2;
+ buf.position(originalPosition);
+ buf.mark();
+ buf.position(buf.limit());
+
+ // readonly's contents should be the same as buf
+ readonly = buf.asReadOnlyBuffer();
+ assertNotSame(buf, readonly);
+ assertTrue(readonly.isReadOnly());
+ assertEquals(buf.position(), readonly.position());
+ assertEquals(buf.limit(), readonly.limit());
+ assertEquals(buf.isDirect(), readonly.isDirect());
+ assertEquals(buf.order(), readonly.order());
+ assertEquals(buf.capacity(), readonly.capacity());
+ assertContentEquals(buf, readonly);
+
+ // readonly's position, mark, and limit should be independent to buf
+ readonly.reset();
+ assertEquals(readonly.position(), originalPosition);
+ readonly.clear();
+ assertEquals(buf.position(), buf.limit());
+ buf.reset();
+ assertEquals(buf.position(), originalPosition);
+ }
+
+ public void testCompact() {
+ // case: buffer is full
+ buf.clear();
+ buf.mark();
+ loadTestData1(buf);
+ CharBuffer ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), buf.capacity());
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, (char) 0, buf.capacity());
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // case: buffer is empty
+ buf.position(0);
+ buf.limit(0);
+ buf.mark();
+ ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), 0);
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, (char) 0, buf.capacity());
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // case: normal
+ assertTrue(buf.capacity() > 5);
+ buf.position(1);
+ buf.limit(5);
+ buf.mark();
+ ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), 4);
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, (char) 1, 4);
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+ }
+
+ public void testCompareTo() {
+ // compare to self
+ assertEquals(0, buf.compareTo(buf));
+
+ assertTrue(buf.capacity() > SMALL_TEST_LENGTH);
+ buf.clear();
+ CharBuffer other = CharBuffer.allocate(buf.capacity());
+ other.put(buf);
+ other.clear();
+ buf.clear();
+ assertEquals(0, buf.compareTo(other));
+ assertEquals(0, other.compareTo(buf));
+ buf.position(1);
+ assertTrue(buf.compareTo(other) > 0);
+ assertTrue(other.compareTo(buf) < 0);
+ other.position(2);
+ assertTrue(buf.compareTo(other) < 0);
+ assertTrue(other.compareTo(buf) > 0);
+ buf.position(2);
+ assertTrue(buf.compareTo(other) == 0);
+ assertTrue(other.compareTo(buf) == 0);
+ other.limit(SMALL_TEST_LENGTH);
+ assertTrue(buf.compareTo(other) > 0);
+ assertTrue(other.compareTo(buf) < 0);
+ }
+
+ public void testDuplicate() {
+ // mark the position 0
+ buf.clear();
+ buf.mark();
+ buf.position(buf.limit());
+
+ // duplicate's contents should be the same as buf
+ CharBuffer duplicate = buf.duplicate();
+ assertNotSame(buf, duplicate);
+ assertEquals(buf.position(), duplicate.position());
+ assertEquals(buf.limit(), duplicate.limit());
+ assertEquals(buf.isReadOnly(), duplicate.isReadOnly());
+ assertEquals(buf.isDirect(), duplicate.isDirect());
+ assertEquals(buf.order(), duplicate.order());
+ assertEquals(buf.capacity(), duplicate.capacity());
+ assertContentEquals(buf, duplicate);
+
+ // duplicate's position, mark, and limit should be independent to
+ // buf
+ duplicate.reset();
+ assertEquals(duplicate.position(), 0);
+ duplicate.clear();
+ assertEquals(buf.position(), buf.limit());
+ buf.reset();
+ assertEquals(buf.position(), 0);
+
+ // mark another position
+ buf.clear();
+ int originalPosition = (buf.position() + buf.limit()) / 2;
+ buf.position(originalPosition);
+ buf.mark();
+ buf.position(buf.limit());
+
+ // duplicate's contents should be the same as buf
+ duplicate = buf.duplicate();
+ assertNotSame(buf, duplicate);
+ assertEquals(buf.position(), duplicate.position());
+ assertEquals(buf.limit(), duplicate.limit());
+ assertEquals(buf.isReadOnly(), duplicate.isReadOnly());
+ assertEquals(buf.isDirect(), duplicate.isDirect());
+ assertEquals(buf.order(), duplicate.order());
+ assertEquals(buf.capacity(), duplicate.capacity());
+ assertContentEquals(buf, duplicate);
+
+ // duplicate's position, mark, and limit should be independent to
+ // buf
+ duplicate.reset();
+ assertEquals(duplicate.position(), originalPosition);
+ duplicate.clear();
+ assertEquals(buf.position(), buf.limit());
+ buf.reset();
+ assertEquals(buf.position(), originalPosition);
+
+ // duplicate share the same content with buf
+ if (!duplicate.isReadOnly()) {
+ loadTestData1(buf);
+ assertContentEquals(buf, duplicate);
+ loadTestData2(duplicate);
+ assertContentEquals(buf, duplicate);
+ }
+ }
+
+ public void testEquals() {
+ // equal to self
+ assertTrue(buf.equals(buf));
+ CharBuffer readonly = buf.asReadOnlyBuffer();
+ assertTrue(buf.equals(readonly));
+ CharBuffer duplicate = buf.duplicate();
+ assertTrue(buf.equals(duplicate));
+
+ // always false, if type mismatch
+ assertFalse(buf.equals(Boolean.TRUE));
+
+ assertTrue(buf.capacity() > 5);
+
+ buf.limit(buf.capacity()).position(0);
+ readonly.limit(readonly.capacity()).position(1);
+ assertFalse(buf.equals(readonly));
+
+ buf.limit(buf.capacity() - 1).position(0);
+ duplicate.limit(duplicate.capacity()).position(0);
+ assertFalse(buf.equals(duplicate));
+ }
+
+ /*
+ * Class under test for char get()
+ */
+ public void testGet() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ assertEquals(buf.get(), buf.get(i));
+ }
+ try {
+ buf.get();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.CharBuffer get(char[])
+ */
+ public void testGetcharArray() {
+ char array[] = new char[1];
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ CharBuffer ret = buf.get(array);
+ assertEquals(array[0], buf.get(i));
+ assertSame(ret, buf);
+ }
+ try {
+ buf.get(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.CharBuffer get(char[], int, int)
+ */
+ public void testGetcharArrayintint() {
+ buf.clear();
+ char array[] = new char[buf.capacity()];
+
+ try {
+ buf.get(new char[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.get(array, -1, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ buf.get(array, array.length, 0);
+ try {
+ buf.get(array, array.length + 1, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.get(array, 2, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get((char[])null, 2, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ buf.get(array, 2, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ buf.get(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+
+ buf.clear();
+ CharBuffer ret = buf.get(array, 0, array.length);
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(buf, array, 0, array.length);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for char get(int)
+ */
+ public void testGetint() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ assertEquals(buf.get(), buf.get(i));
+ }
+ try {
+ buf.get(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get(buf.limit());
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void testHashCode() {
+ buf.clear();
+ loadTestData1(buf);
+ CharBuffer readonly = buf.asReadOnlyBuffer();
+ CharBuffer duplicate = buf.duplicate();
+ assertTrue(buf.hashCode() == readonly.hashCode());
+ assertTrue(buf.capacity() > SMALL_TEST_LENGTH);
+ duplicate.position(buf.capacity() / 2);
+ assertTrue(buf.hashCode() != duplicate.hashCode());
+ }
+
+ /*
+ * Class under test for java.nio.CharBuffer put(char)
+ */
+ public void testPutchar() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ CharBuffer ret = buf.put((char) i);
+ assertEquals(buf.get(i), (char) i);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put((char) 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.CharBuffer put(char[])
+ */
+ public void testPutcharArray() {
+ char array[] = new char[1];
+
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ array[0] = (char) i;
+ CharBuffer ret = buf.put(array);
+ assertEquals(buf.get(i), (char) i);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ try {
+ buf.put((char[]) null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.CharBuffer put(char[], int, int)
+ */
+ public void testPutcharArrayintint() {
+ buf.clear();
+ char array[] = new char[buf.capacity()];
+ try {
+ buf.put((char[]) null, 0, 1);
+ fail("Should throw NullPointerException"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ buf.put(new char[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.put(array, -1, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, array.length + 1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ buf.put(array, array.length, 0);
+ assertEquals(buf.position(), 0);
+ try {
+ buf.put(array, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put((char[])null, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ buf.put(array, 2, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ assertEquals(buf.position(), 0);
+
+ loadTestData2(array, 0, array.length);
+ CharBuffer ret = buf.put(array, 0, array.length);
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(buf, array, 0, array.length);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for java.nio.CharBuffer put(java.nio.CharBuffer)
+ */
+ public void testPutCharBuffer() {
+ CharBuffer other = CharBuffer.allocate(buf.capacity());
+
+ try {
+ buf.put((CharBuffer) null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ buf.put(buf);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ buf.put(CharBuffer.allocate(buf.capacity() + 1));
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ try {
+ buf.flip();
+ buf.put((CharBuffer)null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ loadTestData2(other);
+ other.clear();
+ buf.clear();
+ CharBuffer ret = buf.put(other);
+ assertEquals(other.position(), other.capacity());
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(other, buf);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for java.nio.CharBuffer put(int, char)
+ */
+ public void testPutintchar() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), 0);
+ CharBuffer ret = buf.put(i, (char) i);
+ assertEquals(buf.get(i), (char) i);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(-1, (char) 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(buf.limit(), (char) 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void testSlice() {
+ assertTrue(buf.capacity() > 5);
+ buf.position(1);
+ buf.limit(buf.capacity() - 1);
+
+ CharBuffer slice = buf.slice();
+ assertEquals(buf.isReadOnly(), slice.isReadOnly());
+ assertEquals(buf.isDirect(), slice.isDirect());
+ assertEquals(buf.order(), slice.order());
+ assertEquals(slice.position(), 0);
+ assertEquals(slice.limit(), buf.remaining());
+ assertEquals(slice.capacity(), buf.remaining());
+ try {
+ slice.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // slice share the same content with buf
+ if (!slice.isReadOnly()) {
+ loadTestData1(slice);
+ assertContentLikeTestData1(buf, 1, (char) 0, slice.capacity());
+ buf.put(2, (char) 500);
+ assertEquals(slice.get(1), 500);
+ }
+ }
+
+ public void testToString() {
+ String expected = "";
+ for (int i = buf.position(); i < buf.limit(); i++) {
+ expected += buf.get(i);
+ }
+ String str = buf.toString();
+ assertEquals(expected, str);
+ }
+
+ public void testCharAt() {
+ for (int i = 0; i < buf.remaining(); i++) {
+ assertEquals(buf.get(buf.position() + i), buf.charAt(i));
+ }
+ try {
+ buf.charAt(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.charAt(buf.remaining());
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void testLength() {
+ assertEquals(buf.length(), buf.remaining());
+ }
+
+ public void testSubSequence() {
+ try {
+ buf.subSequence(-1, buf.length());
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.subSequence(buf.length() + 1, buf.length() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ assertEquals(buf.subSequence(buf.length(), buf.length()).length(), 0);
+ try {
+ buf.subSequence(1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.subSequence(1, buf.length() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ assertEquals(buf.subSequence(0, buf.length()).toString(), buf
+ .toString());
+
+ if (buf.length() >= 2) {
+ assertEquals(buf.subSequence(1, buf.length() - 1).toString(), buf
+ .toString().substring(1, buf.length() - 1));
+ }
+ }
+
+ public void testPutString() {
+ String str = " ";
+
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ str = "" + (char) i;
+ CharBuffer ret = buf.put(str);
+ assertEquals(buf.get(i), (char) i);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(str);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ try {
+ buf.put((String) null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ public void testPutStringintint() {
+ buf.clear();
+ String str = String.valueOf(new char[buf.capacity()]);
+
+ // Throw a BufferOverflowException and no character is transfered to
+ // CharBuffer
+ try {
+ buf.put(String.valueOf(new char[buf.capacity() + 1]), 0, buf
+ .capacity() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ try {
+ buf.put((String) null, 0, buf.capacity() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ assertEquals(0, buf.position());
+
+ buf.clear();
+ try {
+ buf.put(str, -1, str.length());
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(str, str.length() + 1, str.length() + 2);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put((String) null, -1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ buf.put(str, str.length(), str.length());
+ assertEquals(buf.position(), 0);
+ try {
+ buf.put(str, 2, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(str, 2, str.length() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+
+ char array[] = new char[buf.capacity()];
+ loadTestData2(array, 0, array.length);
+ str = String.valueOf(array);
+
+ CharBuffer ret = buf.put(str, 0, str.length());
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(buf, str.toCharArray(), 0, str.length());
+ assertSame(ret, buf);
+ }
+
+ void loadTestData1(char array[], int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ array[offset + i] = (char) i;
+ }
+ }
+
+ void loadTestData2(char array[], int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ array[offset + i] = (char) (length - i);
+ }
+ }
+
+ void loadTestData1(CharBuffer buf) {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ buf.put(i, (char) i);
+ }
+ }
+
+ void loadTestData2(CharBuffer buf) {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ buf.put(i, (char) (buf.capacity() - i));
+ }
+ }
+
+ private void assertContentEquals(CharBuffer buf, char array[], int offset,
+ int length) {
+ for (int i = 0; i < length; i++) {
+ assertEquals(buf.get(i), array[offset + i]);
+ }
+ }
+
+ private void assertContentEquals(CharBuffer buf, CharBuffer other) {
+ assertEquals(buf.capacity(), other.capacity());
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.get(i), other.get(i));
+ }
+ }
+
+ private void assertContentLikeTestData1(CharBuffer buf, int startIndex,
+ char startValue, int length) {
+ char value = startValue;
+ for (int i = 0; i < length; i++) {
+ assertEquals(buf.get(startIndex + i), value);
+ value = (char) (value + 1);
+ }
+ }
+
+ public void testAppendSelf() throws Exception {
+ CharBuffer cb = CharBuffer.allocate(10);
+ CharBuffer cb2 = cb.duplicate();
+ cb.append(cb);
+ assertEquals(10, cb.position());
+ cb.clear();
+ assertEquals(cb2, cb);
+
+ cb.put("abc");
+ cb2 = cb.duplicate();
+ cb.append(cb);
+ assertEquals(10, cb.position());
+ cb.clear();
+ cb2.clear();
+ assertEquals(cb2, cb);
+
+ cb.put("edfg");
+ cb.clear();
+ cb2 = cb.duplicate();
+ cb.append(cb);
+ assertEquals(10, cb.position());
+ cb.clear();
+ cb2.clear();
+ assertEquals(cb, cb2);
+ }
+
+ public void testAppendOverFlow() throws IOException {
+ CharBuffer cb = CharBuffer.allocate(1);
+ CharSequence cs = "String";
+ cb.put('A');
+ try {
+ cb.append('C');
+ fail("should throw BufferOverflowException.");
+ } catch (BufferOverflowException ex) {
+ // expected;
+ }
+ try {
+ cb.append(cs);
+ fail("should throw BufferOverflowException.");
+ } catch (BufferOverflowException ex) {
+ // expected;
+ }
+ try {
+ cb.append(cs, 1, 2);
+ fail("should throw BufferOverflowException.");
+ } catch (BufferOverflowException ex) {
+ // expected;
+ }
+ }
+
+ public void testReadOnlyMap() throws IOException {
+ CharBuffer cb = CharBuffer.wrap("ABCDE").asReadOnlyBuffer();
+ CharSequence cs = "String";
+ try {
+ cb.append('A');
+ fail("should throw ReadOnlyBufferException.");
+ } catch (ReadOnlyBufferException ex) {
+ // expected;
+ }
+ try {
+ cb.append(cs);
+ fail("should throw ReadOnlyBufferException.");
+ } catch (ReadOnlyBufferException ex) {
+ // expected;
+ }
+ try {
+ cb.append(cs, 1, 2);
+ fail("should throw ReadOnlyBufferException.");
+ } catch (ReadOnlyBufferException ex) {
+ // expected;
+ }
+ cb.append(cs, 1, 1);
+ }
+
+ public void testAppendCNormal() throws IOException {
+ CharBuffer cb = CharBuffer.allocate(2);
+ cb.put('A');
+ assertSame(cb, cb.append('B'));
+ assertEquals('B', cb.get(1));
+ }
+
+ public void testAppendCharSequenceNormal() throws IOException {
+ CharBuffer cb = CharBuffer.allocate(10);
+ cb.put('A');
+ assertSame(cb, cb.append("String"));
+ assertEquals("AString", cb.flip().toString());
+ cb.append(null);
+ assertEquals("null", cb.flip().toString());
+ }
+
+ public void testAppendCharSequenceIINormal() throws IOException {
+ CharBuffer cb = CharBuffer.allocate(10);
+ cb.put('A');
+ assertSame(cb, cb.append("String", 1, 3));
+ assertEquals("Atr", cb.flip().toString());
+
+ cb.append(null, 0, 1);
+ assertEquals("n", cb.flip().toString());
+ }
+
+ public void testAppendCharSequenceII_IllegalArgument() throws IOException {
+ CharBuffer cb = CharBuffer.allocate(10);
+ cb.append("String", 0, 0);
+ cb.append("String", 2, 2);
+ try {
+ cb.append("String", -1, 1);
+ fail("should throw IndexOutOfBoundsException.");
+ } catch (IndexOutOfBoundsException ex) {
+ // expected;
+ }
+ try {
+ cb.append("String", -1, -1);
+ fail("should throw IndexOutOfBoundsException.");
+ } catch (IndexOutOfBoundsException ex) {
+ // expected;
+ }
+ try {
+ cb.append("String", 3, 2);
+ fail("should throw IndexOutOfBoundsException.");
+ } catch (IndexOutOfBoundsException ex) {
+ // expected;
+ }
+ try {
+ cb.append("String", 3, 0);
+ fail("should throw IndexOutOfBoundsException.");
+ } catch (IndexOutOfBoundsException ex) {
+ // expected;
+ }
+ try {
+ cb.append("String", 3, 110);
+ fail("should throw IndexOutOfBoundsException.");
+ } catch (IndexOutOfBoundsException ex) {
+ // expected;
+ }
+ }
+
+ public void testReadCharBuffer() throws IOException {
+ CharBuffer source = CharBuffer.wrap("String");
+ CharBuffer target = CharBuffer.allocate(10);
+ assertEquals(6, source.read(target));
+ assertEquals("String", target.flip().toString());
+ // return -1 when nothing to read
+ assertEquals(-1, source.read(target));
+ // NullPointerException
+ try {
+ assertEquals(-1, source.read(null));
+ fail("should throw NullPointerException.");
+ } catch (NullPointerException ex) {
+ // expected;
+ }
+
+ }
+
+ public void testReadReadOnly() throws IOException {
+ CharBuffer source = CharBuffer.wrap("String");
+ CharBuffer target = CharBuffer.allocate(10).asReadOnlyBuffer();
+ try {
+ source.read(target);
+ fail("should throw ReadOnlyBufferException.");
+ } catch (ReadOnlyBufferException ex) {
+ // expected;
+ }
+ // if target has no remaining, needn't to check the isReadOnly
+ target.flip();
+ assertEquals(0, source.read(target));
+ }
+
+ public void testReadOverflow() throws IOException {
+ CharBuffer source = CharBuffer.wrap("String");
+ CharBuffer target = CharBuffer.allocate(1);
+ assertEquals(1, source.read(target));
+ assertEquals("S", target.flip().toString());
+ assertEquals(1, source.position());
+ }
+
+ public void testReadSelf() throws Exception {
+ CharBuffer source = CharBuffer.wrap("abuffer");
+ try {
+ source.read(source);
+ fail("should throw IAE.");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+ }
+
+ public void testRead_scenario1() throws Exception {
+ char[] charArray = new char[] { 'a', 'b' };
+ CharBuffer charBuffer = CharBuffer.wrap(charArray);
+ try {
+ charBuffer.read(charBuffer);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ charBuffer.put(charArray);
+ assertEquals(-1, charBuffer.read(charBuffer));
+ }
+
+ public void testRead_scenario2() throws Exception {
+ CharBuffer charBufferA = CharBuffer.allocate(0);
+ CharBuffer allocateBuffer = CharBuffer.allocate(1);
+ CharBuffer charBufferB = CharBuffer.wrap(allocateBuffer);
+ assertEquals(-1, charBufferA.read(charBufferB));
+
+ allocateBuffer.append(allocateBuffer);
+ charBufferB = CharBuffer.wrap(allocateBuffer);
+ assertEquals(-1, charBufferA.read(charBufferB));
+ }
+
+ public void testIsDirect() {
+ assertFalse(buf.isDirect());
+ }
+
+ public void testHasArray() {
+ assertTrue(buf.hasArray());
+ }
+
+ public void testOrder() {
+ assertEquals(ByteOrder.nativeOrder(), buf.order());
+ }
+
+ public void testIsReadOnly() {
+ assertFalse(buf.isReadOnly());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectByteBufferTest.java
new file mode 100644
index 0000000..f274676
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectByteBufferTest.java
@@ -0,0 +1,60 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.ByteBuffer;
+
+public class DirectByteBufferTest extends ByteBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = ByteBuffer.allocateDirect(BUFFER_LENGTH);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ buf = null;
+ baseBuf = null;
+ }
+
+ /**
+ * @tests java.nio.ByteBuffer#allocateDirect(int)
+ *
+ */
+ public void testAllocatedByteBuffer_IllegalArg() {
+ try {
+ ByteBuffer.allocateDirect(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ public void testIsDirect() {
+ assertTrue(buf.isDirect());
+ }
+
+ public void testHasArray() {
+ // Android direct byte buffers have backing arrays.
+ assertTrue(buf.hasArray());
+ // assertFalse(buf.hasArray());
+ }
+
+ public void testIsReadOnly() {
+ assertFalse(buf.isReadOnly());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectCharBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectCharBufferTest.java
new file mode 100644
index 0000000..83cfc9d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectCharBufferTest.java
@@ -0,0 +1,61 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+public class DirectCharBufferTest extends CharBufferTest {
+
+ public void setUp(){
+ buf = ByteBuffer.allocateDirect(BUFFER_LENGTH*2).asCharBuffer();
+ super.loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ public void tearDown(){
+ buf = null;
+ baseBuf = null;
+ }
+
+ public void testHasArray() {
+ assertFalse(buf.hasArray());
+ }
+
+ public void testArray() {
+ try {
+ buf.array();
+ fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ }
+ }
+
+ public void testArrayOffset() {
+ try {
+ buf.arrayOffset();
+ fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ }
+ }
+
+ public void testIsDirect() {
+ assertTrue(buf.isDirect());
+ }
+
+ public void testOrder() {
+ assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectDoubleBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectDoubleBufferTest.java
new file mode 100644
index 0000000..561c0fa
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectDoubleBufferTest.java
@@ -0,0 +1,60 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+public class DirectDoubleBufferTest extends DoubleBufferTest {
+ public void setUp(){
+ buf = ByteBuffer.allocateDirect(BUFFER_LENGTH*8).asDoubleBuffer();
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ public void tearDown(){
+ buf = null;
+ baseBuf = null;
+ }
+
+ public void testHasArray() {
+ assertFalse(buf.hasArray());
+ }
+
+ public void testArray() {
+ try {
+ buf.array();
+ fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ }
+ }
+
+ public void testArrayOffset() {
+ try {
+ buf.arrayOffset();
+ fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ }
+ }
+
+ public void testIsDirect() {
+ assertTrue(buf.isDirect());
+ }
+
+ public void testOrder() {
+ assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectFloatBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectFloatBufferTest.java
new file mode 100644
index 0000000..8739c1b
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectFloatBufferTest.java
@@ -0,0 +1,61 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+public class DirectFloatBufferTest extends FloatBufferTest {
+ public void setUp(){
+ buf = ByteBuffer.allocateDirect(BUFFER_LENGTH*4).asFloatBuffer();
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ public void tearDown(){
+ buf = null;
+ baseBuf = null;
+ }
+
+ public void testHasArray() {
+ assertFalse(buf.hasArray());
+ }
+
+ public void testArray() {
+ try {
+ buf.array();
+ fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ }
+ }
+
+ public void testArrayOffset() {
+ try {
+ buf.arrayOffset();
+ fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+ }
+
+ public void testIsDirect() {
+ assertTrue(buf.isDirect());
+ }
+
+ public void testOrder() {
+ assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectIntBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectIntBufferTest.java
new file mode 100644
index 0000000..393366e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectIntBufferTest.java
@@ -0,0 +1,61 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+public class DirectIntBufferTest extends IntBufferTest {
+ public void setUp(){
+ buf = ByteBuffer.allocateDirect(BUFFER_LENGTH*4).asIntBuffer();
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ public void tearDown(){
+ buf = null;
+ baseBuf = null;
+ }
+
+ public void testHasArray() {
+ assertFalse(buf.hasArray());
+ }
+
+ public void testArray() {
+ try {
+ buf.array();
+ fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ }
+ }
+
+ public void testArrayOffset() {
+ try {
+ buf.arrayOffset();
+ fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+ }
+
+ public void testIsDirect() {
+ assertTrue(buf.isDirect());
+ }
+
+ public void testOrder() {
+ assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectLongBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectLongBufferTest.java
new file mode 100644
index 0000000..245cd25
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectLongBufferTest.java
@@ -0,0 +1,62 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+
+public class DirectLongBufferTest extends LongBufferTest {
+ public void setUp(){
+ buf = ByteBuffer.allocateDirect(BUFFER_LENGTH*8).asLongBuffer();
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ public void tearDown(){
+ buf = null;
+ baseBuf = null;
+ }
+
+ public void testHasArray() {
+ assertFalse(buf.hasArray());
+ }
+
+ public void testArray() {
+ try {
+ buf.array();
+ fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ }
+ }
+
+ public void testArrayOffset() {
+ try {
+ buf.arrayOffset();
+ fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+ }
+
+ public void testIsDirect() {
+ assertTrue(buf.isDirect());
+ }
+
+ public void testOrder() {
+ assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectShortBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectShortBufferTest.java
new file mode 100644
index 0000000..9ae290a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DirectShortBufferTest.java
@@ -0,0 +1,61 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+
+public class DirectShortBufferTest extends ShortBufferTest {
+ public void setUp(){
+ buf = ByteBuffer.allocateDirect(BUFFER_LENGTH*2).asShortBuffer();
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ public void tearDown(){
+ buf = null;
+ baseBuf = null;
+ }
+
+ public void testHasArray() {
+ assertFalse(buf.hasArray());
+ }
+
+ public void testArray() {
+ try {
+ buf.array();
+ fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ }
+ }
+
+ public void testArrayOffset() {
+ try {
+ buf.arrayOffset();
+ fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+ }
+
+ public void testIsDirect() {
+ assertTrue(buf.isDirect());
+ }
+
+ public void testOrder() {
+ assertEquals(ByteOrder.BIG_ENDIAN, buf.order());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DoubleBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DoubleBufferTest.java
new file mode 100644
index 0000000..40ff2e0
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DoubleBufferTest.java
@@ -0,0 +1,664 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.BufferOverflowException;
+import java.nio.BufferUnderflowException;
+import java.nio.ByteBuffer;
+import java.nio.ByteOrder;
+import java.nio.DoubleBuffer;
+import java.nio.InvalidMarkException;
+
+/**
+ * Tests java.nio.DoubleBuffer
+ */
+public class DoubleBufferTest extends AbstractBufferTest {
+
+ protected static final int SMALL_TEST_LENGTH = 5;
+
+ protected static final int BUFFER_LENGTH = 20;
+
+ protected DoubleBuffer buf;
+
+ protected void setUp() throws Exception {
+ buf = DoubleBuffer.allocate(BUFFER_LENGTH);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ buf = null;
+ baseBuf = null;
+ }
+
+ /*
+ * Test with bit sequences that represent the IEEE754 doubles Positive
+ * infinity, negative infinity, and NaN.
+ */
+ public void testNaNs() {
+ long[] nans = new long[] { 0x7ff0000000000000L, 0xfff0000000000000L,
+ 0x7ff8000000000000L };
+ for (int i = 0; i < nans.length; i++) {
+ long longBitsIn = nans[i];
+ double dbl = Double.longBitsToDouble(longBitsIn);
+ long longBitsOut = Double.doubleToRawLongBits(dbl);
+ // Sanity check
+ assertTrue(longBitsIn == longBitsOut);
+
+ // Store the double and retrieve it
+ ByteBuffer buffer = ByteBuffer.allocate(8);
+ buffer.putDouble(dbl);
+ double bufDoubleOut = buffer.getDouble(0);
+
+ // Check the bits sequence was not normalized
+ long bufLongOut = Double.doubleToRawLongBits(bufDoubleOut);
+ assertTrue(longBitsIn == bufLongOut);
+ }
+ }
+
+ public void testArray() {
+ double array[] = buf.array();
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+ }
+
+ public void testArrayOffset() {
+ double array[] = buf.array();
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+ }
+
+ public void testAsReadOnlyBuffer() {
+ buf.clear();
+ buf.mark();
+ buf.position(buf.limit());
+
+ // readonly's contents should be the same as buf
+ DoubleBuffer readonly = buf.asReadOnlyBuffer();
+ assertNotSame(buf, readonly);
+ assertTrue(readonly.isReadOnly());
+ assertEquals(buf.position(), readonly.position());
+ assertEquals(buf.limit(), readonly.limit());
+ assertEquals(buf.isDirect(), readonly.isDirect());
+ assertEquals(buf.order(), readonly.order());
+ assertContentEquals(buf, readonly);
+
+ // readonly's position, mark, and limit should be independent to buf
+ readonly.reset();
+ assertEquals(readonly.position(), 0);
+ readonly.clear();
+ assertEquals(buf.position(), buf.limit());
+ buf.reset();
+ assertEquals(buf.position(), 0);
+ }
+
+ public void testCompact() {
+ // case: buffer is full
+ buf.clear();
+ buf.mark();
+ loadTestData1(buf);
+ DoubleBuffer ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), buf.capacity());
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, 0.0, buf.capacity());
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // case: buffer is empty
+ buf.position(0);
+ buf.limit(0);
+ buf.mark();
+ ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), 0);
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, 0.0, buf.capacity());
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // case: normal
+ assertTrue(buf.capacity() > 5);
+ buf.position(1);
+ buf.limit(5);
+ buf.mark();
+ ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), 4);
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, 1.0, 4);
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+ }
+
+ public void testCompareTo() {
+ DoubleBuffer other = DoubleBuffer.allocate(buf.capacity());
+ loadTestData1(other);
+ assertEquals(0, buf.compareTo(other));
+ assertEquals(0, other.compareTo(buf));
+ buf.position(1);
+ assertTrue(buf.compareTo(other) > 0);
+ assertTrue(other.compareTo(buf) < 0);
+ other.position(2);
+ assertTrue(buf.compareTo(other) < 0);
+ assertTrue(other.compareTo(buf) > 0);
+ buf.position(2);
+ other.limit(5);
+ assertTrue(buf.compareTo(other) > 0);
+ assertTrue(other.compareTo(buf) < 0);
+
+ DoubleBuffer dbuffer1 = DoubleBuffer.wrap(new double[] { Double.NaN });
+ DoubleBuffer dbuffer2 = DoubleBuffer.wrap(new double[] { Double.NaN });
+ DoubleBuffer dbuffer3 = DoubleBuffer.wrap(new double[] { 42d });
+
+ assertEquals("Failed equal comparison with NaN entry", 0, dbuffer1
+ .compareTo(dbuffer2));
+ assertEquals("Failed greater than comparison with NaN entry", 1, dbuffer3
+ .compareTo(dbuffer1));
+ assertEquals("Failed greater than comparison with NaN entry", 1, dbuffer1
+ .compareTo(dbuffer3));
+ }
+
+ public void testDuplicate() {
+ buf.clear();
+ buf.mark();
+ buf.position(buf.limit());
+
+ // duplicate's contents should be the same as buf
+ DoubleBuffer duplicate = buf.duplicate();
+ assertNotSame(buf, duplicate);
+ assertEquals(buf.position(), duplicate.position());
+ assertEquals(buf.limit(), duplicate.limit());
+ assertEquals(buf.isReadOnly(), duplicate.isReadOnly());
+ assertEquals(buf.isDirect(), duplicate.isDirect());
+ assertEquals(buf.order(), duplicate.order());
+ assertContentEquals(buf, duplicate);
+
+ // duplicate's position, mark, and limit should be independent to buf
+ duplicate.reset();
+ assertEquals(duplicate.position(), 0);
+ duplicate.clear();
+ assertEquals(buf.position(), buf.limit());
+ buf.reset();
+ assertEquals(buf.position(), 0);
+
+ // duplicate share the same content with buf
+ // FIXME
+ if (!duplicate.isReadOnly()) {
+ loadTestData1(buf);
+ assertContentEquals(buf, duplicate);
+ loadTestData2(duplicate);
+ assertContentEquals(buf, duplicate);
+ }
+ }
+
+ public void testEquals() {
+ // equal to self
+ assertTrue(buf.equals(buf));
+ DoubleBuffer readonly = buf.asReadOnlyBuffer();
+ assertTrue(buf.equals(readonly));
+ DoubleBuffer duplicate = buf.duplicate();
+ assertTrue(buf.equals(duplicate));
+
+ // always false, if type mismatch
+ assertFalse(buf.equals(Boolean.TRUE));
+
+ assertTrue(buf.capacity() > 5);
+
+ buf.limit(buf.capacity()).position(0);
+ readonly.limit(readonly.capacity()).position(1);
+ assertFalse(buf.equals(readonly));
+
+ buf.limit(buf.capacity() - 1).position(0);
+ duplicate.limit(duplicate.capacity()).position(0);
+ assertFalse(buf.equals(duplicate));
+ }
+
+ /*
+ * Class under test for double get()
+ */
+ public void testGet() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ assertEquals(buf.get(), buf.get(i), 0.01);
+ }
+ try {
+ buf.get();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.DoubleBuffer get(double[])
+ */
+ public void testGetdoubleArray() {
+ double array[] = new double[1];
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ DoubleBuffer ret = buf.get(array);
+ assertEquals(array[0], buf.get(i), 0.01);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.get(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.DoubleBuffer get(double[], int, int)
+ */
+ public void testGetdoubleArrayintint() {
+ buf.clear();
+ double array[] = new double[buf.capacity()];
+
+ try {
+ buf.get(new double[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.get(array, -1, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ buf.get(array, array.length, 0);
+ try {
+ buf.get(array, array.length + 1, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.get(array, 2, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get((double[])null, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ buf.get(array, 2, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ buf.get(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+
+ buf.clear();
+ DoubleBuffer ret = buf.get(array, 0, array.length);
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(buf, array, 0, array.length);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for double get(int)
+ */
+ public void testGetint() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ assertEquals(buf.get(), buf.get(i), 0.01);
+ }
+ try {
+ buf.get(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get(buf.limit());
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void testHasArray() {
+ assertTrue(buf.hasArray());
+ }
+
+ public void testHashCode() {
+ buf.clear();
+ DoubleBuffer readonly = buf.asReadOnlyBuffer();
+ DoubleBuffer duplicate = buf.duplicate();
+ assertTrue(buf.hashCode() == readonly.hashCode());
+
+ assertTrue(buf.capacity() > 5);
+ duplicate.position(buf.capacity() / 2);
+ assertTrue(buf.hashCode() != duplicate.hashCode());
+ }
+
+ public void testIsDirect() {
+ assertFalse(buf.isDirect());
+ }
+
+ public void testOrder() {
+ assertEquals(ByteOrder.nativeOrder(), buf.order());
+ }
+
+ /*
+ * Class under test for java.nio.DoubleBuffer put(double)
+ */
+ public void testPutdouble() {
+
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ DoubleBuffer ret = buf.put((double) i);
+ assertEquals(buf.get(i), (double) i, 0.0);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.DoubleBuffer put(double[])
+ */
+ public void testPutdoubleArray() {
+ double array[] = new double[1];
+
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ array[0] = (double) i;
+ DoubleBuffer ret = buf.put(array);
+ assertEquals(buf.get(i), (double) i, 0.0);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.DoubleBuffer put(double[], int, int)
+ */
+ public void testPutdoubleArrayintint() {
+ buf.clear();
+ double array[] = new double[buf.capacity()];
+
+ try {
+ buf.put(new double[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.put(array, -1, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, array.length + 1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ buf.put(array, array.length, 0);
+ assertEquals(buf.position(), 0);
+ try {
+ buf.put(array, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put((double[])null, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ buf.put(array, 2, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ assertEquals(buf.position(), 0);
+
+ loadTestData2(array, 0, array.length);
+ DoubleBuffer ret = buf.put(array, 0, array.length);
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(buf, array, 0, array.length);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for java.nio.DoubleBuffer put(java.nio.DoubleBuffer)
+ */
+ public void testPutDoubleBuffer() {
+ DoubleBuffer other = DoubleBuffer.allocate(buf.capacity());
+
+ try {
+ buf.put(buf);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ buf.put(DoubleBuffer.allocate(buf.capacity() + 1));
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+
+ loadTestData2(other);
+ other.clear();
+ buf.clear();
+ DoubleBuffer ret = buf.put(other);
+ assertEquals(other.position(), other.capacity());
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(other, buf);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for java.nio.DoubleBuffer put(int, double)
+ */
+ public void testPutintdouble() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), 0);
+ DoubleBuffer ret = buf.put(i, (double) i);
+ assertEquals(buf.get(i), (double) i, 0.0);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(-1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(buf.limit(), 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void testSlice() {
+ assertTrue(buf.capacity() > 5);
+ buf.position(1);
+ buf.limit(buf.capacity() - 1);
+
+ DoubleBuffer slice = buf.slice();
+ assertEquals(buf.isReadOnly(), slice.isReadOnly());
+ assertEquals(buf.isDirect(), slice.isDirect());
+ assertEquals(buf.order(), slice.order());
+ assertEquals(slice.position(), 0);
+ assertEquals(slice.limit(), buf.remaining());
+ assertEquals(slice.capacity(), buf.remaining());
+ try {
+ slice.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // slice share the same content with buf
+ // FIXME:
+ if (!slice.isReadOnly()) {
+ loadTestData1(slice);
+ assertContentLikeTestData1(buf, 1, 0, slice.capacity());
+ buf.put(2, 500);
+ assertEquals(slice.get(1), 500, 0.0);
+ }
+ }
+
+ public void testToString() {
+ String str = buf.toString();
+ assertTrue(str.indexOf("Double") >= 0 || str.indexOf("double") >= 0);
+ assertTrue(str.indexOf("" + buf.position()) >= 0);
+ assertTrue(str.indexOf("" + buf.limit()) >= 0);
+ assertTrue(str.indexOf("" + buf.capacity()) >= 0);
+ }
+
+ void loadTestData1(double array[], int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ array[offset + i] = (double) i;
+ }
+ }
+
+ void loadTestData2(double array[], int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ array[offset + i] = (double) length - i;
+ }
+ }
+
+ void loadTestData1(DoubleBuffer buf) {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ buf.put(i, (double) i);
+ }
+ }
+
+ void loadTestData2(DoubleBuffer buf) {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ buf.put(i, (double) buf.capacity() - i);
+ }
+ }
+
+ private void assertContentEquals(DoubleBuffer buf, double array[],
+ int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ assertEquals(buf.get(i), array[offset + i], 0.01);
+ }
+ }
+
+ private void assertContentEquals(DoubleBuffer buf, DoubleBuffer other) {
+ assertEquals(buf.capacity(), other.capacity());
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.get(i), other.get(i), 0.01);
+ }
+ }
+
+ private void assertContentLikeTestData1(DoubleBuffer buf, int startIndex,
+ double startValue, int length) {
+ double value = startValue;
+ for (int i = 0; i < length; i++) {
+ assertEquals(buf.get(startIndex + i), value, 0.01);
+ value = value + 1.0;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateDirectByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateDirectByteBufferTest.java
new file mode 100644
index 0000000..656241a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateDirectByteBufferTest.java
@@ -0,0 +1,31 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+
+public class DuplicateDirectByteBufferTest extends DirectByteBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = buf.duplicate();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateHeapByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateHeapByteBufferTest.java
new file mode 100644
index 0000000..9f44d7a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateHeapByteBufferTest.java
@@ -0,0 +1,32 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+
+public class DuplicateHeapByteBufferTest extends HeapByteBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = buf.duplicate();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateWrappedByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateWrappedByteBufferTest.java
new file mode 100644
index 0000000..2796b88
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/DuplicateWrappedByteBufferTest.java
@@ -0,0 +1,32 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+
+public class DuplicateWrappedByteBufferTest extends WrappedByteBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = buf.duplicate();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/FloatBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/FloatBufferTest.java
new file mode 100644
index 0000000..cfef096
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/FloatBufferTest.java
@@ -0,0 +1,674 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.BufferOverflowException;
+import java.nio.BufferUnderflowException;
+import java.nio.ByteOrder;
+import java.nio.DoubleBuffer;
+import java.nio.FloatBuffer;
+import java.nio.InvalidMarkException;
+
+/**
+ * Tests java.nio.FloatBuffer
+ *
+ */
+public class FloatBufferTest extends AbstractBufferTest {
+
+ protected static final int SMALL_TEST_LENGTH = 5;
+
+ protected static final int BUFFER_LENGTH = 20;
+
+ protected FloatBuffer buf;
+
+ protected void setUp() throws Exception {
+ buf = FloatBuffer.allocate(BUFFER_LENGTH);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ buf = null;
+ baseBuf = null;
+ }
+
+ public void testArray() {
+ float array[] = buf.array();
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+ }
+
+ public void testArrayOffset() {
+ float array[] = buf.array();
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+ }
+
+ public void testAsReadOnlyBuffer() {
+ buf.clear();
+ buf.mark();
+ buf.position(buf.limit());
+
+ // readonly's contents should be the same as buf
+ FloatBuffer readonly = buf.asReadOnlyBuffer();
+ assertNotSame(buf, readonly);
+ assertTrue(readonly.isReadOnly());
+ assertEquals(buf.position(), readonly.position());
+ assertEquals(buf.limit(), readonly.limit());
+ assertEquals(buf.isDirect(), readonly.isDirect());
+ assertEquals(buf.order(), readonly.order());
+ assertContentEquals(buf, readonly);
+
+ // readonly's position, mark, and limit should be independent to buf
+ readonly.reset();
+ assertEquals(readonly.position(), 0);
+ readonly.clear();
+ assertEquals(buf.position(), buf.limit());
+ buf.reset();
+ assertEquals(buf.position(), 0);
+ }
+
+ public void testCompact() {
+
+ // case: buffer is full
+ buf.clear();
+ buf.mark();
+ loadTestData1(buf);
+ FloatBuffer ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), buf.capacity());
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, 0.0f, buf.capacity());
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // case: buffer is empty
+ buf.position(0);
+ buf.limit(0);
+ buf.mark();
+ ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), 0);
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, 0.0f, buf.capacity());
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // case: normal
+ assertTrue(buf.capacity() > 5);
+ buf.position(1);
+ buf.limit(5);
+ buf.mark();
+ ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), 4);
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, 1.0f, 4);
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+ }
+
+ public void testCompareTo() {
+ try {
+ buf.compareTo(null);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ // compare to self
+ assertEquals(0, buf.compareTo(buf));
+
+ // normal cases
+ assertTrue(buf.capacity() > 5);
+ buf.clear();
+ FloatBuffer other = FloatBuffer.allocate(buf.capacity());
+ loadTestData1(other);
+ assertEquals(0, buf.compareTo(other));
+ assertEquals(0, other.compareTo(buf));
+ buf.position(1);
+ assertTrue(buf.compareTo(other) > 0);
+ assertTrue(other.compareTo(buf) < 0);
+ other.position(2);
+ assertTrue(buf.compareTo(other) < 0);
+ assertTrue(other.compareTo(buf) > 0);
+ buf.position(2);
+ other.limit(5);
+ assertTrue(buf.compareTo(other) > 0);
+ assertTrue(other.compareTo(buf) < 0);
+
+ FloatBuffer fbuffer1 = FloatBuffer.wrap(new float[] { Float.NaN });
+ FloatBuffer fbuffer2 = FloatBuffer.wrap(new float[] { Float.NaN });
+ FloatBuffer fbuffer3 = FloatBuffer.wrap(new float[] { 42f });
+
+ assertEquals("Failed equal comparison with NaN entry", 0, fbuffer1
+ .compareTo(fbuffer2));
+ assertEquals("Failed greater than comparison with NaN entry", 1, fbuffer3
+ .compareTo(fbuffer1));
+ assertEquals("Failed greater than comparison with NaN entry", 1, fbuffer1
+ .compareTo(fbuffer3));
+
+ }
+
+ public void testDuplicate() {
+ buf.clear();
+ buf.mark();
+ buf.position(buf.limit());
+
+ // duplicate's contents should be the same as buf
+ FloatBuffer duplicate = buf.duplicate();
+ assertNotSame(buf, duplicate);
+ assertEquals(buf.position(), duplicate.position());
+ assertEquals(buf.limit(), duplicate.limit());
+ assertEquals(buf.isReadOnly(), duplicate.isReadOnly());
+ assertEquals(buf.isDirect(), duplicate.isDirect());
+ assertEquals(buf.order(), duplicate.order());
+ assertContentEquals(buf, duplicate);
+
+ // duplicate's position, mark, and limit should be independent to buf
+ duplicate.reset();
+ assertEquals(duplicate.position(), 0);
+ duplicate.clear();
+ assertEquals(buf.position(), buf.limit());
+ buf.reset();
+ assertEquals(buf.position(), 0);
+
+ // duplicate share the same content with buf
+ if (!duplicate.isReadOnly()) {
+ loadTestData1(buf);
+ assertContentEquals(buf, duplicate);
+ loadTestData2(duplicate);
+ assertContentEquals(buf, duplicate);
+ }
+ }
+
+ public void testEquals() {
+ // equal to self
+ assertTrue(buf.equals(buf));
+ FloatBuffer readonly = buf.asReadOnlyBuffer();
+ assertTrue(buf.equals(readonly));
+ FloatBuffer duplicate = buf.duplicate();
+ assertTrue(buf.equals(duplicate));
+
+ // always false, if type mismatch
+ assertFalse(buf.equals(Boolean.TRUE));
+
+ assertTrue(buf.capacity() > 5);
+
+ buf.limit(buf.capacity()).position(0);
+ readonly.limit(readonly.capacity()).position(1);
+ assertFalse(buf.equals(readonly));
+
+ buf.limit(buf.capacity() - 1).position(0);
+ duplicate.limit(duplicate.capacity()).position(0);
+ assertFalse(buf.equals(duplicate));
+ }
+
+ /*
+ * Class under test for float get()
+ */
+ public void testGet() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ assertEquals(buf.get(), buf.get(i), 0.01);
+ }
+ try {
+ buf.get();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.FloatBuffer get(float[])
+ */
+ public void testGetfloatArray() {
+ float array[] = new float[1];
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ FloatBuffer ret = buf.get(array);
+ assertEquals(array[0], buf.get(i), 0.01);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.get(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ try {
+ buf.position(buf.limit());
+ buf.get((float[])null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ buf.get(new float[0]);
+ }
+
+ /*
+ * Class under test for java.nio.FloatBuffer get(float[], int, int)
+ */
+ public void testGetfloatArrayintint() {
+ buf.clear();
+ float array[] = new float[buf.capacity()];
+
+ try {
+ buf.get(new float[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.get(array, -1, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ buf.get(array, array.length, 0);
+ try {
+ buf.get(array, array.length + 1, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.get(array, 2, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get((float[])null, 2, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ buf.get(array, 2, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ buf.get(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+
+ buf.clear();
+ FloatBuffer ret = buf.get(array, 0, array.length);
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(buf, array, 0, array.length);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for float get(int)
+ */
+ public void testGetint() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ assertEquals(buf.get(), buf.get(i), 0.01);
+ }
+ try {
+ buf.get(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get(buf.limit());
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void testHasArray() {
+ assertNotNull(buf.array());
+ }
+
+ public void testHashCode() {
+ buf.clear();
+ FloatBuffer readonly = buf.asReadOnlyBuffer();
+ FloatBuffer duplicate = buf.duplicate();
+ assertTrue(buf.hashCode() == readonly.hashCode());
+
+ assertTrue(buf.capacity() > 5);
+ duplicate.position(buf.capacity() / 2);
+ assertTrue(buf.hashCode() != duplicate.hashCode());
+ }
+
+ public void testIsDirect() {
+ assertFalse(buf.isDirect());
+ }
+
+ public void testOrder() {
+ buf.order();
+ if (buf.hasArray()) {
+ assertEquals(ByteOrder.nativeOrder(), buf.order());
+ }
+ }
+
+ /*
+ * Class under test for java.nio.FloatBuffer put(float)
+ */
+ public void testPutfloat() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ FloatBuffer ret = buf.put((float) i);
+ assertEquals(buf.get(i), (float) i, 0.0);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.FloatBuffer put(float[])
+ */
+ public void testPutfloatArray() {
+ float array[] = new float[1];
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ array[0] = (float) i;
+ FloatBuffer ret = buf.put(array);
+ assertEquals(buf.get(i), (float) i, 0.0);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ try {
+ buf.position(buf.limit());
+ buf.put((float[])null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.FloatBuffer put(float[], int, int)
+ */
+ public void testPutfloatArrayintint() {
+ buf.clear();
+ float array[] = new float[buf.capacity()];
+ try {
+ buf.put(new float[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.put(array, -1, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, array.length + 1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ buf.put(array, array.length, 0);
+ assertEquals(buf.position(), 0);
+ try {
+ buf.put(array, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put((float[])null, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ buf.put(array, 2, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ assertEquals(buf.position(), 0);
+
+ loadTestData2(array, 0, array.length);
+ FloatBuffer ret = buf.put(array, 0, array.length);
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(buf, array, 0, array.length);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for java.nio.FloatBuffer put(java.nio.FloatBuffer)
+ */
+ public void testPutFloatBuffer() {
+ FloatBuffer other = FloatBuffer.allocate(buf.capacity());
+ try {
+ buf.put(buf);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ buf.put(FloatBuffer.allocate(buf.capacity() + 1));
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ try {
+ buf.flip();
+ buf.put((FloatBuffer)null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ buf.clear();
+ loadTestData2(other);
+ other.clear();
+ buf.clear();
+ FloatBuffer ret = buf.put(other);
+ assertEquals(other.position(), other.capacity());
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(other, buf);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for java.nio.FloatBuffer put(int, float)
+ */
+ public void testPutintfloat() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), 0);
+ FloatBuffer ret = buf.put(i, (float) i);
+ assertEquals(buf.get(i), (float) i, 0.0);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(-1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(buf.limit(), 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void testSlice() {
+ assertTrue(buf.capacity() > 5);
+ buf.position(1);
+ buf.limit(buf.capacity() - 1);
+
+ FloatBuffer slice = buf.slice();
+ assertEquals(buf.isReadOnly(), slice.isReadOnly());
+ assertEquals(buf.isDirect(), slice.isDirect());
+ assertEquals(buf.order(), slice.order());
+ assertEquals(slice.position(), 0);
+ assertEquals(slice.limit(), buf.remaining());
+ assertEquals(slice.capacity(), buf.remaining());
+ try {
+ slice.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // slice share the same content with buf
+ if (!slice.isReadOnly()) {
+ loadTestData1(slice);
+ assertContentLikeTestData1(buf, 1, 0, slice.capacity());
+ buf.put(2, 500);
+ assertEquals(slice.get(1), 500, 0.0);
+ }
+ }
+
+ public void testToString() {
+ String str = buf.toString();
+ assertTrue(str.indexOf("Float") >= 0 || str.indexOf("float") >= 0);
+ assertTrue(str.indexOf("" + buf.position()) >= 0);
+ assertTrue(str.indexOf("" + buf.limit()) >= 0);
+ assertTrue(str.indexOf("" + buf.capacity()) >= 0);
+ }
+
+ void loadTestData1(float array[], int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ array[offset + i] = (float) i;
+ }
+ }
+
+ void loadTestData2(float array[], int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ array[offset + i] = (float) length - i;
+ }
+ }
+
+ void loadTestData1(FloatBuffer buf) {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ buf.put(i, (float) i);
+ }
+ }
+
+ void loadTestData2(FloatBuffer buf) {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ buf.put(i, (float) buf.capacity() - i);
+ }
+ }
+
+ void assertContentEquals(FloatBuffer buf, float array[],
+ int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ assertEquals(buf.get(i), array[offset + i], 0.01);
+ }
+ }
+
+ void assertContentEquals(FloatBuffer buf, FloatBuffer other) {
+ assertEquals(buf.capacity(), other.capacity());
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.get(i), other.get(i), 0.01);
+ }
+ }
+
+ void assertContentLikeTestData1(FloatBuffer buf,
+ int startIndex, float startValue, int length) {
+ float value = startValue;
+ for (int i = 0; i < length; i++) {
+ assertEquals(buf.get(startIndex + i), value, 0.01);
+ value = value + 1.0f;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapByteBufferTest.java
new file mode 100644
index 0000000..2f8e44b
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapByteBufferTest.java
@@ -0,0 +1,60 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.ByteBuffer;
+
+
+public class HeapByteBufferTest extends ByteBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = ByteBuffer.allocate(BUFFER_LENGTH);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ buf = null;
+ baseBuf = null;
+ }
+
+ /**
+ * @tests java.nio.ByteBuffer#allocate(int)
+ *
+ */
+ public void testAllocatedByteBuffer_IllegalArg() {
+ try {
+ ByteBuffer.allocate(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ public void testIsDirect() {
+ assertFalse(buf.isDirect());
+ }
+
+ public void testHasArray() {
+ assertTrue(buf.hasArray());
+ }
+
+ public void testIsReadOnly() {
+ assertFalse(buf.isReadOnly());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapCharBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapCharBufferTest.java
new file mode 100644
index 0000000..a0c8d74
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapCharBufferTest.java
@@ -0,0 +1,44 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.CharBuffer;
+
+
+public class HeapCharBufferTest extends CharBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = CharBuffer.allocate(BUFFER_LENGTH);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ buf = null;
+ baseBuf = null;
+ }
+
+ public void testAllocatedCharBuffer_IllegalArg() {
+ try {
+ CharBuffer.allocate(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapDoubleBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapDoubleBufferTest.java
new file mode 100644
index 0000000..2985899
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapDoubleBufferTest.java
@@ -0,0 +1,42 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.DoubleBuffer;
+
+public class HeapDoubleBufferTest extends DoubleBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = DoubleBuffer.allocate(BUFFER_LENGTH);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ buf = null;
+ baseBuf = null;
+ }
+
+ public void testAllocatedDoubleBuffer_IllegalArg() {
+ try {
+ DoubleBuffer.allocate(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapFloatBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapFloatBufferTest.java
new file mode 100644
index 0000000..f90b34e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapFloatBufferTest.java
@@ -0,0 +1,42 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.FloatBuffer;
+
+public class HeapFloatBufferTest extends FloatBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = FloatBuffer.allocate(BUFFER_LENGTH);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ buf = null;
+ baseBuf = null;
+ }
+
+ public void testAllocatedFloatBuffer_IllegalArg() {
+ try {
+ FloatBuffer.allocate(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapIntBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapIntBufferTest.java
new file mode 100644
index 0000000..0d68835
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapIntBufferTest.java
@@ -0,0 +1,42 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.IntBuffer;
+
+public class HeapIntBufferTest extends IntBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = IntBuffer.allocate(BUFFER_LENGTH);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ buf = null;
+ baseBuf = null;
+ }
+
+ public void testAllocatedIntBuffer_IllegalArg() {
+ try {
+ IntBuffer.allocate(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapLongBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapLongBufferTest.java
new file mode 100644
index 0000000..f4f2ae1
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapLongBufferTest.java
@@ -0,0 +1,42 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.LongBuffer;
+
+public class HeapLongBufferTest extends LongBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = LongBuffer.allocate(BUFFER_LENGTH);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ buf = null;
+ baseBuf = null;
+ }
+
+ public void testAllocatedLongBuffer_IllegalArg() {
+ try {
+ LongBuffer.allocate(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapShortBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapShortBufferTest.java
new file mode 100644
index 0000000..327a035
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/HeapShortBufferTest.java
@@ -0,0 +1,42 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.ShortBuffer;
+
+public class HeapShortBufferTest extends ShortBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = ShortBuffer.allocate(BUFFER_LENGTH);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ buf = null;
+ baseBuf = null;
+ }
+
+ public void testAllocatedShortBuffer_IllegalArg() {
+ try {
+ ShortBuffer.allocate(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/IntBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/IntBufferTest.java
new file mode 100644
index 0000000..97babcf
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/IntBufferTest.java
@@ -0,0 +1,650 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.BufferOverflowException;
+import java.nio.BufferUnderflowException;
+import java.nio.ByteOrder;
+import java.nio.IntBuffer;
+import java.nio.InvalidMarkException;
+
+/**
+ * Tests java.nio.IntBuffer
+ *
+ */
+public class IntBufferTest extends AbstractBufferTest {
+
+
+ protected static final int SMALL_TEST_LENGTH = 5;
+
+ protected static final int BUFFER_LENGTH = 20;
+
+ protected IntBuffer buf;
+
+ protected void setUp() throws Exception {
+ buf = IntBuffer.allocate(BUFFER_LENGTH);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ buf = null;
+ baseBuf = null;
+ }
+
+ public void testArray() {
+ int array[] = buf.array();
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+ }
+
+ public void testArrayOffset() {
+ int array[] = buf.array();
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+ }
+
+ public void testAsReadOnlyBuffer() {
+ buf.clear();
+ buf.mark();
+ buf.position(buf.limit());
+
+ // readonly's contents should be the same as buf
+ IntBuffer readonly = buf.asReadOnlyBuffer();
+ assertNotSame(buf, readonly);
+ assertTrue(readonly.isReadOnly());
+ assertEquals(buf.position(), readonly.position());
+ assertEquals(buf.limit(), readonly.limit());
+ assertEquals(buf.isDirect(), readonly.isDirect());
+ assertEquals(buf.order(), readonly.order());
+ assertContentEquals(buf, readonly);
+
+ // readonly's position, mark, and limit should be independent to buf
+ readonly.reset();
+ assertEquals(readonly.position(), 0);
+ readonly.clear();
+ assertEquals(buf.position(), buf.limit());
+ buf.reset();
+ assertEquals(buf.position(), 0);
+ }
+
+ public void testCompact() {
+ // case: buffer is full
+ buf.clear();
+ buf.mark();
+ loadTestData1(buf);
+ IntBuffer ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), buf.capacity());
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, 0, buf.capacity());
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // case: buffer is empty
+ buf.position(0);
+ buf.limit(0);
+ buf.mark();
+ ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), 0);
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, 0, buf.capacity());
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // case: normal
+ assertTrue(buf.capacity() > 5);
+ buf.position(1);
+ buf.limit(5);
+ buf.mark();
+ ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), 4);
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, 1, 4);
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+ }
+
+ public void testCompareTo() {
+ // compare to self
+ assertEquals(0, buf.compareTo(buf));
+
+ // normal cases
+ assertTrue(buf.capacity() > 5);
+ buf.clear();
+ IntBuffer other = IntBuffer.allocate(buf.capacity());
+ loadTestData1(other);
+ assertEquals(0, buf.compareTo(other));
+ assertEquals(0, other.compareTo(buf));
+ buf.position(1);
+ assertTrue(buf.compareTo(other) > 0);
+ assertTrue(other.compareTo(buf) < 0);
+ other.position(2);
+ assertTrue(buf.compareTo(other) < 0);
+ assertTrue(other.compareTo(buf) > 0);
+ buf.position(2);
+ other.limit(5);
+ assertTrue(buf.compareTo(other) > 0);
+ assertTrue(other.compareTo(buf) < 0);
+ }
+
+ public void testDuplicate() {
+ buf.clear();
+ buf.mark();
+ buf.position(buf.limit());
+
+ // duplicate's contents should be the same as buf
+ IntBuffer duplicate = buf.duplicate();
+ assertNotSame(buf, duplicate);
+ assertEquals(buf.position(), duplicate.position());
+ assertEquals(buf.limit(), duplicate.limit());
+ assertEquals(buf.isReadOnly(), duplicate.isReadOnly());
+ assertEquals(buf.isDirect(), duplicate.isDirect());
+ assertEquals(buf.order(), duplicate.order());
+ assertContentEquals(buf, duplicate);
+
+ // duplicate's position, mark, and limit should be independent to buf
+ duplicate.reset();
+ assertEquals(duplicate.position(), 0);
+ duplicate.clear();
+ assertEquals(buf.position(), buf.limit());
+ buf.reset();
+ assertEquals(buf.position(), 0);
+
+ // duplicate share the same content with buf
+ if (!duplicate.isReadOnly()) {
+ loadTestData1(buf);
+ assertContentEquals(buf, duplicate);
+ loadTestData2(duplicate);
+ assertContentEquals(buf, duplicate);
+ }
+ }
+
+ public void testEquals() {
+ // equal to self
+ assertTrue(buf.equals(buf));
+ IntBuffer readonly = buf.asReadOnlyBuffer();
+ assertTrue(buf.equals(readonly));
+ IntBuffer duplicate = buf.duplicate();
+ assertTrue(buf.equals(duplicate));
+
+ // always false, if type mismatch
+ assertFalse(buf.equals(Boolean.TRUE));
+
+ assertTrue(buf.capacity() > 5);
+
+ buf.limit(buf.capacity()).position(0);
+ readonly.limit(readonly.capacity()).position(1);
+ assertFalse(buf.equals(readonly));
+
+ buf.limit(buf.capacity() - 1).position(0);
+ duplicate.limit(duplicate.capacity()).position(0);
+ assertFalse(buf.equals(duplicate));
+ }
+
+ /*
+ * Class under test for int get()
+ */
+ public void testGet() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ assertEquals(buf.get(), buf.get(i));
+ }
+ try {
+ buf.get();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.IntBuffer get(int[])
+ */
+ public void testGetintArray() {
+ int array[] = new int[1];
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ IntBuffer ret = buf.get(array);
+ assertEquals(array[0], buf.get(i));
+ assertSame(ret, buf);
+ }
+ try {
+ buf.get(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ try {
+ buf.get((int[])null);
+ fail("Should throw NPE"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.IntBuffer get(int[], int, int)
+ */
+ public void testGetintArrayintint() {
+ buf.clear();
+ int array[] = new int[buf.capacity()];
+
+ try {
+ buf.get(new int[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.get(array, -1, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ buf.get(array, array.length, 0);
+ try {
+ buf.get(array, array.length + 1, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.get(array, 2, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get((int[])null, 2, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ buf.get(array, 2, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ buf.get(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+
+ buf.clear();
+ IntBuffer ret = buf.get(array, 0, array.length);
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(buf, array, 0, array.length);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for int get(int)
+ */
+ public void testGetint() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ assertEquals(buf.get(), buf.get(i));
+ }
+ try {
+ buf.get(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get(buf.limit());
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void testHasArray() {
+ assertNotNull(buf.array());
+ }
+
+ public void testHashCode() {
+ buf.clear();
+ IntBuffer readonly = buf.asReadOnlyBuffer();
+ IntBuffer duplicate = buf.duplicate();
+ assertTrue(buf.hashCode() == readonly.hashCode());
+
+ assertTrue(buf.capacity() > 5);
+ duplicate.position(buf.capacity() / 2);
+ assertTrue(buf.hashCode() != duplicate.hashCode());
+ }
+
+ public void testIsDirect() {
+ assertFalse(buf.isDirect());
+ }
+
+ public void testOrder() {
+ buf.order();
+ assertEquals(ByteOrder.nativeOrder(), buf.order());
+ }
+
+ /*
+ * Class under test for java.nio.IntBuffer put(int)
+ */
+ public void testPutint() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ IntBuffer ret = buf.put((int) i);
+ assertEquals(buf.get(i), (int) i);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.IntBuffer put(int[])
+ */
+ public void testPutintArray() {
+ int array[] = new int[1];
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ array[0] = (int) i;
+ IntBuffer ret = buf.put(array);
+ assertEquals(buf.get(i), (int) i);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ try {
+ buf.position(buf.limit());
+ buf.put((int[])null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.IntBuffer put(int[], int, int)
+ */
+ public void testPutintArrayintint() {
+ buf.clear();
+ int array[] = new int[buf.capacity()];
+ try {
+ buf.put(new int[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.put(array, -1, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, array.length + 1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ buf.put(array, array.length, 0);
+ assertEquals(buf.position(), 0);
+ try {
+ buf.put(array, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put((int[])null, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ buf.put(array, 2, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ assertEquals(buf.position(), 0);
+
+ loadTestData2(array, 0, array.length);
+ IntBuffer ret = buf.put(array, 0, array.length);
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(buf, array, 0, array.length);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for java.nio.IntBuffer put(java.nio.IntBuffer)
+ */
+ public void testPutIntBuffer() {
+ IntBuffer other = IntBuffer.allocate(buf.capacity());
+ try {
+ buf.put(buf);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ buf.put(IntBuffer.allocate(buf.capacity() + 1));
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ try {
+ buf.flip();
+ buf.put((IntBuffer)null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ loadTestData2(other);
+ other.clear();
+ buf.clear();
+ IntBuffer ret = buf.put(other);
+ assertEquals(other.position(), other.capacity());
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(other, buf);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for java.nio.IntBuffer put(int, int)
+ */
+ public void testPutintint() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), 0);
+ IntBuffer ret = buf.put(i, (int) i);
+ assertEquals(buf.get(i), (int) i);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(-1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(buf.limit(), 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void testSlice() {
+ assertTrue(buf.capacity() > 5);
+ buf.position(1);
+ buf.limit(buf.capacity() - 1);
+
+ IntBuffer slice = buf.slice();
+ assertEquals(buf.isReadOnly(), slice.isReadOnly());
+ assertEquals(buf.isDirect(), slice.isDirect());
+ assertEquals(buf.order(), slice.order());
+ assertEquals(slice.position(), 0);
+ assertEquals(slice.limit(), buf.remaining());
+ assertEquals(slice.capacity(), buf.remaining());
+ try {
+ slice.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // slice share the same content with buf
+ if (!slice.isReadOnly()) {
+ loadTestData1(slice);
+ assertContentLikeTestData1(buf, 1, 0, slice.capacity());
+ buf.put(2, 500);
+ assertEquals(slice.get(1), 500);
+ }
+ }
+
+ public void testToString() {
+ String str = buf.toString();
+ assertTrue(str.indexOf("Int") >= 0 || str.indexOf("int") >= 0);
+ assertTrue(str.indexOf("" + buf.position()) >= 0);
+ assertTrue(str.indexOf("" + buf.limit()) >= 0);
+ assertTrue(str.indexOf("" + buf.capacity()) >= 0);
+ }
+
+ void loadTestData1(int array[], int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ array[offset + i] = (int) i;
+ }
+ }
+
+ void loadTestData2(int array[], int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ array[offset + i] = (int) length - i;
+ }
+ }
+
+ void loadTestData1(IntBuffer buf) {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ buf.put(i, (int) i);
+ }
+ }
+
+ void loadTestData2(IntBuffer buf) {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ buf.put(i, (int) buf.capacity() - i);
+ }
+ }
+
+ void assertContentEquals(IntBuffer buf, int array[],
+ int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ assertEquals(buf.get(i), array[offset + i]);
+ }
+ }
+
+ void assertContentEquals(IntBuffer buf, IntBuffer other) {
+ assertEquals(buf.capacity(), other.capacity());
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.get(i), other.get(i));
+ }
+ }
+
+ void assertContentLikeTestData1(IntBuffer buf,
+ int startIndex, int startValue, int length) {
+ int value = startValue;
+ for (int i = 0; i < length; i++) {
+ assertEquals(buf.get(startIndex + i), value);
+ value = value + 1;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/InvalidMarkExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/InvalidMarkExceptionTest.java
new file mode 100644
index 0000000..4b7682d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/InvalidMarkExceptionTest.java
@@ -0,0 +1,51 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.InvalidMarkException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class InvalidMarkExceptionTest extends TestCase {
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new InvalidMarkException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new InvalidMarkException());
+ }
+
+ /**
+ *@tests {@link java.nio.InvalidMarkException#InvalidMarkException()}
+ */
+ public void test_Constructor() {
+ InvalidMarkException exception = new InvalidMarkException();
+ assertNull(exception.getMessage());
+ assertNull(exception.getLocalizedMessage());
+ assertNull(exception.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/LongBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/LongBufferTest.java
new file mode 100644
index 0000000..371351b
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/LongBufferTest.java
@@ -0,0 +1,657 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.BufferOverflowException;
+import java.nio.BufferUnderflowException;
+import java.nio.ByteOrder;
+import java.nio.InvalidMarkException;
+import java.nio.LongBuffer;
+
+/**
+ * Tests java.nio.LongBuffer
+ *
+ */
+public class LongBufferTest extends AbstractBufferTest {
+
+
+ protected static final int SMALL_TEST_LENGTH = 5;
+
+ protected static final int BUFFER_LENGTH = 20;
+
+ protected LongBuffer buf;
+
+ protected void setUp() throws Exception {
+ buf = LongBuffer.allocate(BUFFER_LENGTH);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ buf = null;
+ baseBuf = null;
+ }
+
+ public void testArray() {
+ long array[] = buf.array();
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+ }
+
+ public void testArrayOffset() {
+ long array[] = buf.array();
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+ }
+
+ public void testAsReadOnlyBuffer() {
+ buf.clear();
+ buf.mark();
+ buf.position(buf.limit());
+
+ // readonly's contents should be the same as buf
+ LongBuffer readonly = buf.asReadOnlyBuffer();
+ assertNotSame(buf, readonly);
+ assertTrue(readonly.isReadOnly());
+ assertEquals(buf.position(), readonly.position());
+ assertEquals(buf.limit(), readonly.limit());
+ assertEquals(buf.isDirect(), readonly.isDirect());
+ assertEquals(buf.order(), readonly.order());
+ assertContentEquals(buf, readonly);
+
+ // readonly's position, mark, and limit should be independent to buf
+ readonly.reset();
+ assertEquals(readonly.position(), 0);
+ readonly.clear();
+ assertEquals(buf.position(), buf.limit());
+ buf.reset();
+ assertEquals(buf.position(), 0);
+ }
+
+ public void testCompact() {
+ // case: buffer is full
+ buf.clear();
+ buf.mark();
+ loadTestData1(buf);
+ LongBuffer ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), buf.capacity());
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, 0, buf.capacity());
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // case: buffer is empty
+ buf.position(0);
+ buf.limit(0);
+ buf.mark();
+ ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), 0);
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, 0, buf.capacity());
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // case: normal
+ assertTrue(buf.capacity() > 5);
+ buf.position(1);
+ buf.limit(5);
+ buf.mark();
+ ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), 4);
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, 1, 4);
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+ }
+
+ public void testCompareTo() {
+ // compare to self
+ assertEquals(0, buf.compareTo(buf));
+
+ // normal cases
+ assertTrue(buf.capacity() > 5);
+ buf.clear();
+ LongBuffer other = LongBuffer.allocate(buf.capacity());
+ loadTestData1(other);
+ assertEquals(0, buf.compareTo(other));
+ assertEquals(0, other.compareTo(buf));
+ buf.position(1);
+ assertTrue(buf.compareTo(other) > 0);
+ assertTrue(other.compareTo(buf) < 0);
+ other.position(2);
+ assertTrue(buf.compareTo(other) < 0);
+ assertTrue(other.compareTo(buf) > 0);
+ buf.position(2);
+ other.limit(5);
+ assertTrue(buf.compareTo(other) > 0);
+ assertTrue(other.compareTo(buf) < 0);
+ }
+
+ public void testDuplicate() {
+ buf.clear();
+ buf.mark();
+ buf.position(buf.limit());
+
+ // duplicate's contents should be the same as buf
+ LongBuffer duplicate = buf.duplicate();
+ assertNotSame(buf, duplicate);
+ assertEquals(buf.position(), duplicate.position());
+ assertEquals(buf.limit(), duplicate.limit());
+ assertEquals(buf.isReadOnly(), duplicate.isReadOnly());
+ assertEquals(buf.isDirect(), duplicate.isDirect());
+ assertEquals(buf.order(), duplicate.order());
+ assertContentEquals(buf, duplicate);
+
+ // duplicate's position, mark, and limit should be independent to buf
+ duplicate.reset();
+ assertEquals(duplicate.position(), 0);
+ duplicate.clear();
+ assertEquals(buf.position(), buf.limit());
+ buf.reset();
+ assertEquals(buf.position(), 0);
+
+ // duplicate share the same content with buf
+ if (!duplicate.isReadOnly()) {
+ loadTestData1(buf);
+ assertContentEquals(buf, duplicate);
+ loadTestData2(duplicate);
+ assertContentEquals(buf, duplicate);
+ }
+ }
+
+ public void testEquals() {
+ // equal to self
+ assertTrue(buf.equals(buf));
+ LongBuffer readonly = buf.asReadOnlyBuffer();
+ assertTrue(buf.equals(readonly));
+ LongBuffer duplicate = buf.duplicate();
+ assertTrue(buf.equals(duplicate));
+
+ // always false, if type mismatch
+ assertFalse(buf.equals(Boolean.TRUE));
+
+ assertTrue(buf.capacity() > 5);
+
+ buf.limit(buf.capacity()).position(0);
+ readonly.limit(readonly.capacity()).position(1);
+ assertFalse(buf.equals(readonly));
+
+ buf.limit(buf.capacity() - 1).position(0);
+ duplicate.limit(duplicate.capacity()).position(0);
+ assertFalse(buf.equals(duplicate));
+ }
+
+ /*
+ * Class under test for long get()
+ */
+ public void testGet() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ assertEquals(buf.get(), buf.get(i));
+ }
+ try {
+ buf.get();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.LongBuffer get(long[])
+ */
+ public void testGetlongArray() {
+ long array[] = new long[1];
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ LongBuffer ret = buf.get(array);
+ assertEquals(array[0], buf.get(i));
+ assertSame(ret, buf);
+ }
+ try {
+ buf.get(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ try {
+ buf.position(buf.limit());
+ buf.get((long[])null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.LongBuffer get(long[], int, int)
+ */
+ public void testGetlongArrayintint() {
+ buf.clear();
+ long array[] = new long[buf.capacity()];
+
+ try {
+ buf.get(new long[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.get(array, -1, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ buf.get(array, array.length, 0);
+ try {
+ buf.get(array, array.length + 1, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.get(array, 2, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get((long[])null, 2, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ buf.get(array, 2, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ buf.get(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+
+ buf.clear();
+ LongBuffer ret = buf.get(array, 0, array.length);
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(buf, array, 0, array.length);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for long get(int)
+ */
+ public void testGetint() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ assertEquals(buf.get(), buf.get(i));
+ }
+ try {
+ buf.get(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get(buf.limit());
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void testHasArray() {
+ assertNotNull(buf.array());
+ }
+
+ public void testHashCode() {
+ buf.clear();
+ LongBuffer readonly = buf.asReadOnlyBuffer();
+ LongBuffer duplicate = buf.duplicate();
+ assertTrue(buf.hashCode() == readonly.hashCode());
+
+ assertTrue(buf.capacity() > 5);
+ duplicate.position(buf.capacity() / 2);
+ assertTrue(buf.hashCode() != duplicate.hashCode());
+ }
+
+ public void testIsDirect() {
+ assertFalse(buf.isDirect());
+ }
+
+ public void testOrder() {
+ buf.order();
+ assertEquals(ByteOrder.nativeOrder(), buf.order());
+ }
+
+ /*
+ * Class under test for java.nio.LongBuffer put(long)
+ */
+ public void testPutlong() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ LongBuffer ret = buf.put((long) i);
+ assertEquals(buf.get(i), (long) i);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.LongBuffer put(long[])
+ */
+ public void testPutlongArray() {
+ long array[] = new long[1];
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ array[0] = (long) i;
+ LongBuffer ret = buf.put(array);
+ assertEquals(buf.get(i), (long) i);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ try {
+ buf.position(buf.limit());
+ buf.put((long[])null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.LongBuffer put(long[], int, int)
+ */
+ public void testPutlongArrayintint() {
+ buf.clear();
+ long array[] = new long[buf.capacity()];
+ try {
+ buf.put(new long[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.put(array, -1, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, array.length + 1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ buf.put(array, array.length, 0);
+ assertEquals(buf.position(), 0);
+ try {
+ buf.put(array, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, 2, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put((long[])null, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ buf.put(array, 2, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ assertEquals(buf.position(), 0);
+
+ loadTestData2(array, 0, array.length);
+ LongBuffer ret = buf.put(array, 0, array.length);
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(buf, array, 0, array.length);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for java.nio.LongBuffer put(java.nio.LongBuffer)
+ */
+ public void testPutLongBuffer() {
+ LongBuffer other = LongBuffer.allocate(buf.capacity());
+ try {
+ buf.put(buf);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ buf.put(LongBuffer.allocate(buf.capacity() + 1));
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ try {
+ buf.flip();
+ buf.put((LongBuffer)null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ loadTestData2(other);
+ other.clear();
+ buf.clear();
+ LongBuffer ret = buf.put(other);
+ assertEquals(other.position(), other.capacity());
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(other, buf);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for java.nio.LongBuffer put(int, long)
+ */
+ public void testPutintlong() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), 0);
+ LongBuffer ret = buf.put(i, (long) i);
+ assertEquals(buf.get(i), (long) i);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(-1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(buf.limit(), 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void testSlice() {
+ assertTrue(buf.capacity() > 5);
+ buf.position(1);
+ buf.limit(buf.capacity() - 1);
+
+ LongBuffer slice = buf.slice();
+ assertEquals(buf.isReadOnly(), slice.isReadOnly());
+ assertEquals(buf.isDirect(), slice.isDirect());
+ assertEquals(buf.order(), slice.order());
+ assertEquals(slice.position(), 0);
+ assertEquals(slice.limit(), buf.remaining());
+ assertEquals(slice.capacity(), buf.remaining());
+ try {
+ slice.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // slice share the same content with buf
+ if (!slice.isReadOnly()) {
+ loadTestData1(slice);
+ assertContentLikeTestData1(buf, 1, 0, slice.capacity());
+ buf.put(2, 500);
+ assertEquals(slice.get(1), 500);
+ }
+ }
+
+ public void testToString() {
+ String str = buf.toString();
+ assertTrue(str.indexOf("Long") >= 0 || str.indexOf("long") >= 0);
+ assertTrue(str.indexOf("" + buf.position()) >= 0);
+ assertTrue(str.indexOf("" + buf.limit()) >= 0);
+ assertTrue(str.indexOf("" + buf.capacity()) >= 0);
+ }
+
+ void loadTestData1(long array[], int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ array[offset + i] = (long) i;
+ }
+ }
+
+ void loadTestData2(long array[], int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ array[offset + i] = (long) length - i;
+ }
+ }
+
+ void loadTestData1(LongBuffer buf) {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ buf.put(i, (long) i);
+ }
+ }
+
+ void loadTestData2(LongBuffer buf) {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ buf.put(i, (long) buf.capacity() - i);
+ }
+ }
+
+ void assertContentEquals(LongBuffer buf, long array[],
+ int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ assertEquals(buf.get(i), array[offset + i]);
+ }
+ }
+
+ void assertContentEquals(LongBuffer buf, LongBuffer other) {
+ assertEquals(buf.capacity(), other.capacity());
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.get(i), other.get(i));
+ }
+ }
+
+ void assertContentLikeTestData1(LongBuffer buf,
+ int startIndex, long startValue, int length) {
+ long value = startValue;
+ for (int i = 0; i < length; i++) {
+ assertEquals(buf.get(startIndex + i), value);
+ value = value + 1;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/MappedByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/MappedByteBufferTest.java
new file mode 100644
index 0000000..308db21
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/MappedByteBufferTest.java
@@ -0,0 +1,231 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.BufferUnderflowException;
+import java.nio.ByteBuffer;
+import java.nio.IntBuffer;
+import java.nio.MappedByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.channels.NonWritableChannelException;
+import java.nio.channels.FileChannel.MapMode;
+
+import junit.framework.TestCase;
+
+public class MappedByteBufferTest extends TestCase {
+
+ File tmpFile, emptyFile;
+
+ /**
+ * A regression test for failing to correctly set capacity of underlying
+ * wrapped buffer from a mapped byte buffer.
+ */
+ public void testasIntBuffer() throws IOException {
+ // Map file
+ FileInputStream fis = new FileInputStream(tmpFile);
+ FileChannel fc = fis.getChannel();
+ MappedByteBuffer mmb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc
+ .size());
+ int len = mmb.capacity();
+ assertEquals("Got wrong number of bytes", 46, len); //$NON-NLS-1$
+
+ // Read in our 26 bytes
+ for (int i = 0; i < 26; i++) {
+ byte b = mmb.get();
+ assertEquals("Got wrong byte value", (byte) 'A' + i, b); //$NON-NLS-1$
+ }
+
+ // Now convert to an IntBuffer to read our ints
+ IntBuffer ibuffer = mmb.asIntBuffer();
+ for (int i = 0; i < 5; i++) {
+ int val = ibuffer.get();
+ assertEquals("Got wrong int value", i + 1, val); //$NON-NLS-1$
+ }
+ fc.close();
+ }
+
+ /**
+ * Regression for HARMONY-6315 - FileChannel.map throws IOException
+ * when called with size 0
+ *
+ * @throws IOException
+ */
+ public void testEmptyBuffer() throws IOException {
+ // Map empty file
+ FileInputStream fis = new FileInputStream(emptyFile);
+ FileChannel fc = fis.getChannel();
+ MappedByteBuffer mmb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
+
+ // check non-null
+ assertNotNull("MappedByteBuffer created from empty file should not be null",
+ mmb);
+
+ // check capacity is 0
+ int len = mmb.capacity();
+ assertEquals("MappedByteBuffer created from empty file should have 0 capacity",
+ 0, len);
+
+ assertFalse("MappedByteBuffer from empty file shouldn't be backed by an array ",
+ mmb.hasArray());
+
+ try
+ {
+ byte b = mmb.get();
+ fail("Calling MappedByteBuffer.get() on empty buffer should throw a BufferUnderflowException");
+ }
+ catch (BufferUnderflowException e)
+ {
+ // expected behaviour
+ }
+
+ // test expected exceptions thrown
+ try
+ {
+ mmb = fc.map(FileChannel.MapMode.READ_WRITE, 0, fc.size());
+ fail("Expected NonWritableChannelException to be thrown");
+ }
+ catch (NonWritableChannelException e)
+ {
+ // expected behaviour
+ }
+ try
+ {
+ mmb = fc.map(FileChannel.MapMode.PRIVATE, 0, fc.size());
+ fail("Expected NonWritableChannelException to be thrown");
+ }
+ catch (NonWritableChannelException e)
+ {
+ // expected behaviour
+ }
+ fc.close();
+ }
+
+ /**
+ * @tests {@link java.nio.MappedByteBuffer#force()}
+ */
+ public void test_force() throws IOException {
+ // buffer was not mapped in read/write mode
+ FileInputStream fileInputStream = new FileInputStream(tmpFile);
+ FileChannel fileChannelRead = fileInputStream.getChannel();
+ MappedByteBuffer mmbRead = fileChannelRead.map(MapMode.READ_ONLY, 0,
+ fileChannelRead.size());
+
+ mmbRead.force();
+
+ FileInputStream inputStream = new FileInputStream(tmpFile);
+ FileChannel fileChannelR = inputStream.getChannel();
+ MappedByteBuffer resultRead = fileChannelR.map(MapMode.READ_ONLY, 0,
+ fileChannelR.size());
+
+ //If this buffer was not mapped in read/write mode, then invoking this method has no effect.
+ assertEquals(
+ "Invoking force() should have no effect when this buffer was not mapped in read/write mode",
+ mmbRead, resultRead);
+
+ // Buffer was mapped in read/write mode
+ RandomAccessFile randomFile = new RandomAccessFile(tmpFile, "rw");
+ FileChannel fileChannelReadWrite = randomFile.getChannel();
+ MappedByteBuffer mmbReadWrite = fileChannelReadWrite.map(
+ FileChannel.MapMode.READ_WRITE, 0, fileChannelReadWrite.size());
+
+ mmbReadWrite.put((byte) 'o');
+ mmbReadWrite.force();
+
+ RandomAccessFile random = new RandomAccessFile(tmpFile, "rw");
+ FileChannel fileChannelRW = random.getChannel();
+ MappedByteBuffer resultReadWrite = fileChannelRW.map(
+ FileChannel.MapMode.READ_WRITE, 0, fileChannelRW.size());
+
+ // Invoking force() will change the buffer
+ assertFalse(mmbReadWrite.equals(resultReadWrite));
+
+ fileChannelRead.close();
+ fileChannelR.close();
+ fileChannelReadWrite.close();
+ fileChannelRW.close();
+ }
+
+ /**
+ * @tests {@link java.nio.MappedByteBuffer#load()}
+ */
+ public void test_load() throws IOException {
+ FileInputStream fileInputStream = new FileInputStream(tmpFile);
+ FileChannel fileChannelRead = fileInputStream.getChannel();
+ MappedByteBuffer mmbRead = fileChannelRead.map(MapMode.READ_ONLY, 0,
+ fileChannelRead.size());
+
+ assertEquals(mmbRead, mmbRead.load());
+
+ RandomAccessFile randomFile = new RandomAccessFile(tmpFile, "rw");
+ FileChannel fileChannelReadWrite = randomFile.getChannel();
+ MappedByteBuffer mmbReadWrite = fileChannelReadWrite.map(
+ FileChannel.MapMode.READ_WRITE, 0, fileChannelReadWrite.size());
+
+ assertEquals(mmbReadWrite, mmbReadWrite.load());
+
+ fileChannelRead.close();
+ fileChannelReadWrite.close();
+ }
+
+ protected void setUp() throws IOException {
+ // Create temp file with 26 bytes and 5 ints
+ tmpFile = File.createTempFile("harmony", "test"); //$NON-NLS-1$//$NON-NLS-2$
+ tmpFile.deleteOnExit();
+ FileOutputStream fileOutputStream = new FileOutputStream(tmpFile);
+ FileChannel fileChannel = fileOutputStream.getChannel();
+ ByteBuffer byteBuffer = ByteBuffer.allocateDirect(26 + 20);
+ for (int i = 0; i < 26; i++) {
+ byteBuffer.put((byte) ('A' + i));
+ }
+ for (int i = 0; i < 5; i++) {
+ byteBuffer.putInt(i + 1);
+ }
+ byteBuffer.rewind();
+ fileChannel.write(byteBuffer);
+ fileChannel.close();
+ fileOutputStream.close();
+
+ emptyFile = File.createTempFile("harmony", "test"); //$NON-NLS-1$//$NON-NLS-2$
+ emptyFile.deleteOnExit();
+ }
+
+ public void test_position() throws IOException {
+ File tmp = File.createTempFile("hmy", "tmp");
+ tmp.deleteOnExit();
+ RandomAccessFile f = new RandomAccessFile(tmp, "rw");
+ FileChannel ch = f.getChannel();
+ MappedByteBuffer mbb = ch.map(MapMode.READ_WRITE, 0L, 100L);
+ ch.close();
+
+ mbb.putInt(1, 1);
+ mbb.position(50);
+ mbb.putInt(50);
+
+ mbb.flip();
+ mbb.get();
+ assertEquals(1, mbb.getInt());
+
+ mbb.position(50);
+ assertEquals(50, mbb.getInt());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyBufferExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyBufferExceptionTest.java
new file mode 100644
index 0000000..cbacbc5
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyBufferExceptionTest.java
@@ -0,0 +1,51 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.ReadOnlyBufferException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+public class ReadOnlyBufferExceptionTest extends TestCase {
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new ReadOnlyBufferException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new ReadOnlyBufferException());
+ }
+
+ /**
+ *@tests {@link java.nio.ReadOnlyBufferException#ReadOnlyBufferException()}
+ */
+ public void test_Constructor() {
+ ReadOnlyBufferException exception = new ReadOnlyBufferException();
+ assertNull(exception.getMessage());
+ assertNull(exception.getLocalizedMessage());
+ assertNull(exception.getCause());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyCharBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyCharBufferTest.java
new file mode 100644
index 0000000..f951962
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyCharBufferTest.java
@@ -0,0 +1,209 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.CharBuffer;
+import java.nio.ReadOnlyBufferException;
+
+public class ReadOnlyCharBufferTest extends CharBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ loadTestData1(buf);
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ buf = null;
+ baseBuf = null;
+ super.tearDown();
+ }
+
+ public void testIsReadOnly() {
+ assertTrue(buf.isReadOnly());
+ }
+
+ public void testHasArray() {
+ assertFalse(buf.hasArray());
+ }
+
+ public void testArray() {
+ try {
+ buf.array();
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ }
+ }
+
+ public void testHashCode() {
+ CharBuffer duplicate = buf.duplicate();
+ assertEquals(buf.hashCode(), duplicate.hashCode());
+ }
+
+ public void testArrayOffset() {
+ try {
+ buf.arrayOffset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ }
+ }
+
+ public void testCompact() {
+ try {
+ buf.compact();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutchar() {
+ try {
+ buf.put((char) 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutcharArray() {
+ char array[] = new char[1];
+ try {
+ buf.put(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((char[]) null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ public void testPutcharArrayintint() {
+ char array[] = new char[1];
+ try {
+ buf.put(array, 0, array.length);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((char[]) null, 0, 1);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(new char[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(array, -1, array.length);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutCharBuffer() {
+ CharBuffer other = CharBuffer.allocate(1);
+ try {
+ buf.put(other);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((CharBuffer) null);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(buf);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutintchar() {
+ try {
+ buf.put(0, (char) 0);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(-1, (char) 0);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutStringintint() {
+ buf.clear();
+ String str = String.valueOf(new char[buf.capacity()]);
+ try {
+ buf.put(str, 0, str.length());
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((String) null, 0, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException expected) {
+ } catch (NullPointerException expected) {
+ }
+ try {
+ buf.put(str, -1, str.length());
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException expected) {
+ } catch (NullPointerException expected) {
+ }
+ String longStr = String.valueOf(new char[buf.capacity()+1]);
+ try {
+ buf.put(longStr, 0, longStr.length());
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutString() {
+ String str = " ";
+ try {
+ buf.put(str);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((String)null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDirectByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDirectByteBufferTest.java
new file mode 100644
index 0000000..20c7914
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDirectByteBufferTest.java
@@ -0,0 +1,44 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+
+public class ReadOnlyDirectByteBufferTest extends DirectByteBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testIsReadOnly() {
+ assertTrue(buf.isReadOnly());
+ }
+
+ public void testHasArray() {
+ assertFalse(buf.hasArray());
+ }
+
+ public void testHashCode() {
+ super.readOnlyHashCode();
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDoubleBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDoubleBufferTest.java
new file mode 100644
index 0000000..d87e81d
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyDoubleBufferTest.java
@@ -0,0 +1,160 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.DoubleBuffer;
+import java.nio.ReadOnlyBufferException;
+
+public class ReadOnlyDoubleBufferTest extends DoubleBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testIsReadOnly() {
+ assertTrue(buf.isReadOnly());
+ }
+
+ public void testHasArray() {
+ assertFalse(buf.hasArray());
+ }
+
+ public void testArray() {
+ try {
+ buf.array();
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ }
+ }
+
+ public void testHashCode() {
+ DoubleBuffer duplicate = buf.duplicate();
+ assertEquals(buf.hashCode(), duplicate.hashCode());
+ }
+
+ public void testArrayOffset() {
+ try {
+ buf.arrayOffset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ }
+ }
+
+ public void testCompact() {
+ try {
+ buf.compact();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutdouble() {
+ try {
+ buf.put(0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutdoubleArray() {
+ double array[] = new double[1];
+ try {
+ buf.put(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((double[]) null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ public void testPutdoubleArrayintint() {
+ double array[] = new double[1];
+ try {
+ buf.put(array, 0, array.length);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((double[]) null, 0, 1);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(new double[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(array, -1, array.length);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutDoubleBuffer() {
+ DoubleBuffer other = DoubleBuffer.allocate(1);
+ try {
+ buf.put(other);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((DoubleBuffer) null);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(buf);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutintdouble() {
+ try {
+ buf.put(0, (double) 0);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(-1, (double) 0);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyFloatBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyFloatBufferTest.java
new file mode 100644
index 0000000..3acc5c4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyFloatBufferTest.java
@@ -0,0 +1,161 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.FloatBuffer;
+import java.nio.ReadOnlyBufferException;
+
+public class ReadOnlyFloatBufferTest extends FloatBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testIsReadOnly() {
+ assertTrue(buf.isReadOnly());
+ }
+
+ public void testHasArray() {
+ assertFalse(buf.hasArray());
+ }
+
+ public void testArray() {
+ try {
+ buf.array();
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ //expected
+ }
+ }
+
+ public void testHashCode() {
+ FloatBuffer duplicate = buf.duplicate();
+ assertEquals(buf.hashCode(), duplicate.hashCode());
+ }
+
+ public void testArrayOffset() {
+ try {
+ buf.arrayOffset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+ }
+
+ public void testCompact() {
+ try {
+ buf.compact();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutfloat() {
+ try {
+ buf.put(0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutfloatArray() {
+ float array[] = new float[1];
+ try {
+ buf.put(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((float[]) null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ public void testPutfloatArrayintint() {
+ float array[] = new float[1];
+ try {
+ buf.put(array, 0, array.length);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((float[]) null, 0, 1);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(new float[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(array, -1, array.length);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutFloatBuffer() {
+ FloatBuffer other = FloatBuffer.allocate(1);
+ try {
+ buf.put(other);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((FloatBuffer) null);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(buf);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutintfloat() {
+ try {
+ buf.put(0, (float) 0);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(-1, (float) 0);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapByteBufferTest.java
new file mode 100644
index 0000000..7452a24
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapByteBufferTest.java
@@ -0,0 +1,43 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+
+public class ReadOnlyHeapByteBufferTest extends HeapByteBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testIsReadOnly() {
+ assertTrue(buf.isReadOnly());
+ }
+
+ public void testHasArray() {
+ assertFalse(buf.hasArray());
+ }
+
+ public void testHashCode() {
+ super.readOnlyHashCode();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapCharBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapCharBufferTest.java
new file mode 100644
index 0000000..4c7792a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapCharBufferTest.java
@@ -0,0 +1,35 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.CharBuffer;
+
+
+public class ReadOnlyHeapCharBufferTest extends ReadOnlyCharBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = CharBuffer.allocate(BUFFER_LENGTH);
+ super.loadTestData1(buf);
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapDoubleBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapDoubleBufferTest.java
new file mode 100644
index 0000000..f95c4c2
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapDoubleBufferTest.java
@@ -0,0 +1,34 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.DoubleBuffer;
+
+public class ReadOnlyHeapDoubleBufferTest extends ReadOnlyDoubleBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = DoubleBuffer.allocate(BUFFER_LENGTH);
+ super.loadTestData1(buf);
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapFloatBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapFloatBufferTest.java
new file mode 100644
index 0000000..f2c6644
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapFloatBufferTest.java
@@ -0,0 +1,32 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.FloatBuffer;
+
+public class ReadOnlyHeapFloatBufferTest extends ReadOnlyFloatBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = FloatBuffer.allocate(BUFFER_LENGTH);
+ super.loadTestData1(buf);
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapIntBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapIntBufferTest.java
new file mode 100644
index 0000000..f9a3877
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapIntBufferTest.java
@@ -0,0 +1,32 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.IntBuffer;
+
+public class ReadOnlyHeapIntBufferTest extends ReadOnlyIntBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = IntBuffer.allocate(BUFFER_LENGTH);
+ super.loadTestData1(buf);
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapLongBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapLongBufferTest.java
new file mode 100644
index 0000000..efba978
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapLongBufferTest.java
@@ -0,0 +1,32 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.LongBuffer;
+
+public class ReadOnlyHeapLongBufferTest extends ReadOnlyLongBufferTest{
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = LongBuffer.allocate(BUFFER_LENGTH);
+ super.loadTestData1(buf);
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapShortBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapShortBufferTest.java
new file mode 100644
index 0000000..bbbd616
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyHeapShortBufferTest.java
@@ -0,0 +1,32 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.ShortBuffer;
+
+public class ReadOnlyHeapShortBufferTest extends ReadOnlyShortBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = ShortBuffer.allocate(BUFFER_LENGTH);
+ super.loadTestData1(buf);
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyIntBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyIntBufferTest.java
new file mode 100644
index 0000000..61e78a6
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyIntBufferTest.java
@@ -0,0 +1,161 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.IntBuffer;
+import java.nio.ReadOnlyBufferException;
+
+public class ReadOnlyIntBufferTest extends IntBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testIsReadOnly() {
+ assertTrue(buf.isReadOnly());
+ }
+
+ public void testHasArray() {
+ assertFalse(buf.hasArray());
+ }
+
+ public void testArray() {
+ try {
+ buf.array();
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ //expected
+ }
+ }
+
+ public void testHashCode() {
+ IntBuffer duplicate = buf.duplicate();
+ assertEquals(buf.hashCode(), duplicate.hashCode());
+ }
+
+ public void testArrayOffset() {
+ try {
+ buf.arrayOffset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+ }
+
+ public void testCompact() {
+ try {
+ buf.compact();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutint() {
+ try {
+ buf.put(0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutintArray() {
+ int array[] = new int[1];
+ try {
+ buf.put(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((int[]) null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ public void testPutintArrayintint() {
+ int array[] = new int[1];
+ try {
+ buf.put(array, 0, array.length);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((int[]) null, -1, 1);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(new int[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(array, -1, array.length);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutIntBuffer() {
+ IntBuffer other = IntBuffer.allocate(1);
+ try {
+ buf.put(other);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((IntBuffer) null);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(buf);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutintint() {
+ try {
+ buf.put(0, (int) 0);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(-1, (int) 0);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyLongBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyLongBufferTest.java
new file mode 100644
index 0000000..b670606
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyLongBufferTest.java
@@ -0,0 +1,161 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.LongBuffer;
+import java.nio.ReadOnlyBufferException;
+
+public class ReadOnlyLongBufferTest extends LongBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testIsReadOnly() {
+ assertTrue(buf.isReadOnly());
+ }
+
+ public void testHasArray() {
+ assertFalse(buf.hasArray());
+ }
+
+ public void testArray() {
+ try {
+ buf.array();
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ //expected
+ }
+ }
+
+ public void testHashCode() {
+ LongBuffer duplicate = buf.duplicate();
+ assertEquals(buf.hashCode(), duplicate.hashCode());
+ }
+
+ public void testArrayOffset() {
+ try {
+ buf.arrayOffset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+ }
+
+ public void testCompact() {
+ try {
+ buf.compact();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutlong() {
+ try {
+ buf.put(0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutlongArray() {
+ long array[] = new long[1];
+ try {
+ buf.put(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((long[]) null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ public void testPutlongArrayintint() {
+ long array[] = new long[1];
+ try {
+ buf.put(array, 0, array.length);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((long[]) null, 0, 1);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(new long[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(array, -1, array.length);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutLongBuffer() {
+ LongBuffer other = LongBuffer.allocate(1);
+ try {
+ buf.put(other);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((LongBuffer) null);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(buf);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutintlong() {
+ try {
+ buf.put(0, (long) 0);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(-1, (long) 0);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyShortBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyShortBufferTest.java
new file mode 100644
index 0000000..611f6bf
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyShortBufferTest.java
@@ -0,0 +1,161 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.ReadOnlyBufferException;
+import java.nio.ShortBuffer;
+
+public class ReadOnlyShortBufferTest extends ShortBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testIsReadOnly() {
+ assertTrue(buf.isReadOnly());
+ }
+
+ public void testHasArray() {
+ assertFalse(buf.hasArray());
+ }
+
+ public void testArray() {
+ try {
+ buf.array();
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ //expected
+ }
+ }
+
+ public void testHashCode() {
+ ShortBuffer duplicate = buf.duplicate();
+ assertEquals(buf.hashCode(), duplicate.hashCode());
+ }
+
+ public void testArrayOffset() {
+ try {
+ buf.arrayOffset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ //expected
+ }
+ }
+
+ public void testCompact() {
+ try {
+ buf.compact();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutshort() {
+ try {
+ buf.put((short)0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutshortArray() {
+ short array[] = new short[1];
+ try {
+ buf.put(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((short[]) null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ public void testPutshortArrayintint() {
+ short array[] = new short[1];
+ try {
+ buf.put(array, 0, array.length);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((short[]) null, 0, 1);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(new short[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(array, -1, array.length);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutShortBuffer() {
+ ShortBuffer other = ShortBuffer.allocate(1);
+ try {
+ buf.put(other);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((ShortBuffer) null);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(buf);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+
+ public void testPutintshort() {
+ try {
+ buf.put(0, (short) 0);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put(-1, (short) 0);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedByteBufferTest.java
new file mode 100644
index 0000000..031d75b
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedByteBufferTest.java
@@ -0,0 +1,45 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+
+public class ReadOnlyWrappedByteBufferTest extends WrappedByteBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testIsReadOnly() {
+ assertTrue(buf.isReadOnly());
+ }
+
+ public void testHasArray() {
+ assertFalse(buf.hasArray());
+ }
+
+ public void testHashCode() {
+ super.readOnlyHashCode();
+ }
+
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedCharBufferTest1.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedCharBufferTest1.java
new file mode 100644
index 0000000..57c04bf
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedCharBufferTest1.java
@@ -0,0 +1,34 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.CharBuffer;
+
+public class ReadOnlyWrappedCharBufferTest1 extends ReadOnlyCharBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = CharBuffer.wrap(new char[BUFFER_LENGTH]);
+ super.loadTestData1(buf);
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedDoubleBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedDoubleBufferTest.java
new file mode 100644
index 0000000..d1ba9df
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedDoubleBufferTest.java
@@ -0,0 +1,32 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.DoubleBuffer;
+
+public class ReadOnlyWrappedDoubleBufferTest extends ReadOnlyDoubleBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = DoubleBuffer.wrap(new double[BUFFER_LENGTH]);
+ super.loadTestData1(buf);
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedFloatBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedFloatBufferTest.java
new file mode 100644
index 0000000..affddaa
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedFloatBufferTest.java
@@ -0,0 +1,32 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.FloatBuffer;
+
+public class ReadOnlyWrappedFloatBufferTest extends ReadOnlyFloatBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = FloatBuffer.wrap(new float[BUFFER_LENGTH]);
+ super.loadTestData1(buf);
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedIntBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedIntBufferTest.java
new file mode 100644
index 0000000..a4d0155
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedIntBufferTest.java
@@ -0,0 +1,32 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.IntBuffer;
+
+public class ReadOnlyWrappedIntBufferTest extends ReadOnlyIntBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = IntBuffer.wrap(new int[BUFFER_LENGTH]);
+ super.loadTestData1(buf);
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedLongBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedLongBufferTest.java
new file mode 100644
index 0000000..58491da
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedLongBufferTest.java
@@ -0,0 +1,32 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.LongBuffer;
+
+public class ReadOnlyWrappedLongBufferTest extends ReadOnlyLongBufferTest{
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = LongBuffer.wrap(new long[BUFFER_LENGTH]);
+ super.loadTestData1(buf);
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedShortBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedShortBufferTest.java
new file mode 100644
index 0000000..0ecb3a4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ReadOnlyWrappedShortBufferTest.java
@@ -0,0 +1,32 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.ShortBuffer;
+
+public class ReadOnlyWrappedShortBufferTest extends ReadOnlyShortBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = ShortBuffer.wrap(new short[BUFFER_LENGTH]);
+ super.loadTestData1(buf);
+ buf = buf.asReadOnlyBuffer();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ShortBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ShortBufferTest.java
new file mode 100644
index 0000000..98d7659
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/ShortBufferTest.java
@@ -0,0 +1,637 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.BufferOverflowException;
+import java.nio.BufferUnderflowException;
+import java.nio.ByteOrder;
+import java.nio.InvalidMarkException;
+import java.nio.ShortBuffer;
+
+/**
+ * Tests java.nio.ShortBuffer
+ *
+ */
+public class ShortBufferTest extends AbstractBufferTest {
+
+ protected static final int SMALL_TEST_LENGTH = 5;
+
+ protected static final int BUFFER_LENGTH = 20;
+
+ protected ShortBuffer buf;
+
+ protected void setUp() throws Exception {
+ buf = ShortBuffer.allocate(BUFFER_LENGTH);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ buf = null;
+ baseBuf = null;
+ }
+
+ public void testArray() {
+ short array[] = buf.array();
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+ }
+
+ public void testArrayOffset() {
+ short array[] = buf.array();
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(array, buf.arrayOffset(), buf.capacity());
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData1(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+
+ loadTestData2(buf);
+ assertContentEquals(buf, array, buf.arrayOffset(), buf.capacity());
+ }
+
+ public void testAsReadOnlyBuffer() {
+ buf.clear();
+ buf.mark();
+ buf.position(buf.limit());
+
+ // readonly's contents should be the same as buf
+ ShortBuffer readonly = buf.asReadOnlyBuffer();
+ assertNotSame(buf, readonly);
+ assertTrue(readonly.isReadOnly());
+ assertEquals(buf.position(), readonly.position());
+ assertEquals(buf.limit(), readonly.limit());
+ assertEquals(buf.isDirect(), readonly.isDirect());
+ assertEquals(buf.order(), readonly.order());
+ assertContentEquals(buf, readonly);
+
+ // readonly's position, mark, and limit should be independent to buf
+ readonly.reset();
+ assertEquals(readonly.position(), 0);
+ readonly.clear();
+ assertEquals(buf.position(), buf.limit());
+ buf.reset();
+ assertEquals(buf.position(), 0);
+ }
+
+ public void testCompact() {
+ // case: buffer is full
+ buf.clear();
+ buf.mark();
+ loadTestData1(buf);
+ ShortBuffer ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), buf.capacity());
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, (short) 0, buf.capacity());
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // case: buffer is empty
+ buf.position(0);
+ buf.limit(0);
+ buf.mark();
+ ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), 0);
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, (short) 0, buf.capacity());
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // case: normal
+ assertTrue(buf.capacity() > 5);
+ buf.position(1);
+ buf.limit(5);
+ buf.mark();
+ ret = buf.compact();
+ assertSame(ret, buf);
+ assertEquals(buf.position(), 4);
+ assertEquals(buf.limit(), buf.capacity());
+ assertContentLikeTestData1(buf, 0, (short) 1, 4);
+ try {
+ buf.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+ }
+
+ public void testCompareTo() {
+ // compare to self
+ assertEquals(0, buf.compareTo(buf));
+
+ // normal cases
+ assertTrue(buf.capacity() > 5);
+ buf.clear();
+ ShortBuffer other = ShortBuffer.allocate(buf.capacity());
+ loadTestData1(other);
+ assertEquals(0, buf.compareTo(other));
+ assertEquals(0, other.compareTo(buf));
+ buf.position(1);
+ assertTrue(buf.compareTo(other) > 0);
+ assertTrue(other.compareTo(buf) < 0);
+ other.position(2);
+ assertTrue(buf.compareTo(other) < 0);
+ assertTrue(other.compareTo(buf) > 0);
+ buf.position(2);
+ other.limit(5);
+ assertTrue(buf.compareTo(other) > 0);
+ assertTrue(other.compareTo(buf) < 0);
+ }
+
+ public void testDuplicate() {
+ buf.clear();
+ buf.mark();
+ buf.position(buf.limit());
+
+ // duplicate's contents should be the same as buf
+ ShortBuffer duplicate = buf.duplicate();
+ assertNotSame(buf, duplicate);
+ assertEquals(buf.position(), duplicate.position());
+ assertEquals(buf.limit(), duplicate.limit());
+ assertEquals(buf.isReadOnly(), duplicate.isReadOnly());
+ assertEquals(buf.isDirect(), duplicate.isDirect());
+ assertEquals(buf.order(), duplicate.order());
+ assertContentEquals(buf, duplicate);
+
+ // duplicate's position, mark, and limit should be independent to buf
+ duplicate.reset();
+ assertEquals(duplicate.position(), 0);
+ duplicate.clear();
+ assertEquals(buf.position(), buf.limit());
+ buf.reset();
+ assertEquals(buf.position(), 0);
+
+ // duplicate share the same content with buf
+ if (!duplicate.isReadOnly()) {
+ loadTestData1(buf);
+ assertContentEquals(buf, duplicate);
+ loadTestData2(duplicate);
+ assertContentEquals(buf, duplicate);
+ }
+ }
+
+ public void testEquals() {
+ // equal to self
+ assertTrue(buf.equals(buf));
+ ShortBuffer readonly = buf.asReadOnlyBuffer();
+ assertTrue(buf.equals(readonly));
+ ShortBuffer duplicate = buf.duplicate();
+ assertTrue(buf.equals(duplicate));
+
+ // always false, if type mismatch
+ assertFalse(buf.equals(Boolean.TRUE));
+
+ assertTrue(buf.capacity() > 5);
+
+ buf.limit(buf.capacity()).position(0);
+ readonly.limit(readonly.capacity()).position(1);
+ assertFalse(buf.equals(readonly));
+
+ buf.limit(buf.capacity() - 1).position(0);
+ duplicate.limit(duplicate.capacity()).position(0);
+ assertFalse(buf.equals(duplicate));
+ }
+
+ /*
+ * Class under test for short get()
+ */
+ public void testGet() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ assertEquals(buf.get(), buf.get(i));
+ }
+ try {
+ buf.get();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.ShortBuffer get(short[])
+ */
+ public void testGetshortArray() {
+ short array[] = new short[1];
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ ShortBuffer ret = buf.get(array);
+ assertEquals(array[0], buf.get(i));
+ assertSame(ret, buf);
+ }
+ try {
+ buf.get(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.ShortBuffer get(short[], int, int)
+ */
+ public void testGetshortArrayintint() {
+ buf.clear();
+ short array[] = new short[buf.capacity()];
+
+ try {
+ buf.get(new short[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.get(array, -1, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ buf.get(array, array.length, 0);
+ try {
+ buf.get(array, array.length + 1, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.get((short[])null, 2, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ buf.get(array, 2, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferUnderflowException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ buf.get(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+
+ buf.clear();
+ ShortBuffer ret = buf.get(array, 0, array.length);
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(buf, array, 0, array.length);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for short get(int)
+ */
+ public void testGetint() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ assertEquals(buf.get(), buf.get(i));
+ }
+ try {
+ buf.get(-1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.get(buf.limit());
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void testHasArray() {
+ assertNotNull(buf.array());
+ }
+
+ public void testHashCode() {
+ buf.clear();
+ ShortBuffer readonly = buf.asReadOnlyBuffer();
+ ShortBuffer duplicate = buf.duplicate();
+ assertTrue(buf.hashCode() == readonly.hashCode());
+
+ assertTrue(buf.capacity() > 5);
+ duplicate.position(buf.capacity() / 2);
+ assertTrue(buf.hashCode() != duplicate.hashCode());
+ }
+
+ public void testIsDirect() {
+ assertFalse(buf.isDirect());
+ }
+
+ public void testOrder() {
+ buf.order();
+ assertEquals(ByteOrder.nativeOrder(), buf.order());
+ }
+
+ /*
+ * Class under test for java.nio.ShortBuffer put(short)
+ */
+ public void testPutshort() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ ShortBuffer ret = buf.put((short) i);
+ assertEquals(buf.get(i), (short) i);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put((short) 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.ShortBuffer put(short[])
+ */
+ public void testPutshortArray() {
+ short array[] = new short[1];
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), i);
+ array[0] = (short) i;
+ ShortBuffer ret = buf.put(array);
+ assertEquals(buf.get(i), (short) i);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(array);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ try {
+ buf.position(buf.limit());
+ buf.put((short[])null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /*
+ * Class under test for java.nio.ShortBuffer put(short[], int, int)
+ */
+ public void testPutshortArrayintint() {
+ buf.clear();
+ short array[] = new short[buf.capacity()];
+ try {
+ buf.put(new short[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ assertEquals(buf.position(), 0);
+ try {
+ buf.put(array, -1, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, array.length + 1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ buf.put(array, array.length, 0);
+ assertEquals(buf.position(), 0);
+ try {
+ buf.put(array, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put((short[])null, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ buf.put(array, 2, array.length);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ assertEquals(buf.position(), 0);
+
+ loadTestData2(array, 0, array.length);
+ ShortBuffer ret = buf.put(array, 0, array.length);
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(buf, array, 0, array.length);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for java.nio.ShortBuffer put(java.nio.ShortBuffer)
+ */
+ public void testPutShortBuffer() {
+ ShortBuffer other = ShortBuffer.allocate(buf.capacity());
+ try {
+ buf.put(buf);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ buf.put(ShortBuffer.allocate(buf.capacity() + 1));
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (BufferOverflowException e) {
+ // expected
+ }
+ try {
+ buf.flip();
+ buf.put((ShortBuffer)null);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ loadTestData2(other);
+ other.clear();
+ buf.clear();
+ ShortBuffer ret = buf.put(other);
+ assertEquals(other.position(), other.capacity());
+ assertEquals(buf.position(), buf.capacity());
+ assertContentEquals(other, buf);
+ assertSame(ret, buf);
+ }
+
+ /*
+ * Class under test for java.nio.ShortBuffer put(int, short)
+ */
+ public void testPutintshort() {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.position(), 0);
+ ShortBuffer ret = buf.put(i, (short) i);
+ assertEquals(buf.get(i), (short) i);
+ assertSame(ret, buf);
+ }
+ try {
+ buf.put(-1, (short) 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ buf.put(buf.limit(), (short) 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ }
+
+ public void testSlice() {
+ assertTrue(buf.capacity() > 5);
+ buf.position(1);
+ buf.limit(buf.capacity() - 1);
+
+ ShortBuffer slice = buf.slice();
+ assertEquals(buf.isReadOnly(), slice.isReadOnly());
+ assertEquals(buf.isDirect(), slice.isDirect());
+ assertEquals(buf.order(), slice.order());
+ assertEquals(slice.position(), 0);
+ assertEquals(slice.limit(), buf.remaining());
+ assertEquals(slice.capacity(), buf.remaining());
+ try {
+ slice.reset();
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (InvalidMarkException e) {
+ // expected
+ }
+
+ // slice share the same content with buf
+ if (!slice.isReadOnly()) {
+ loadTestData1(slice);
+ assertContentLikeTestData1(buf, 1, (short) 0, slice.capacity());
+ buf.put(2, (short) 500);
+ assertEquals(slice.get(1), 500);
+ }
+ }
+
+ public void testToString() {
+ String str = buf.toString();
+ assertTrue(str.indexOf("Short") >= 0 || str.indexOf("short") >= 0);
+ assertTrue(str.indexOf("" + buf.position()) >= 0);
+ assertTrue(str.indexOf("" + buf.limit()) >= 0);
+ assertTrue(str.indexOf("" + buf.capacity()) >= 0);
+ }
+
+ void loadTestData1(short array[], int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ array[offset + i] = (short) i;
+ }
+ }
+
+ void loadTestData2(short array[], int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ array[offset + i] = (short) (length - i);
+ }
+ }
+
+ void loadTestData1(ShortBuffer buf) {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ buf.put(i, (short) i);
+ }
+ }
+
+ void loadTestData2(ShortBuffer buf) {
+ buf.clear();
+ for (int i = 0; i < buf.capacity(); i++) {
+ buf.put(i, (short) (buf.capacity() - i));
+ }
+ }
+
+ void assertContentEquals(ShortBuffer buf, short array[],
+ int offset, int length) {
+ for (int i = 0; i < length; i++) {
+ assertEquals(buf.get(i), array[offset + i]);
+ }
+ }
+
+ void assertContentEquals(ShortBuffer buf, ShortBuffer other) {
+ assertEquals(buf.capacity(), other.capacity());
+ for (int i = 0; i < buf.capacity(); i++) {
+ assertEquals(buf.get(i), other.get(i));
+ }
+ }
+
+ void assertContentLikeTestData1(ShortBuffer buf,
+ int startIndex, short startValue, int length) {
+ short value = startValue;
+ for (int i = 0; i < length; i++) {
+ assertEquals(buf.get(startIndex + i), value);
+ value = (short) (value + 1);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceDirectByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceDirectByteBufferTest.java
new file mode 100644
index 0000000..541cde0
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceDirectByteBufferTest.java
@@ -0,0 +1,32 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+
+public class SliceDirectByteBufferTest extends DirectByteBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf.position(1).limit(BUFFER_LENGTH-1);
+ buf = buf.slice();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceHeapByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceHeapByteBufferTest.java
new file mode 100644
index 0000000..9f9f7aa
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceHeapByteBufferTest.java
@@ -0,0 +1,33 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+
+public class SliceHeapByteBufferTest extends HeapByteBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf.position(1).limit(BUFFER_LENGTH-1);
+ buf = buf.slice();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceWrappedByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceWrappedByteBufferTest.java
new file mode 100644
index 0000000..f1ddfb9
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/SliceWrappedByteBufferTest.java
@@ -0,0 +1,33 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+
+public class SliceWrappedByteBufferTest extends WrappedByteBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf.position(1).limit(BUFFER_LENGTH-1);
+ buf = buf.slice();
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedByteBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedByteBufferTest.java
new file mode 100644
index 0000000..6460d2e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedByteBufferTest.java
@@ -0,0 +1,97 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.ByteBuffer;
+
+public class WrappedByteBufferTest extends ByteBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = ByteBuffer.wrap(new byte[BUFFER_LENGTH]);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ buf = null;
+ baseBuf = null;
+ }
+
+ /**
+ * @tests java.nio.ByteBuffer#allocate(byte[],int,int)
+ *
+ */
+ public void testWrappedByteBuffer_IllegalArg() {
+ byte array[] = new byte[BUFFER_LENGTH];
+ try {
+ ByteBuffer.wrap(array, -1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ ByteBuffer.wrap(array, BUFFER_LENGTH + 1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ ByteBuffer.wrap(array, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ ByteBuffer.wrap(array, 0, BUFFER_LENGTH + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ ByteBuffer.wrap(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ ByteBuffer.wrap(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ ByteBuffer.wrap((byte[])null, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ public void testIsDirect() {
+ assertFalse(buf.isDirect());
+ }
+
+ public void testHasArray() {
+ assertTrue(buf.hasArray());
+ }
+
+ public void testIsReadOnly() {
+ assertFalse(buf.isReadOnly());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest1.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest1.java
new file mode 100644
index 0000000..9181a77
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest1.java
@@ -0,0 +1,84 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.CharBuffer;
+
+public class WrappedCharBufferTest1 extends CharBufferTest {
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = CharBuffer.wrap(new char[BUFFER_LENGTH]);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ baseBuf = null;
+ buf = null;
+ }
+
+ /**
+ * @tests java.nio.CharBuffer#allocate(char[],int,int)
+ *
+ */
+ public void testWrappedCharBuffer_IllegalArg() {
+ char array[] = new char[BUFFER_LENGTH];
+ try {
+ CharBuffer.wrap(array, -1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ CharBuffer.wrap(array, BUFFER_LENGTH + 1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ CharBuffer.wrap(array, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ CharBuffer.wrap(array, 0, BUFFER_LENGTH + 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ CharBuffer.wrap(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ CharBuffer.wrap(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ CharBuffer.wrap((char[])null, -1, 0);
+ fail("Should throw NPE"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest2.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest2.java
new file mode 100644
index 0000000..c0a4aac
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedCharBufferTest2.java
@@ -0,0 +1,129 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.BufferOverflowException;
+import java.nio.CharBuffer;
+import java.nio.ReadOnlyBufferException;
+
+public class WrappedCharBufferTest2 extends ReadOnlyCharBufferTest {
+ protected static final String TEST_STRING = "123456789abcdef12345";
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = CharBuffer.wrap(TEST_STRING);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ baseBuf = null;
+ buf = null;
+ }
+
+ public void testWrappedCharSequence_IllegalArg() {
+ String str = TEST_STRING;
+ try {
+ CharBuffer.wrap(str, -1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ CharBuffer.wrap(str, 21, 21);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ CharBuffer.wrap(str, 2, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ CharBuffer.wrap(str, 0, 21);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ CharBuffer.wrap((String)null, -1, 21);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ public void testArray() {
+ try {
+ buf.array();
+ fail("Should throw UnsupportedOperationException"); //$NON-NLS-1$
+ } catch (UnsupportedOperationException e) {
+ }
+ }
+
+ public void testPutcharArrayintint() {
+ char array[] = new char[1];
+ try {
+ buf.put(array, 0, array.length);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((char[]) null, 0, 1);
+ fail("Should throw NullPointerException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException expected) {
+ } catch (NullPointerException expected) {
+ }
+ try {
+ buf.put(new char[buf.capacity() + 1], 0, buf.capacity() + 1);
+ fail("Should throw BufferOverflowException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException expected) {
+ } catch (BufferOverflowException expected) {
+ }
+ try {
+ buf.put(array, -1, array.length);
+ fail("Should throw IndexOutOfBoundsException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException expected) {
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ public void testPutCharBuffer() {
+ CharBuffer other = CharBuffer.allocate(1);
+ try {
+ buf.put(other);
+ fail("Should throw ReadOnlyBufferException"); //$NON-NLS-1$
+ } catch (ReadOnlyBufferException e) {
+ // expected
+ }
+ try {
+ buf.put((CharBuffer) null);
+ fail("Should throw NullPointerException"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ buf.put(buf);
+ fail("Should throw IllegalArgumentException"); //$NON-NLS-1$
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedDoubleBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedDoubleBufferTest.java
new file mode 100644
index 0000000..f970849
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedDoubleBufferTest.java
@@ -0,0 +1,87 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.DoubleBuffer;
+
+public class WrappedDoubleBufferTest extends DoubleBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = DoubleBuffer.wrap(new double[BUFFER_LENGTH]);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ baseBuf = null;
+ buf = null;
+ }
+
+ /**
+ * @tests java.nio.CharBuffer#allocate(char[],int,int)
+ *
+ */
+ public void testWrappedDoubleuffer_IllegalArg() {
+ double array[] = new double[20];
+ try {
+ DoubleBuffer.wrap(array, -1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ DoubleBuffer.wrap(array, 21, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ DoubleBuffer.wrap(array, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ DoubleBuffer.wrap(array, 0, 21);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ DoubleBuffer.wrap(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ DoubleBuffer.wrap(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ DoubleBuffer.wrap((double[])null, -1, 0);
+ fail("Should throw NPE"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ }
+
+ DoubleBuffer buf = DoubleBuffer.wrap(array, 2, 16);
+ assertEquals(buf.position(), 2);
+ assertEquals(buf.limit(), 18);
+ assertEquals(buf.capacity(), 20);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedFloatBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedFloatBufferTest.java
new file mode 100644
index 0000000..43b13c3
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedFloatBufferTest.java
@@ -0,0 +1,87 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.FloatBuffer;
+
+public class WrappedFloatBufferTest extends FloatBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = FloatBuffer.wrap(new float[BUFFER_LENGTH]);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ baseBuf = null;
+ buf = null;
+ }
+
+ /**
+ * @tests java.nio.CharBuffer#allocate(char[],int,int)
+ *
+ */
+ public void testWrappedFloatBuffer_IllegalArg() {
+ float array[] = new float[20];
+ try {
+ FloatBuffer.wrap(array, -1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ FloatBuffer.wrap(array, 21, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ FloatBuffer.wrap(array, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ FloatBuffer.wrap(array, 0, 21);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ FloatBuffer.wrap(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ FloatBuffer.wrap(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ FloatBuffer.wrap((float[])null, -1, 0);
+ fail("Should throw NPE"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ }
+
+ FloatBuffer buf = FloatBuffer.wrap(array, 2, 16);
+ assertEquals(buf.position(), 2);
+ assertEquals(buf.limit(), 18);
+ assertEquals(buf.capacity(), 20);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedIntBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedIntBufferTest.java
new file mode 100644
index 0000000..383e964
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedIntBufferTest.java
@@ -0,0 +1,87 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.IntBuffer;
+
+public class WrappedIntBufferTest extends IntBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = IntBuffer.wrap(new int[BUFFER_LENGTH]);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ baseBuf = null;
+ buf = null;
+ }
+
+ /**
+ * @tests java.nio.CharBuffer#allocate(char[],int,int)
+ *
+ */
+ public void testWrappedIntBuffer_IllegalArg() {
+ int array[] = new int[20];
+ try {
+ IntBuffer.wrap(array, -1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ IntBuffer.wrap(array, 21, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ IntBuffer.wrap(array, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ IntBuffer.wrap(array, 0, 21);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ IntBuffer.wrap(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ IntBuffer.wrap(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ IntBuffer.wrap((int[])null, -1, 0);
+ fail("Should throw NPE"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ }
+
+ IntBuffer buf = IntBuffer.wrap(array, 2, 16);
+ assertEquals(buf.position(), 2);
+ assertEquals(buf.limit(), 18);
+ assertEquals(buf.capacity(), 20);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedLongBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedLongBufferTest.java
new file mode 100644
index 0000000..581c912
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedLongBufferTest.java
@@ -0,0 +1,87 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.LongBuffer;
+
+public class WrappedLongBufferTest extends LongBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = LongBuffer.wrap(new long[BUFFER_LENGTH]);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ baseBuf = null;
+ buf = null;
+ }
+
+ /**
+ * @tests java.nio.CharBuffer#allocate(char[],int,int)
+ *
+ */
+ public void testWrappedLongBuffer_IllegalArg() {
+ long array[] = new long[20];
+ try {
+ LongBuffer.wrap(array, -1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ LongBuffer.wrap(array, 21, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ LongBuffer.wrap(array, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ LongBuffer.wrap(array, 0, 21);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ LongBuffer.wrap(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ LongBuffer.wrap(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ LongBuffer.wrap((long[])null, -1, 0);
+ fail("Should throw NPE"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ }
+
+ LongBuffer buf = LongBuffer.wrap(array, 2, 16);
+ assertEquals(buf.position(), 2);
+ assertEquals(buf.limit(), 18);
+ assertEquals(buf.capacity(), 20);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedShortBufferTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedShortBufferTest.java
new file mode 100644
index 0000000..9c6f781
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/WrappedShortBufferTest.java
@@ -0,0 +1,87 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio;
+
+import java.nio.ShortBuffer;
+
+public class WrappedShortBufferTest extends ShortBufferTest {
+ protected void setUp() throws Exception {
+ super.setUp();
+ buf = ShortBuffer.wrap(new short[BUFFER_LENGTH]);
+ loadTestData1(buf);
+ baseBuf = buf;
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ baseBuf = null;
+ buf = null;
+ }
+
+ /**
+ * @tests java.nio.CharBuffer#allocate(char[],int,int)
+ *
+ */
+ public void testWrappedShortBuffer_IllegalArg() {
+ short array[] = new short[20];
+ try {
+ ShortBuffer.wrap(array, -1, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ ShortBuffer.wrap(array, 21, 0);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ ShortBuffer.wrap(array, 0, -1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ ShortBuffer.wrap(array, 0, 21);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ ShortBuffer.wrap(array, Integer.MAX_VALUE, 1);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ ShortBuffer.wrap(array, 1, Integer.MAX_VALUE);
+ fail("Should throw Exception"); //$NON-NLS-1$
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ ShortBuffer.wrap((short[])null, -1, 0);
+ fail("Should throw NPE"); //$NON-NLS-1$
+ } catch (NullPointerException e) {
+ }
+
+ ShortBuffer buf = ShortBuffer.wrap(array, 2, 16);
+ assertEquals(buf.position(), 2);
+ assertEquals(buf.limit(), 18);
+ assertEquals(buf.capacity(), 20);
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AlreadyConnectedExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AlreadyConnectedExceptionTest.java
new file mode 100644
index 0000000..ac820a4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AlreadyConnectedExceptionTest.java
@@ -0,0 +1,54 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.AlreadyConnectedException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for AlreadyConnectedException
+ */
+public class AlreadyConnectedExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.AlreadyConnectedException#AlreadyConnectedException()}
+ */
+ public void test_Constructor() {
+ AlreadyConnectedException e = new AlreadyConnectedException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new AlreadyConnectedException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new AlreadyConnectedException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AsynchronousCloseExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AsynchronousCloseExceptionTest.java
new file mode 100644
index 0000000..123eb1f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/AsynchronousCloseExceptionTest.java
@@ -0,0 +1,54 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.AsynchronousCloseException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for AsynchronousCloseException
+ */
+public class AsynchronousCloseExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.AsynchronousCloseException#AsynchronousCloseException()}
+ */
+ public void test_Constructor() {
+ AsynchronousCloseException e = new AsynchronousCloseException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new AsynchronousCloseException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new AsynchronousCloseException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/CancelledKeyExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/CancelledKeyExceptionTest.java
new file mode 100644
index 0000000..7a73322
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/CancelledKeyExceptionTest.java
@@ -0,0 +1,54 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.CancelledKeyException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for CancelledKeyException
+ */
+public class CancelledKeyExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.CancelledKeyException#CancelledKeyException()}
+ */
+ public void test_Constructor() {
+ CancelledKeyException e = new CancelledKeyException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new CancelledKeyException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new CancelledKeyException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ChannelsTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ChannelsTest.java
new file mode 100644
index 0000000..4223fb8
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ChannelsTest.java
@@ -0,0 +1,622 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.io.Writer;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.nio.channels.Channels;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.IllegalBlockingModeException;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.nio.channels.WritableByteChannel;
+import java.nio.charset.Charset;
+import java.nio.charset.UnsupportedCharsetException;
+
+import tests.support.Support_PortManager;
+
+import junit.framework.TestCase;
+
+/**
+ * Note: the test case uses a temp text file named "test" which contains 31
+ * characters : "P@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]"
+ *
+ */
+
+public class ChannelsTest extends TestCase {
+ private static final String CODE_SET = "GB2312"; //$NON-NLS-1$
+
+ private static final String BAD_CODE_SET = "GB2313"; //$NON-NLS-1$
+
+ private FileInputStream fins;
+
+ private FileOutputStream fouts;
+
+ private final int writebufSize = 60;
+
+ private final int testNum = 10;
+
+ private final int fileSize = 31;// the file size
+
+ private File tmpFile;
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ // Make the test file same in every test
+ tmpFile = File.createTempFile("test","tmp");
+ tmpFile.deleteOnExit();
+ this.writeFileSame();
+ }
+
+ protected void tearDown() throws Exception {
+ if (null != this.fins) {
+ this.fins.close();
+ this.fins = null;
+ }
+ if (null != this.fouts) {
+ this.fouts.close();
+ this.fouts = null;
+ }
+
+ tmpFile.delete();
+ super.tearDown();
+
+ }
+
+ private void writeFileSame() throws IOException {
+ this.fouts = new FileOutputStream(tmpFile);
+ byte[] bit = new byte[1];
+ bit[0] = 80;
+ this.fouts.write(bit);
+ this.fouts.flush();
+ String writebuf = ""; //$NON-NLS-1$
+ for (int val = 0; val < this.writebufSize / 2; val++) {
+ writebuf = writebuf + ((char) (val + 64));
+ }
+ this.fouts.write(writebuf.getBytes());
+ }
+
+ /*
+ * This private method is to assert if the file size is the same as the
+ * compare Number in the test
+ */
+ private void assertFileSizeSame(File fileToTest, int compareNumber)
+ throws IOException {
+ FileInputStream file = new FileInputStream(fileToTest);
+ assertEquals(file.available(), compareNumber);
+ file.close();
+ }
+
+ // test if new Channel to input is null
+ public void testNewChannelInputStream_InputNull() throws IOException {
+ ByteBuffer byteBuf = ByteBuffer.allocate(this.testNum);
+ this.fins = null;
+ int readres = this.testNum;
+ try {
+ ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
+ assertNotNull(rbChannel);
+ readres = rbChannel.read(byteBuf);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ assertEquals(this.testNum, readres);
+ }
+
+ // test if buffer to read is null
+ public void testNewChannelInputStream_BufferNull() throws IOException {
+ ByteBuffer byteBuf = ByteBuffer.allocate(this.testNum);
+ int readres = this.testNum;
+ this.fins = new FileInputStream(tmpFile);
+ ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
+ assertNotNull(rbChannel);
+ try {
+ readres = rbChannel.read(null);
+ fail();
+ } catch (NullPointerException e) {
+ // correct
+ }
+ assertEquals(this.testNum, readres);
+ readres = 0;
+ try {
+ readres = rbChannel.read(byteBuf);
+ } catch (NullPointerException e) {
+ fail();
+ }
+ assertEquals(this.testNum, readres);
+ }
+
+ /*
+ * Test method for 'java.nio.channels.Channels.NewChannel'
+ */
+ public void testNewChannelInputStream() throws IOException {
+ int bufSize = 10;
+ int readres = 0;
+ byte[] byteArray = new byte[bufSize];
+ ByteBuffer byteBuf = ByteBuffer.allocate(bufSize);
+ this.fins = new FileInputStream(tmpFile);
+ readres = this.fins.read(byteArray);
+
+ assertEquals(bufSize, readres);
+ assertFalse(0 == this.fins.available());
+
+ ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
+ // fins still reads.
+ assertFalse(0 == this.fins.available());
+ readres = this.fins.read(byteArray);
+ assertEquals(bufSize, readres);
+
+ // rbChannel also reads.
+ assertNotNull(rbChannel);
+ readres = rbChannel.read(byteBuf);
+
+ assertEquals(bufSize, readres);
+ InputStream ins = Channels.newInputStream(rbChannel);
+ assertNotNull(ins);
+ assertEquals(0, ins.available());
+ }
+
+ // test if fout to change is null
+ public void testNewChannelOutputStream_inputNull() throws IOException {
+ int writeres = this.testNum;
+ ByteBuffer writebuf = ByteBuffer.allocate(this.writebufSize);
+ for (int val = 0; val < this.writebufSize / 2; val++) {
+ writebuf.putChar((char) (val + 64));
+ }
+ this.fouts = null;
+ try {
+ WritableByteChannel rbChannel = Channels.newChannel(this.fouts);
+ writeres = rbChannel.write(writebuf);
+ assertEquals(0, writeres);
+
+ writebuf.flip();
+ writeres = rbChannel.write(writebuf);
+ fail("Should throw NPE.");
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ // test if write buf is null
+ public void testNewChannelOutputStream_BufNull() throws IOException {
+ int writeres = this.testNum;
+ ByteBuffer writebuf = null;
+ try {
+ this.fouts = new FileOutputStream(tmpFile);
+ } catch (FileNotFoundException e) {
+ fail();
+ }
+
+ WritableByteChannel rbChannel = Channels.newChannel(this.fouts);
+ try {
+ writeres = rbChannel.write(writebuf);
+ fail();
+ } catch (NullPointerException e) {
+ // correct
+ }
+ assertEquals(this.testNum, writeres);
+ }
+
+ /*
+ * Test method for 'java.nio.channels.Channels.NewChannel(OutputStream)'
+ */
+ public void testNewChannelOutputStream() throws IOException {
+ int writeNum = 0;
+ ByteBuffer writebuf = ByteBuffer.allocateDirect(this.writebufSize);
+ for (int val = 0; val < this.writebufSize / 2; val++) {
+ writebuf.putChar((char) (val + 64));
+ }
+ this.fouts = new FileOutputStream(tmpFile);
+ WritableByteChannel testChannel = this.fouts.getChannel();
+ WritableByteChannel rbChannel = Channels.newChannel(this.fouts);
+
+ assertTrue(testChannel.isOpen());
+ assertTrue(rbChannel.isOpen());
+
+ byte[] bit = new byte[1];
+ bit[0] = 80;
+ this.fouts.write(bit);
+ this.fouts.flush();
+ this.fins = new FileInputStream(tmpFile);
+ assertEquals(this.fins.available(), 1);
+ this.fins.close();
+
+ writeNum = rbChannel.write(writebuf);
+ // write success ,but output null
+ assertEquals(0, writeNum);
+ // close of fouts does not affect on channel
+ this.fouts.close();
+ writeNum = rbChannel.write(writebuf);
+ assertEquals(0, writeNum);
+ try {
+ writeNum = testChannel.write(writebuf);
+ fail();
+ } catch (ClosedChannelException e) {
+ // correct
+ }
+ assertEquals(0, writeNum);
+ // close of rbchannel does affect on testchannel(same channel)
+ rbChannel.close();
+ try {
+ writeNum = testChannel.write(writebuf);
+ fail();
+ } catch (ClosedChannelException e) {
+ // correct
+ }
+ }
+
+ public void testNewInputStreamReadableByteChannel_InputNull()
+ throws Exception {
+ byte[] readbuf = new byte[this.testNum];
+ this.fins = new FileInputStream(tmpFile);
+ ReadableByteChannel readbc = this.fins.getChannel();
+ assertEquals(this.fileSize, this.fins.available());
+ assertTrue(readbc.isOpen());
+
+ try {
+ InputStream testins = Channels.newInputStream(null);
+ assertNotNull(testins);
+ testins.read(readbuf);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void testNewInputStreamReadableByteChannel() throws Exception {
+ ByteBuffer readbcbuf = ByteBuffer.allocateDirect(this.testNum);
+ byte[] readbuf = new byte[this.testNum];
+ this.fins = new FileInputStream(tmpFile);
+ ReadableByteChannel readbc = this.fins.getChannel();
+ assertEquals(this.fileSize, this.fins.available());
+ assertTrue(readbc.isOpen());
+ InputStream testins = Channels.newInputStream(readbc);
+ // read in testins and fins use the same pointer
+ testins.read(readbuf);
+ assertEquals(this.fins.available(), this.fileSize - this.testNum);
+ int readNum = readbc.read(readbcbuf);
+ assertEquals(readNum, this.testNum);
+ assertEquals(this.fins.available(), this.fileSize - this.testNum * 2);
+ testins.read(readbuf);
+ assertEquals(this.fins.available(), this.fileSize - this.testNum * 3);
+ // readbc.close() affect testins
+ readbc.close();
+ assertFalse(readbc.isOpen());
+ try {
+ testins.read(readbuf);
+ fail();
+ } catch (ClosedChannelException e) {
+ // correct
+ }
+ }
+
+ public void testNewOutputStreamWritableByteChannel_InputNull()
+ throws Exception {
+ byte[] writebuf = new byte[this.testNum];
+ try {
+ OutputStream testouts = Channels.newOutputStream(null);
+ assertNotNull(testouts);
+ testouts.write(writebuf);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ try {
+ WritableByteChannel writebc = Channels.newChannel((OutputStream) null);
+ assertTrue(writebc.isOpen());
+ OutputStream testoutputS = Channels.newOutputStream(writebc);
+ testoutputS.write(writebuf);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void testNewOutputStreamWritableByteChannel() throws Exception {
+ byte[] writebuf = new byte[this.testNum];
+ ByteBuffer writebcbuf = ByteBuffer.allocateDirect(this.testNum);
+ this.fouts = new FileOutputStream(tmpFile);
+ WritableByteChannel writebc = this.fouts.getChannel();
+
+ assertTrue(writebc.isOpen());
+ OutputStream testouts = Channels.newOutputStream(writebc);
+
+ // read in testins and fins use the same pointer
+ testouts.write(writebuf);
+ this.assertFileSizeSame(tmpFile, this.testNum);
+ writebc.write(writebcbuf);
+ this.assertFileSizeSame(tmpFile, this.testNum * 2);
+ testouts.write(writebuf);
+ this.assertFileSizeSame(tmpFile, this.testNum * 3);
+ // readbc.close() affect testins
+ writebc.close();
+ assertFalse(writebc.isOpen());
+ try {
+ testouts.write(writebuf);
+ fail();
+ } catch (ClosedChannelException e) {
+ // correct
+ }
+ }
+
+ public void testnewReaderCharsetError() throws Exception {
+ this.fins = new FileInputStream(tmpFile);
+
+ ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
+ try {
+ Channels.newReader(rbChannel, Charset.forName(BAD_CODE_SET)
+ .newDecoder(), //$NON-NLS-1$
+ -1);
+ fail();
+ } catch (UnsupportedCharsetException e) {
+ // correct
+ }
+ }
+
+ public void testnewWriterCharsetError() throws Exception {
+ this.fouts = new FileOutputStream(tmpFile);
+ WritableByteChannel wbChannel = Channels.newChannel(this.fouts);
+ try {
+ Channels.newWriter(wbChannel, Charset.forName(BAD_CODE_SET)
+ .newEncoder(), -1);
+ fail();
+ } catch (UnsupportedCharsetException e) {
+ // correct
+ }
+ }
+
+ /*
+ * Test method for
+ * 'java.nio.channels.Channels.newReader(ReadableByteChannel, String)'
+ */
+ public void testNewReaderReadableByteChannelString_InputNull()
+ throws IOException {
+ int bufSize = this.testNum;
+ int readres = 0;
+ CharBuffer charBuf = CharBuffer.allocate(bufSize);
+ this.fins = new FileInputStream(tmpFile);
+ // channel null
+ Reader testReader;
+ try {
+ testReader = Channels.newReader(null, Charset.forName(CODE_SET).newDecoder(), -1);
+ assertNotNull(testReader);
+ assertFalse(testReader.ready());
+ readres = testReader.read((CharBuffer) null);
+ fail();
+ } catch (NullPointerException e) {
+ // correct
+ }
+ assertEquals(0, readres);
+
+ this.fins = null;
+ // channel with null inputs
+ try {
+ ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
+ testReader = Channels.newReader(rbChannel, Charset.forName(CODE_SET).newDecoder(), -1);
+ assertNotNull(testReader);
+ assertFalse(testReader.ready());
+ readres = testReader.read(charBuf);
+ fail();
+ } catch (NullPointerException e) {
+ // correct
+ }
+ }
+
+ /*
+ * Test method for
+ * 'java.nio.channels.Channels.newReader(ReadableByteChannel, String)'
+ */
+ public void testNewReaderReadableByteChannelString_internalBufferZero()
+ throws IOException {
+ int bufSize = this.testNum;
+ int readres = 0;
+ CharBuffer charBuf = CharBuffer.allocate(bufSize);
+ this.fins = new FileInputStream(tmpFile);
+ // channel null
+ Reader testReader;
+ try {
+ testReader = Channels.newReader(null, Charset.forName(CODE_SET).newDecoder(), 0);
+ assertNotNull(testReader);
+ assertFalse(testReader.ready());
+ readres = testReader.read((CharBuffer) null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ assertEquals(0, readres);
+
+ this.fins = null;
+ // channel with null inputs
+ try {
+ ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
+ testReader = Channels.newReader(rbChannel, Charset.forName(CODE_SET).newDecoder(), -1);
+ assertNotNull(testReader);
+ assertFalse(testReader.ready());
+ readres = testReader.read(charBuf);
+ fail();
+ } catch (NullPointerException e) {
+ // correct
+ }
+ }
+
+ /*
+ * Test method for
+ * 'java.nio.channels.Channels.newReader(ReadableByteChannel, String)'
+ */
+ public void testNewReaderReadableByteChannelString() throws IOException {
+ int bufSize = this.testNum;
+ int readres = 0;
+ CharBuffer charBuf = CharBuffer.allocate(bufSize);
+ this.fins = new FileInputStream(tmpFile);
+ ReadableByteChannel rbChannel = Channels.newChannel(this.fins);
+ Reader testReader = Channels.newReader(rbChannel, Charset.forName(
+ CODE_SET).newDecoder(), //$NON-NLS-1$
+ -1);
+ Reader testReader_s = Channels.newReader(rbChannel, CODE_SET); //$NON-NLS-1$
+
+ assertEquals(this.fileSize, this.fins.available());
+ // not ready...
+ assertFalse(testReader.ready());
+ assertFalse(testReader_s.ready());
+ // still reads
+ readres = testReader.read(charBuf);
+ assertEquals(bufSize, readres);
+ assertEquals(0, this.fins.available());
+
+ try {
+ readres = testReader.read((CharBuffer) null);
+ fail();
+ } catch (NullPointerException e) {
+ // correct
+ }
+
+ readres = testReader_s.read(charBuf);
+ assertEquals(0, readres);
+ assertTrue(testReader.ready());
+ assertFalse(testReader_s.ready());
+ }
+
+ /*
+ * Zero-Buffer
+ */
+ public void testNewWriterWritableByteChannelString_internalBufZero()
+ throws IOException {
+
+ String writebuf = ""; //$NON-NLS-1$
+ for (int val = 0; val < this.writebufSize / 2; val++) {
+ writebuf = writebuf + ((char) (val + 64));
+ }
+ // null channel
+ try {
+ Writer testWriter = Channels.newWriter(null, Charset.forName(CODE_SET).newEncoder(), -1);
+ } catch (NullPointerException expected) {
+ }
+
+ // channel with null input
+ this.fouts = null;
+ try {
+ WritableByteChannel wbChannel = Channels.newChannel(this.fouts);
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ /*
+ * this test cannot be passed when buffer set to 0!
+ */
+ public void testNewWriterWritableByteChannelString_InputNull()
+ throws IOException {
+ this.fouts = new FileOutputStream(tmpFile);
+ WritableByteChannel wbChannel = Channels.newChannel(this.fouts);
+ Writer testWriter = Channels.newWriter(wbChannel, Charset.forName(
+ CODE_SET).newEncoder(), //$NON-NLS-1$
+ 1);
+
+ String writebuf = ""; //$NON-NLS-1$
+ for (int val = 0; val < this.writebufSize / 2; val++) {
+ writebuf = writebuf + ((char) (val + 64));
+ }
+ // can write to buffer
+ testWriter.write(writebuf);
+ testWriter.flush();
+ testWriter.close();
+
+ }
+
+ /*
+ * Test method for
+ * 'java.nio.channels.Channels.newWriter(WritableByteChannel, String)'
+ */
+ public void testNewWriterWritableByteChannelString() throws IOException {
+ this.fouts = new FileOutputStream(tmpFile);
+ WritableByteChannel wbChannel = Channels.newChannel(this.fouts);
+ Writer testWriter = Channels.newWriter(wbChannel, CODE_SET); //$NON-NLS-1$
+ Writer testWriter_s = Channels.newWriter(wbChannel, Charset.forName(
+ CODE_SET).newEncoder(), //$NON-NLS-1$
+ -1);
+
+ String writebuf = ""; //$NON-NLS-1$
+ for (int val = 0; val < this.writebufSize / 2; val++) {
+ writebuf = writebuf + ((char) (val + 64));
+ }
+ byte[] bit = new byte[1];
+ bit[0] = 80;
+ this.fouts.write(bit);
+ this.assertFileSizeSame(tmpFile, 1);
+
+ // writer continues to write after '1',what the fouts write
+ testWriter.write(writebuf);
+ testWriter.flush();
+ this.assertFileSizeSame(tmpFile, this.writebufSize / 2 + 1);
+ // testwriter_s does not know if testwrite writes
+ testWriter_s.write(writebuf);
+ testWriter.flush();
+ this.assertFileSizeSame(tmpFile, this.writebufSize / 2 + 1);
+ // testwriter_s even does not know if himself writes?
+ testWriter_s.write(writebuf);
+ testWriter.flush();
+ this.assertFileSizeSame(tmpFile, this.writebufSize / 2 + 1);
+
+ // close the fouts, no longer writable for testWriter
+ for (int val = 0; val < this.writebufSize; val++) {
+ writebuf = writebuf + ((char) (val + 64));
+ }
+ this.fouts.close();
+ testWriter_s.write(writebuf);
+ testWriter.flush();
+ this.assertFileSizeSame(tmpFile, this.writebufSize / 2 + 1);
+ }
+
+ /**
+ * @tests java.nio.channels.Channels#newReader(ReadableByteChannel channel,
+ * String charsetName)
+ */
+ public void test_newReader_LReadableByteChannel_LString()
+ throws IOException {
+ InetSocketAddress localAddr = new InetSocketAddress("127.0.0.1",
+ Support_PortManager.getNextPort());
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(localAddr);
+
+ SocketChannel sc = SocketChannel.open();
+ sc.connect(localAddr);
+ sc.configureBlocking(false);
+ assertFalse(sc.isBlocking());
+
+ ssc.accept().close();
+ ssc.close();
+ assertFalse(sc.isBlocking());
+
+ Reader reader = Channels.newReader(sc, "UTF16");
+ try {
+ int i = reader.read();
+ fail("should throw IllegalBlockingModeException");
+ } catch (IllegalBlockingModeException expected) {
+ }
+
+ try {
+ Channels.newInputStream(sc).read();
+ fail("should throw IllegalBlockingModeException");
+ } catch (IllegalBlockingModeException expected) {
+ }
+
+ sc.close();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedByInterruptExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedByInterruptExceptionTest.java
new file mode 100644
index 0000000..aba37ec
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedByInterruptExceptionTest.java
@@ -0,0 +1,53 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.ClosedByInterruptException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for ClosedByInterruptException
+ */
+public class ClosedByInterruptExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.ClosedByInterruptException#ClosedByInterruptException()}
+ */
+ public void test_Constructor() {
+ ClosedByInterruptException e = new ClosedByInterruptException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new ClosedByInterruptException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new ClosedByInterruptException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedChannelExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedChannelExceptionTest.java
new file mode 100644
index 0000000..3ba322f
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedChannelExceptionTest.java
@@ -0,0 +1,54 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.ClosedChannelException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for ClosedChannelException
+ */
+public class ClosedChannelExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.ClosedChannelException#ClosedChannelException()}
+ */
+ public void test_Constructor() {
+ ClosedChannelException e = new ClosedChannelException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new ClosedChannelException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new ClosedChannelException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedSelectorExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedSelectorExceptionTest.java
new file mode 100644
index 0000000..745d697
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ClosedSelectorExceptionTest.java
@@ -0,0 +1,54 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.ClosedSelectorException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for ClosedSelectorException
+ */
+public class ClosedSelectorExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.ClosedSelectorException#ClosedSelectorException()}
+ */
+ public void test_Constructor() {
+ ClosedSelectorException e = new ClosedSelectorException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new ClosedSelectorException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new ClosedSelectorException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ConnectionPendingExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ConnectionPendingExceptionTest.java
new file mode 100644
index 0000000..0e909ba
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ConnectionPendingExceptionTest.java
@@ -0,0 +1,54 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.ConnectionPendingException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for ConnectionPendingException
+ */
+public class ConnectionPendingExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.ConnectionPendingException#ConnectionPendingException()}
+ */
+ public void test_Constructor() {
+ ConnectionPendingException e = new ConnectionPendingException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new ConnectionPendingException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new ConnectionPendingException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileChannelLockingTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileChannelLockingTest.java
new file mode 100644
index 0000000..cb34343
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileChannelLockingTest.java
@@ -0,0 +1,208 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.channels.FileChannel;
+import java.nio.channels.FileLock;
+import java.nio.channels.NonReadableChannelException;
+import java.nio.channels.NonWritableChannelException;
+import java.nio.channels.OverlappingFileLockException;
+
+import junit.framework.TestCase;
+
+/**
+ * API tests for the NIO FileChannel locking APIs
+ */
+public class FileChannelLockingTest extends TestCase {
+
+ private FileChannel readOnlyChannel;
+
+ private FileChannel writeOnlyChannel;
+
+ private FileChannel readWriteChannel;
+
+ private final String CONTENT = "The best things in life are nearest: Breath in your nostrils, light in your eyes, "
+ + "flowers at your feet, duties at your hand, the path of right just before you. Then do not grasp at the stars, "
+ + "but do life's plain, common work as it comes, certain that daily duties and daily bread are the sweetest "
+ + " things in life.--Robert Louis Stevenson";
+
+ protected void setUp() throws Exception {
+ super.setUp();
+
+ // Create a three temporary files with content.
+ File[] tempFiles = new File[3];
+ for (int i = 0; i < tempFiles.length; i++) {
+ tempFiles[i] = File.createTempFile("testing", "tmp");
+ tempFiles[i].deleteOnExit();
+ FileWriter writer = new FileWriter(tempFiles[i]);
+ writer.write(CONTENT);
+ writer.close();
+ }
+
+ // Open read, write, and read/write channels on the temp files.
+ FileInputStream fileInputStream = new FileInputStream(tempFiles[0]);
+ readOnlyChannel = fileInputStream.getChannel();
+
+ FileOutputStream fileOutputStream = new FileOutputStream(tempFiles[1]);
+ writeOnlyChannel = fileOutputStream.getChannel();
+
+ RandomAccessFile randomAccessFile = new RandomAccessFile(tempFiles[2],
+ "rw");
+ readWriteChannel = randomAccessFile.getChannel();
+ }
+
+ protected void tearDown() throws IOException {
+ if (readOnlyChannel != null) {
+ readOnlyChannel.close();
+ }
+ if (writeOnlyChannel != null) {
+ writeOnlyChannel.close();
+ }
+ if (readWriteChannel != null) {
+ readWriteChannel.close();
+ }
+ }
+
+ public void test_illegalLocks() throws IOException {
+ // Cannot acquire an exclusive lock on a read-only file channel
+ try {
+ readOnlyChannel.lock();
+ fail("Acquiring a full exclusive lock on a read only channel should fail.");
+ } catch (NonWritableChannelException ex) {
+ // Expected.
+ }
+
+ // Cannot get a shared lock on a write-only file channel.
+ try {
+ writeOnlyChannel.lock(1, 10, true);
+ fail("Acquiring a shared lock on a write-only channel should fail.");
+ } catch (NonReadableChannelException ex) {
+ // expected
+ }
+ }
+
+ public void test_lockReadWrite() throws IOException {
+ // Acquire an exclusive lock across the entire file.
+ FileLock flock = readWriteChannel.lock();
+ if (flock != null) {
+ flock.release();
+ }
+ }
+
+ public void test_illegalLockParameters() throws IOException {
+ // Cannot lock negative positions
+ try {
+ readOnlyChannel.lock(-1, 10, true);
+ fail("Passing illegal args to lock should fail.");
+ } catch (IllegalArgumentException ex) {
+ // expected
+ }
+ try {
+ writeOnlyChannel.lock(-1, 10, false);
+ fail("Passing illegal args to lock should fail.");
+ } catch (IllegalArgumentException ex) {
+ // expected
+ }
+ try {
+ readWriteChannel.lock(-1, 10, false);
+ fail("Passing illegal args to lock should fail.");
+ } catch (IllegalArgumentException ex) {
+ // expected
+ }
+
+ // Lock a range at the front, shared.
+ FileLock flock1 = readWriteChannel.lock(22, 110, true);
+
+ // Try to acquire an overlapping lock.
+ try {
+ readWriteChannel.lock(75, 210, true);
+ } catch (OverlappingFileLockException exception) {
+ // expected
+ flock1.release();
+ }
+ }
+
+ public void test_lockLLZ() throws IOException {
+ // Lock a range at the front, non-shared.
+ FileLock flock1 = readWriteChannel.lock(0, 10, false);
+
+ // Lock a shared range further in the same file.
+ FileLock flock2 = readWriteChannel.lock(22, 100, true);
+
+ // The spec allows the impl to refuse shared locks
+ flock1.release();
+ flock2.release();
+ }
+
+ public void test_tryLock() throws IOException {
+ try {
+ readOnlyChannel.tryLock();
+ fail("Acquiring a full exclusive lock on a read channel should have thrown an exception.");
+ } catch (NonWritableChannelException ex) {
+ // Expected.
+ }
+ }
+
+ public void test_tryLockLLZ() throws IOException {
+ // It is illegal to request an exclusive lock on a read-only channel
+ try {
+ readOnlyChannel.tryLock(0, 99, false);
+ fail("Acquiring exclusive lock on read-only channel should fail");
+ } catch (NonWritableChannelException ex) {
+ // Expected
+ }
+
+ // It is invalid to request a lock starting before the file start
+ try {
+ readOnlyChannel.tryLock(-99, 0, true);
+ fail("Acquiring an illegal lock value should fail.");
+ } catch (IllegalArgumentException ex) {
+ // expected
+ }
+
+ // Acquire a valid lock
+ FileLock tmpLock = readOnlyChannel.tryLock(0, 10, true);
+ assertTrue(tmpLock.isValid());
+ tmpLock.release();
+
+ // Acquire another valid lock -- and don't release it yet
+ FileLock lock = readOnlyChannel.tryLock(10, 788, true);
+ assertTrue(lock.isValid());
+
+ // Overlapping locks are illegal
+ try {
+ readOnlyChannel.tryLock(1, 23, true);
+ fail("Acquiring an overlapping lock should fail.");
+ } catch (OverlappingFileLockException ex) {
+ // Expected
+ }
+
+ // Adjacent locks are legal
+ FileLock adjacentLock = readOnlyChannel.tryLock(1, 3, true);
+ assertTrue(adjacentLock.isValid());
+ adjacentLock.release();
+
+ // Release longer lived lock
+ lock.release();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileChannelTest.java
new file mode 100644
index 0000000..9a89f7e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileChannelTest.java
@@ -0,0 +1,3121 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.io.UnsupportedEncodingException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.BufferOverflowException;
+import java.nio.ByteBuffer;
+import java.nio.MappedByteBuffer;
+import java.nio.ReadOnlyBufferException;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.DatagramChannel;
+import java.nio.channels.FileChannel;
+import java.nio.channels.FileLock;
+import java.nio.channels.NonReadableChannelException;
+import java.nio.channels.NonWritableChannelException;
+import java.nio.channels.OverlappingFileLockException;
+import java.nio.channels.Pipe;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.nio.channels.WritableByteChannel;
+import java.nio.channels.FileChannel.MapMode;
+import java.util.Arrays;
+
+import junit.framework.TestCase;
+
+public class FileChannelTest extends TestCase {
+
+ private static final int CAPACITY = 100;
+
+ private static final int LIMITED_CAPACITY = 2;
+
+ private static final int TIME_OUT = 10000;
+
+ private static final String CONTENT = "MYTESTSTRING needs to be a little long";
+
+ private static final byte[] TEST_BYTES;
+
+ private static final byte[] CONTENT_AS_BYTES;
+
+ private static final int CONTENT_AS_BYTES_LENGTH;
+
+ static {
+ try {
+ TEST_BYTES = "test".getBytes("iso8859-1");
+ CONTENT_AS_BYTES = CONTENT.getBytes("iso8859-1");
+ CONTENT_AS_BYTES_LENGTH = CONTENT_AS_BYTES.length;
+ } catch (UnsupportedEncodingException e) {
+ throw new Error(e);
+ }
+ }
+
+ private static final int CONTENT_LENGTH = CONTENT.length();
+
+ private FileChannel readOnlyFileChannel;
+
+ private FileChannel writeOnlyFileChannel;
+
+ private FileChannel readWriteFileChannel;
+
+ private File fileOfReadOnlyFileChannel;
+
+ private File fileOfWriteOnlyFileChannel;
+
+ private File fileOfReadWriteFileChannel;
+
+ private ReadableByteChannel readByteChannel;
+
+ private WritableByteChannel writableByteChannel;
+
+ private DatagramChannel datagramChannelSender;
+
+ private DatagramChannel datagramChannelReceiver;
+
+ private ServerSocketChannel serverSocketChannel;
+
+ private SocketChannel socketChannelSender;
+
+ private SocketChannel socketChannelReceiver;
+
+ private Pipe pipe;
+
+ // to read content from FileChannel
+ private FileInputStream fis;
+
+ private FileLock fileLock;
+
+ protected void setUp() throws Exception {
+ fileOfReadOnlyFileChannel = File.createTempFile(
+ "File_of_readOnlyFileChannel", "tmp");
+ fileOfReadOnlyFileChannel.deleteOnExit();
+ fileOfWriteOnlyFileChannel = File.createTempFile(
+ "File_of_writeOnlyFileChannel", "tmp");
+ fileOfWriteOnlyFileChannel.deleteOnExit();
+ fileOfReadWriteFileChannel = File.createTempFile(
+ "File_of_readWriteFileChannel", "tmp");
+ fileOfReadWriteFileChannel.deleteOnExit();
+ fis = null;
+ fileLock = null;
+ readOnlyFileChannel = new FileInputStream(fileOfReadOnlyFileChannel)
+ .getChannel();
+ writeOnlyFileChannel = new FileOutputStream(fileOfWriteOnlyFileChannel)
+ .getChannel();
+ readWriteFileChannel = new RandomAccessFile(fileOfReadWriteFileChannel,
+ "rw").getChannel();
+ }
+
+ protected void tearDown() {
+ if (null != readOnlyFileChannel) {
+ try {
+ readOnlyFileChannel.close();
+ } catch (IOException e) {
+ // do nothing
+ }
+ }
+ if (null != writeOnlyFileChannel) {
+ try {
+ writeOnlyFileChannel.close();
+ } catch (IOException e) {
+ // do nothing
+ }
+ }
+ if (null != readWriteFileChannel) {
+ try {
+ readWriteFileChannel.close();
+ } catch (IOException e) {
+ // do nothing
+ }
+ }
+ if (null != fis) {
+ try {
+ fis.close();
+ } catch (IOException e) {
+ // do nothing
+ }
+ }
+
+ if (null != fileLock) {
+ try {
+ fileLock.release();
+ } catch (IOException e) {
+ // do nothing
+ }
+ }
+
+ if (null != fileOfReadOnlyFileChannel) {
+ fileOfReadOnlyFileChannel.delete();
+ }
+ if (null != fileOfWriteOnlyFileChannel) {
+ fileOfWriteOnlyFileChannel.delete();
+ }
+ if (null != fileOfReadWriteFileChannel) {
+ fileOfReadWriteFileChannel.delete();
+ }
+ if (null != datagramChannelSender) {
+ try {
+ datagramChannelSender.close();
+ } catch (IOException e) {
+ // do nothing
+ }
+ }
+ if (null != datagramChannelReceiver) {
+ try {
+ datagramChannelReceiver.close();
+ } catch (IOException e) {
+ // do nothing
+ }
+ }
+ if (null != serverSocketChannel) {
+ try {
+ serverSocketChannel.close();
+ } catch (IOException e) {
+ // do nothing
+ }
+ }
+ if (null != socketChannelSender) {
+ try {
+ socketChannelSender.close();
+ } catch (IOException e) {
+ // do nothing
+ }
+ }
+ if (null != socketChannelReceiver) {
+ try {
+ socketChannelReceiver.close();
+ } catch (IOException e) {
+ // do nothing
+ }
+ }
+ if (null != pipe) {
+ if (null != pipe.source()) {
+ try {
+ pipe.source().close();
+ } catch (IOException e) {
+ // do nothing
+ }
+ }
+ if (null != pipe.sink()) {
+ try {
+ pipe.sink().close();
+ } catch (IOException e) {
+ // do nothing
+ }
+ }
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#force(boolean)
+ */
+ public void test_forceJ() throws Exception {
+ ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES);
+ writeOnlyFileChannel.write(writeBuffer);
+ writeOnlyFileChannel.force(true);
+
+ byte[] readBuffer = new byte[CONTENT_AS_BYTES_LENGTH];
+ fis = new FileInputStream(fileOfWriteOnlyFileChannel);
+ fis.read(readBuffer);
+ assertTrue(Arrays.equals(CONTENT_AS_BYTES, readBuffer));
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#force(boolean)
+ */
+ public void test_forceJ_closed() throws Exception {
+ writeOnlyFileChannel.close();
+ try {
+ writeOnlyFileChannel.force(true);
+ fail();
+ } catch (ClosedChannelException expected) {
+ }
+
+ try {
+ writeOnlyFileChannel.force(false);
+ fail();
+ } catch (ClosedChannelException expected) {
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#force(boolean)
+ */
+ public void test_forceJ_ReadOnlyChannel() throws Exception {
+ // force on a read only file channel has no effect.
+ readOnlyFileChannel.force(true);
+ readOnlyFileChannel.force(false);
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#position()
+ */
+ public void test_position_Init() throws Exception {
+ assertEquals(0, readOnlyFileChannel.position());
+ assertEquals(0, writeOnlyFileChannel.position());
+ assertEquals(0, readWriteFileChannel.position());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#position()
+ */
+ public void test_position_ReadOnly() throws Exception {
+ writeDataToFile(fileOfReadOnlyFileChannel);
+
+ assertEquals(0, readOnlyFileChannel.position());
+ ByteBuffer readBuffer = ByteBuffer.allocate(CONTENT_LENGTH);
+ readOnlyFileChannel.read(readBuffer);
+ assertEquals(CONTENT_LENGTH, readOnlyFileChannel.position());
+ }
+
+ /**
+ * Initializes test file.
+ *
+ * @param file
+ * @throws FileNotFoundException
+ * @throws IOException
+ */
+ private void writeDataToFile(File file) throws FileNotFoundException,
+ IOException {
+ FileOutputStream fos = new FileOutputStream(file);
+ try {
+ fos.write(CONTENT_AS_BYTES);
+ } finally {
+ fos.close();
+ }
+ }
+
+ /**
+ * Initializes large test file.
+ *
+ * @param file the file to be written
+ * @param size the content size to be written
+ * @throws FileNotFoundException
+ * @throws IOException
+ */
+ private void writeLargeDataToFile(File file, int size) throws FileNotFoundException,
+ IOException {
+ FileOutputStream fos = new FileOutputStream(file);
+ byte[] buf = new byte[size];
+
+ try {
+ // we don't care about content - just need a particular file size
+ fos.write(buf);
+ } finally {
+ fos.close();
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#position()
+ */
+ public void test_position_WriteOnly() throws Exception {
+ ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES);
+ writeOnlyFileChannel.write(writeBuffer);
+ assertEquals(CONTENT_LENGTH, writeOnlyFileChannel.position());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#position()
+ */
+ public void test_position_ReadWrite() throws Exception {
+ writeDataToFile(fileOfReadWriteFileChannel);
+
+ assertEquals(0, readWriteFileChannel.position());
+ ByteBuffer readBuffer = ByteBuffer.allocate(CONTENT_LENGTH);
+ readWriteFileChannel.read(readBuffer);
+ assertEquals(CONTENT_LENGTH, readWriteFileChannel.position());
+
+ ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES);
+ readWriteFileChannel.write(writeBuffer);
+ assertEquals(CONTENT_LENGTH * 2, readWriteFileChannel.position());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#position()
+ */
+ public void test_position_Closed() throws Exception {
+ readOnlyFileChannel.close();
+ try {
+ readOnlyFileChannel.position();
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException expected) {
+ }
+
+ writeOnlyFileChannel.close();
+ try {
+ writeOnlyFileChannel.position();
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException expected) {
+ }
+
+ readWriteFileChannel.close();
+ try {
+ readWriteFileChannel.position();
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException expected) {
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#position(long)
+ */
+ public void test_positionJ_Closed() throws Exception {
+ final long POSITION = 100;
+
+ readOnlyFileChannel.close();
+ try {
+ readOnlyFileChannel.position(POSITION);
+ fail();
+ } catch (ClosedChannelException expected) {
+ }
+
+ writeOnlyFileChannel.close();
+ try {
+ writeOnlyFileChannel.position(POSITION);
+ fail();
+ } catch (ClosedChannelException expected) {
+ }
+
+ readWriteFileChannel.close();
+ try {
+ readWriteFileChannel.position(POSITION);
+ fail();
+ } catch (ClosedChannelException expected) {
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#position(long)
+ */
+ public void test_positionJ_Negative() throws Exception {
+ final long NEGATIVE_POSITION = -1;
+ try {
+ readOnlyFileChannel.position(NEGATIVE_POSITION);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ writeOnlyFileChannel.position(NEGATIVE_POSITION);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ readWriteFileChannel.position(NEGATIVE_POSITION);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#position(long)
+ */
+ public void test_positionJ_ReadOnly() throws Exception {
+ writeDataToFile(fileOfReadOnlyFileChannel);
+
+ // set the position of the read only file channel to POSITION
+ final int POSITION = 4;
+ readOnlyFileChannel.position(POSITION);
+
+ // reads the content left to readBuffer through read only file channel
+ ByteBuffer readBuffer = ByteBuffer.allocate(CONTENT_LENGTH);
+ int count = readOnlyFileChannel.read(readBuffer);
+ assertEquals(CONTENT_LENGTH - POSITION, count);
+
+ // asserts the content read is the part which stays beyond the POSITION
+ readBuffer.flip();
+ int i = POSITION;
+ while (readBuffer.hasRemaining()) {
+ assertEquals(CONTENT_AS_BYTES[i], readBuffer.get());
+ i++;
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#position(long)
+ */
+ public void test_positionJ_WriteOnly() throws Exception {
+ writeDataToFile(fileOfWriteOnlyFileChannel);
+
+ // init data to write
+ ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES);
+
+ // set the position of the write only file channel to POSITION
+ final int POSITION = 4;
+ writeOnlyFileChannel.position(POSITION);
+
+ // writes to the write only file channel
+ writeOnlyFileChannel.write(writeBuffer);
+ // force to write out.
+ writeOnlyFileChannel.close();
+
+ // gets the result of the write only file channel
+ byte[] result = new byte[POSITION + CONTENT_LENGTH];
+ fis = new FileInputStream(fileOfWriteOnlyFileChannel);
+ fis.read(result);
+
+ // constructs the expected result which has content[0... POSITION] plus
+ // content[0...length()]
+ byte[] expectedResult = new byte[POSITION + CONTENT_LENGTH];
+ System.arraycopy(CONTENT_AS_BYTES, 0, expectedResult, 0, POSITION);
+ System.arraycopy(CONTENT_AS_BYTES, 0, expectedResult, POSITION,
+ CONTENT_LENGTH);
+
+ // asserts result of the write only file channel same as expected
+ assertTrue(Arrays.equals(expectedResult, result));
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#size()
+ */
+ public void test_size_Init() throws Exception {
+ assertEquals(0, readOnlyFileChannel.size());
+ assertEquals(0, writeOnlyFileChannel.size());
+ assertEquals(0, readWriteFileChannel.size());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#size()
+ */
+ public void test_size() throws Exception {
+ writeDataToFile(fileOfReadOnlyFileChannel);
+ assertEquals(fileOfReadOnlyFileChannel.length(), readOnlyFileChannel
+ .size());
+
+
+ // REGRESSION test for read(ByteBuffer[], int, int) on special files
+ try {
+ FileChannel specialFile =
+ new FileInputStream("/dev/zero").getChannel();
+ assertEquals(0, specialFile.size());
+ ByteBuffer buf = ByteBuffer.allocate(8);
+ assertEquals(8, specialFile.read(buf));
+ ByteBuffer[] bufs = { ByteBuffer.allocate(8) };
+ assertEquals(8, specialFile.read(bufs, 0, 1));
+ specialFile.close();
+ } catch (FileNotFoundException e) {
+ // skip test if special file doesn't exist
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#size()
+ */
+ public void test_size_Closed() throws Exception {
+ readOnlyFileChannel.close();
+ try {
+ readOnlyFileChannel.size();
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ writeOnlyFileChannel.close();
+ try {
+ writeOnlyFileChannel.size();
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ readWriteFileChannel.close();
+ try {
+ readWriteFileChannel.size();
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#truncate(long)
+ */
+ public void test_truncateJ_Closed() throws Exception {
+ readOnlyFileChannel.close();
+ try {
+ readOnlyFileChannel.truncate(0);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ writeOnlyFileChannel.close();
+ try {
+ writeOnlyFileChannel.truncate(0);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ readWriteFileChannel.close();
+ try {
+ readWriteFileChannel.truncate(-1);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#truncate(long)
+ */
+ public void test_truncateJ_IllegalArgument() throws Exception {
+ // regression test for Harmony-941
+ try {
+ readOnlyFileChannel.truncate(-1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ writeOnlyFileChannel.truncate(-1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ readWriteFileChannel.truncate(-1);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#truncate(long)
+ */
+ public void test_truncateJ_ReadOnly() throws Exception {
+ writeDataToFile(fileOfReadOnlyFileChannel);
+ try {
+ readOnlyFileChannel.truncate(readOnlyFileChannel.size());
+ fail("should throw NonWritableChannelException.");
+ } catch (NonWritableChannelException e) {
+ // expected
+ }
+
+ try {
+ readOnlyFileChannel.truncate(0);
+ fail("should throw NonWritableChannelException.");
+ } catch (NonWritableChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#truncate(long)
+ */
+ public void test_truncateJ() throws Exception {
+ writeDataToFile(fileOfReadWriteFileChannel);
+
+ int truncateLength = CONTENT_LENGTH + 2;
+ assertEquals(readWriteFileChannel, readWriteFileChannel
+ .truncate(truncateLength));
+ assertEquals(CONTENT_LENGTH, fileOfReadWriteFileChannel.length());
+
+ truncateLength = CONTENT_LENGTH;
+ assertEquals(readWriteFileChannel, readWriteFileChannel
+ .truncate(truncateLength));
+ assertEquals(CONTENT_LENGTH, fileOfReadWriteFileChannel.length());
+
+ truncateLength = CONTENT_LENGTH / 2;
+ assertEquals(readWriteFileChannel, readWriteFileChannel
+ .truncate(truncateLength));
+ assertEquals(truncateLength, fileOfReadWriteFileChannel.length());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#lock()
+ */
+ public void test_lock() throws Exception {
+ MockFileChannel mockFileChannel = new MockFileChannel();
+ // Verify that calling lock() leads to the method
+ // lock(long, long, boolean) being called with a 0 for the
+ // first parameter, Long.MAX_VALUE as the second parameter and false
+ // as the third parameter.
+ mockFileChannel.lock();
+ assertTrue(mockFileChannel.isLockCalled);
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#lock(long, long, boolean)
+ */
+ public void test_lockJJZ_Closed() throws Exception {
+ readOnlyFileChannel.close();
+ try {
+ readOnlyFileChannel.lock(0, 10, false);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ writeOnlyFileChannel.close();
+ try {
+ writeOnlyFileChannel.lock(0, 10, false);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ readWriteFileChannel.close();
+ try {
+ readWriteFileChannel.lock(0, 10, false);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ // throws ClosedChannelException before IllegalArgumentException
+ try {
+ readWriteFileChannel.lock(-1, 0, false);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#lock(long, long, boolean)
+ */
+ public void test_lockJJZ_IllegalArgument() throws Exception {
+ try {
+ writeOnlyFileChannel.lock(0, -1, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ writeOnlyFileChannel.lock(-1, 0, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ readWriteFileChannel.lock(-1, -1, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ readWriteFileChannel.lock(Long.MAX_VALUE, 1, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#lock(long, long, boolean)
+ */
+ public void test_lockJJZ_NonWritable() throws Exception {
+ try {
+ readOnlyFileChannel.lock(0, 10, false);
+ fail("should throw NonWritableChannelException");
+ } catch (NonWritableChannelException e) {
+ // expected
+ }
+
+ // throws NonWritableChannelException before IllegalArgumentException
+ try {
+ readOnlyFileChannel.lock(-1, 0, false);
+ fail("should throw NonWritableChannelException");
+ } catch (NonWritableChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#lock(long, long, boolean)
+ */
+ public void test_lockJJZ_NonReadable() throws Exception {
+ try {
+ writeOnlyFileChannel.lock(0, 10, true);
+ fail("should throw NonReadableChannelException");
+ } catch (NonReadableChannelException e) {
+ // expected
+ }
+
+ // throws NonReadableChannelException before IllegalArgumentException
+ try {
+ writeOnlyFileChannel.lock(-1, 0, true);
+ fail("should throw NonReadableChannelException");
+ } catch (NonReadableChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#lock(long, long, boolean)
+ */
+ public void test_lockJJZ_Shared() throws Exception {
+ final long POSITION = 100;
+ final long SIZE = 200;
+ fileLock = readOnlyFileChannel.lock(POSITION, SIZE, true);
+ assertTrue(fileLock.isValid());
+ // fileLock.isShared depends on whether the underlying platform support
+ // shared lock, but it works on Windows & Linux.
+ assertTrue(fileLock.isShared());
+ assertSame(readOnlyFileChannel, fileLock.channel());
+ assertEquals(POSITION, fileLock.position());
+ assertEquals(SIZE, fileLock.size());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#lock(long, long, boolean)
+ */
+ public void test_lockJJZ_NotShared() throws Exception {
+ final long POSITION = 100;
+ final long SIZE = 200;
+ fileLock = writeOnlyFileChannel.lock(POSITION, SIZE, false);
+ assertTrue(fileLock.isValid());
+ assertFalse(fileLock.isShared());
+ assertSame(writeOnlyFileChannel, fileLock.channel());
+ assertEquals(POSITION, fileLock.position());
+ assertEquals(SIZE, fileLock.size());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#lock(long, long, boolean)
+ */
+ public void test_lockJJZ_Long_MAX_VALUE() throws Exception {
+ final long POSITION = 0;
+ final long SIZE = Long.MAX_VALUE;
+ fileLock = readOnlyFileChannel.lock(POSITION, SIZE, true);
+ assertTrue(fileLock.isValid());
+ assertTrue(fileLock.isShared());
+ assertEquals(POSITION, fileLock.position());
+ assertEquals(SIZE, fileLock.size());
+ assertSame(readOnlyFileChannel, fileLock.channel());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#lock(long, long, boolean)
+ */
+ public void test_lockJJZ_Overlapping() throws Exception {
+ final long POSITION = 100;
+ final long SIZE = 200;
+ fileLock = writeOnlyFileChannel.lock(POSITION, SIZE, false);
+ assertTrue(fileLock.isValid());
+
+ try {
+ writeOnlyFileChannel.lock(POSITION + 1, SIZE, false);
+ fail("should throw OverlappingFileLockException");
+ } catch (OverlappingFileLockException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#lock(long, long, boolean)
+ */
+ public void test_lockJJZ_NotOverlapping() throws Exception {
+ final long POSITION = 100;
+ final long SIZE = 200;
+ FileLock fileLock1 = writeOnlyFileChannel.lock(POSITION, SIZE, false);
+ assertTrue(fileLock1.isValid());
+ FileLock fileLock2 = writeOnlyFileChannel.lock(POSITION + SIZE, SIZE,
+ false);
+ assertTrue(fileLock2.isValid());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#lock(long,long,boolean)
+ */
+ public void test_lockJJZ_After_Release() throws Exception {
+ fileLock = writeOnlyFileChannel.lock(0, 10, false);
+ fileLock.release();
+ // after release file lock can be obtained again.
+ fileLock = writeOnlyFileChannel.lock(0, 10, false);
+ assertTrue(fileLock.isValid());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#tryLock()
+ */
+ public void test_tryLock() throws Exception {
+ MockFileChannel mockFileChannel = new MockFileChannel();
+ // Verify that calling tryLock() leads to the method
+ // tryLock(long, long, boolean) being called with a 0 for the
+ // first parameter, Long.MAX_VALUE as the second parameter and false
+ // as the third parameter.
+ mockFileChannel.tryLock();
+ assertTrue(mockFileChannel.isTryLockCalled);
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean)
+ */
+ public void test_tryLockJJZ_Closed() throws Exception {
+ readOnlyFileChannel.close();
+ try {
+ readOnlyFileChannel.tryLock(0, 10, false);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ writeOnlyFileChannel.close();
+ try {
+ writeOnlyFileChannel.tryLock(0, 10, false);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ readWriteFileChannel.close();
+ try {
+ readWriteFileChannel.tryLock(0, 10, false);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ // throws ClosedChannelException before IllegalArgumentException
+ try {
+ readWriteFileChannel.tryLock(-1, 0, false);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean)
+ */
+ public void test_tryLockJJZ_IllegalArgument() throws Exception {
+ try {
+ writeOnlyFileChannel.tryLock(0, -1, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ writeOnlyFileChannel.tryLock(-1, 0, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ readWriteFileChannel.tryLock(-1, -1, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ readWriteFileChannel.tryLock(Long.MAX_VALUE, 1, false);
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean)
+ */
+ public void test_tryLockJJZ_NonWritable() throws Exception {
+ try {
+ readOnlyFileChannel.tryLock(0, 10, false);
+ fail("should throw NonWritableChannelException");
+ } catch (NonWritableChannelException e) {
+ // expected
+ }
+
+ // throws NonWritableChannelException before IllegalArgumentException
+ try {
+ readOnlyFileChannel.tryLock(-1, 0, false);
+ fail("should throw NonWritableChannelException");
+ } catch (NonWritableChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean)
+ */
+ public void test_tryLockJJZ_NonReadable() throws Exception {
+ try {
+ writeOnlyFileChannel.tryLock(0, 10, true);
+ fail("should throw NonReadableChannelException");
+ } catch (NonReadableChannelException e) {
+ // expected
+ }
+
+ // throws NonReadableChannelException before IllegalArgumentException
+ try {
+ writeOnlyFileChannel.tryLock(-1, 0, true);
+ fail("should throw NonReadableChannelException");
+ } catch (NonReadableChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean)
+ */
+ public void test_tryLockJJZ_Shared() throws Exception {
+ final long POSITION = 100;
+ final long SIZE = 200;
+ fileLock = readOnlyFileChannel.tryLock(POSITION, SIZE, true);
+ assertTrue(fileLock.isValid());
+ // fileLock.isShared depends on whether the underlying platform support
+ // shared lock, but it works on Windows & Linux.
+ assertTrue(fileLock.isShared());
+ assertSame(readOnlyFileChannel, fileLock.channel());
+ assertEquals(POSITION, fileLock.position());
+ assertEquals(SIZE, fileLock.size());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean)
+ */
+ public void test_tryLockJJZ_NotShared() throws Exception {
+ final long POSITION = 100;
+ final long SIZE = 200;
+ fileLock = writeOnlyFileChannel.tryLock(POSITION, SIZE, false);
+ assertTrue(fileLock.isValid());
+ assertFalse(fileLock.isShared());
+ assertSame(writeOnlyFileChannel, fileLock.channel());
+ assertEquals(POSITION, fileLock.position());
+ assertEquals(SIZE, fileLock.size());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean)
+ */
+ public void test_tryLockJJZ_Long_MAX_VALUE() throws Exception {
+ final long POSITION = 0;
+ final long SIZE = Long.MAX_VALUE;
+ fileLock = readOnlyFileChannel.tryLock(POSITION, SIZE, true);
+ assertTrue(fileLock.isValid());
+ assertTrue(fileLock.isShared());
+ assertEquals(POSITION, fileLock.position());
+ assertEquals(SIZE, fileLock.size());
+ assertSame(readOnlyFileChannel, fileLock.channel());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean)
+ */
+ public void test_tryLockJJZ_Overlapping() throws Exception {
+ final long POSITION = 100;
+ final long SIZE = 200;
+ fileLock = writeOnlyFileChannel.lock(POSITION, SIZE, false);
+ assertTrue(fileLock.isValid());
+
+ try {
+ writeOnlyFileChannel.lock(POSITION + 1, SIZE, false);
+ fail("should throw OverlappingFileLockException");
+ } catch (OverlappingFileLockException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#tryLock(long, long, boolean)
+ */
+ public void test_tryLockJJZ_NotOverlapping() throws Exception {
+ final long POSITION = 100;
+ final long SIZE = 200;
+ FileLock fileLock1 = writeOnlyFileChannel
+ .tryLock(POSITION, SIZE, false);
+ assertTrue(fileLock1.isValid());
+
+ FileLock fileLock2 = writeOnlyFileChannel.tryLock(POSITION + SIZE,
+ SIZE, false);
+ assertTrue(fileLock2.isValid());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#tryLock(long,long,boolean)
+ */
+ public void test_tryLockJJZ_After_Release() throws Exception {
+ fileLock = writeOnlyFileChannel.tryLock(0, 10, false);
+ fileLock.release();
+
+ // after release file lock can be obtained again.
+ fileLock = writeOnlyFileChannel.tryLock(0, 10, false);
+ assertTrue(fileLock.isValid());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#read(ByteBuffer)
+ */
+ public void test_readLByteBuffer_Null() throws Exception {
+ ByteBuffer readBuffer = null;
+
+ try {
+ readOnlyFileChannel.read(readBuffer);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ readWriteFileChannel.read(readBuffer);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#read(ByteBuffer)
+ */
+ public void test_readLByteBuffer_Closed() throws Exception {
+ ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY);
+
+ readOnlyFileChannel.close();
+ try {
+ readOnlyFileChannel.read(readBuffer);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ writeOnlyFileChannel.close();
+ try {
+ writeOnlyFileChannel.read(readBuffer);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ readWriteFileChannel.close();
+ try {
+ readWriteFileChannel.read(readBuffer);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ // should throw ClosedChannelException first
+ readBuffer = null;
+ try {
+ readWriteFileChannel.read(readBuffer);
+ fail();
+ } catch (ClosedChannelException expected) {
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void test_readLByteBuffer_WriteOnly() throws Exception {
+ ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY);
+
+ try {
+ writeOnlyFileChannel.read(readBuffer);
+ fail();
+ } catch (NonReadableChannelException expected) {
+ }
+
+ readBuffer = null;
+ try {
+ writeOnlyFileChannel.read(readBuffer);
+ fail();
+ } catch (NonReadableChannelException expected) {
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void test_readLByteBuffer_EmptyFile() throws Exception {
+ ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY);
+ int result = readOnlyFileChannel.read(readBuffer);
+ assertEquals(-1, result);
+ assertEquals(0, readBuffer.position());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#read(ByteBuffer)
+ */
+ public void test_readLByteBuffer_LimitedCapacity() throws Exception {
+ writeDataToFile(fileOfReadOnlyFileChannel);
+
+ ByteBuffer readBuffer = ByteBuffer.allocate(LIMITED_CAPACITY);
+ int result = readOnlyFileChannel.read(readBuffer);
+ assertEquals(LIMITED_CAPACITY, result);
+ assertEquals(LIMITED_CAPACITY, readBuffer.position());
+ readBuffer.flip();
+ for (int i = 0; i < LIMITED_CAPACITY; i++) {
+ assertEquals(CONTENT_AS_BYTES[i], readBuffer.get());
+ }
+ }
+
+ public void test_readLByteBuffer() throws Exception {
+ writeDataToFile(fileOfReadOnlyFileChannel);
+
+ ByteBuffer readBuffer = ByteBuffer.allocate(CONTENT_AS_BYTES_LENGTH);
+ int result = readOnlyFileChannel.read(readBuffer);
+ assertEquals(CONTENT_AS_BYTES_LENGTH, result);
+ assertEquals(CONTENT_AS_BYTES_LENGTH, readBuffer.position());
+ readBuffer.flip();
+ for (int i = 0; i < CONTENT_AS_BYTES_LENGTH; i++) {
+ assertEquals(CONTENT_AS_BYTES[i], readBuffer.get());
+ }
+ }
+
+ public void test_readLByteBufferJ_Null() throws Exception {
+ try {
+ readOnlyFileChannel.read(null, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ readWriteFileChannel.read(null, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void test_readLByteBufferJ_Closed() throws Exception {
+ ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY);
+
+ readOnlyFileChannel.close();
+ try {
+ readOnlyFileChannel.read(readBuffer, 0);
+ fail();
+ } catch (ClosedChannelException expected) {
+ }
+
+ readWriteFileChannel.close();
+ try {
+ readWriteFileChannel.read(readBuffer, 0);
+ fail();
+ } catch (ClosedChannelException expected) {
+ }
+ }
+
+ public void test_readLByteBufferJ_IllegalArgument() throws Exception {
+ ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY);
+
+ try {
+ readOnlyFileChannel.read(readBuffer, -1);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ writeOnlyFileChannel.read(readBuffer, -1);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ readWriteFileChannel.read(readBuffer, -1);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ public void test_readLByteBufferJ_WriteOnly() throws Exception {
+ ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY);
+
+ try {
+ writeOnlyFileChannel.read(readBuffer, 0);
+ fail();
+ } catch (NonReadableChannelException expected) {
+ }
+ }
+
+ public void test_readLByteBufferJ_Emptyfile() throws Exception {
+ ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY);
+ int result = readOnlyFileChannel.read(readBuffer, 0);
+ assertEquals(-1, result);
+ assertEquals(0, readBuffer.position());
+ }
+
+ public void test_readLByteBufferJ_Position_BeyondFileLimit() throws Exception {
+ writeDataToFile(fileOfReadOnlyFileChannel);
+
+ ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY);
+ int result = readOnlyFileChannel.read(readBuffer,
+ CONTENT_AS_BYTES.length);
+ assertEquals(-1, result);
+ assertEquals(0, readBuffer.position());
+ }
+
+ public void test_readLByteBufferJ_Position_As_Long() throws Exception {
+ ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY);
+ try {
+ readOnlyFileChannel.read(readBuffer, Long.MAX_VALUE);
+ } catch (IOException expected) {
+ }
+ }
+
+ public void test_readLByteBufferJ() throws Exception {
+ writeDataToFile(fileOfReadOnlyFileChannel);
+ ByteBuffer readBuffer = ByteBuffer.allocate(CAPACITY);
+
+ final int BUFFER_POSITION = 1;
+ readBuffer.position(BUFFER_POSITION);
+
+ final int POSITION = 2;
+ int result = readOnlyFileChannel.read(readBuffer, POSITION);
+ assertEquals(CONTENT_AS_BYTES_LENGTH - POSITION, result);
+ assertEquals(BUFFER_POSITION + result, readBuffer.position());
+
+ readBuffer.flip();
+ readBuffer.position(BUFFER_POSITION);
+ for (int i = POSITION; i < CONTENT_AS_BYTES_LENGTH; i++) {
+ assertEquals(CONTENT_AS_BYTES[i], readBuffer.get());
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#read(ByteBuffer[])
+ */
+ public void test_read$LByteBuffer() throws Exception {
+ // regression test for Harmony-849
+ writeDataToFile(fileOfReadOnlyFileChannel);
+ ByteBuffer[] readBuffers = new ByteBuffer[2];
+ readBuffers[0] = ByteBuffer.allocate(CAPACITY);
+ readBuffers[1] = ByteBuffer.allocate(CAPACITY);
+
+ long readCount = readOnlyFileChannel.read(readBuffers);
+ assertEquals(CONTENT_AS_BYTES_LENGTH, readCount);
+ assertEquals(CONTENT_AS_BYTES_LENGTH, readBuffers[0].position());
+ assertEquals(0, readBuffers[1].position());
+ readBuffers[0].flip();
+ for (int i = 0; i < CONTENT_AS_BYTES_LENGTH; i++) {
+ assertEquals(CONTENT_AS_BYTES[i], readBuffers[0].get());
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#read(ByteBuffer[])
+ */
+ public void test_read$LByteBuffer_mock() throws Exception {
+ FileChannel mockChannel = new MockFileChannel();
+ ByteBuffer[] buffers = new ByteBuffer[2];
+ mockChannel.read(buffers);
+ // Verify that calling read(ByteBuffer[] dsts) leads to the method
+ // read(dsts, 0, dsts.length)
+ assertTrue(((MockFileChannel)mockChannel).isReadCalled);
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int)
+ */
+ public void test_read$LByteBufferII_Null() throws Exception {
+ ByteBuffer[] readBuffers = null;
+
+ try {
+ readOnlyFileChannel.read(readBuffers, 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ readOnlyFileChannel.read(readBuffers, 1, 11);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ writeOnlyFileChannel.read(readBuffers, 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ readWriteFileChannel.read(readBuffers, 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ // first throws NullPointerException
+ writeOnlyFileChannel.close();
+ try {
+ writeOnlyFileChannel.read(readBuffers, 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int)
+ */
+ public void test_read$LByteBufferII_Closed() throws Exception {
+ ByteBuffer[] readBuffers = new ByteBuffer[2];
+ readBuffers[0] = ByteBuffer.allocate(CAPACITY);
+
+ readOnlyFileChannel.close();
+ try {
+ readOnlyFileChannel.read(readBuffers, 0, 1);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ writeOnlyFileChannel.close();
+ try {
+ writeOnlyFileChannel.read(readBuffers, 0, 1);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ readWriteFileChannel.close();
+ try {
+ readWriteFileChannel.read(readBuffers, 0, 1);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ // regression test for Harmony-902
+ readBuffers[0] = null;
+ try {
+ readOnlyFileChannel.read(readBuffers, 0, 1);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ try {
+ writeOnlyFileChannel.read(readBuffers, 0, 1);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ try {
+ readWriteFileChannel.read(readBuffers, 0, 1);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int)
+ */
+ public void test_read$LByteBufferII_WriteOnly() throws Exception {
+ ByteBuffer[] readBuffers = new ByteBuffer[2];
+ readBuffers[0] = ByteBuffer.allocate(CAPACITY);
+
+ try {
+ writeOnlyFileChannel.read(readBuffers, 0, 1);
+ fail("should throw NonReadableChannelException");
+ } catch (NonReadableChannelException e) {
+ // expected
+ }
+
+ // first throws NonReadableChannelException.
+ readBuffers[0] = null;
+ try {
+ writeOnlyFileChannel.read(readBuffers, 0, 1);
+ fail("should throw NonReadableChannelException");
+ } catch (NonReadableChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int)
+ */
+ public void test_read$LByteBufferII_IndexOutOfBound() throws Exception {
+ ByteBuffer[] readBuffers = new ByteBuffer[2];
+ readBuffers[0] = ByteBuffer.allocate(CAPACITY);
+ readBuffers[1] = ByteBuffer.allocate(CAPACITY);
+
+ try {
+ readOnlyFileChannel.read(readBuffers, 2, 1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ readWriteFileChannel.read(null, -1, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ writeOnlyFileChannel.read(readBuffers, 0, 3);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ try {
+ readWriteFileChannel.read(readBuffers, -1, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ readWriteFileChannel.close();
+ try {
+ readWriteFileChannel.read(readBuffers, 0, 3);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int)
+ */
+ public void test_read$LByteBufferII_EmptyFile() throws Exception {
+ ByteBuffer[] readBuffers = new ByteBuffer[2];
+ readBuffers[0] = ByteBuffer.allocate(CAPACITY);
+ readBuffers[1] = ByteBuffer.allocate(CAPACITY);
+ long result = readOnlyFileChannel.read(readBuffers, 0, 2);
+ assertEquals(-1, result);
+ assertEquals(0, readBuffers[0].position());
+ assertEquals(0, readBuffers[1].position());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int)
+ */
+ public void test_read$LByteBufferII_EmptyBuffers() throws Exception {
+ ByteBuffer[] readBuffers = new ByteBuffer[2];
+ try {
+ readOnlyFileChannel.read(readBuffers, 0, 2);
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ writeDataToFile(fileOfReadOnlyFileChannel);
+ readBuffers[0] = ByteBuffer.allocate(CAPACITY);
+ try {
+ readOnlyFileChannel.read(readBuffers, 0, 2);
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ long result = readOnlyFileChannel.read(readBuffers, 0, 1);
+ assertEquals(CONTENT_AS_BYTES_LENGTH, result);
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int)
+ */
+ public void test_read$LByteBufferII_EmptyFile_EmptyBuffers()
+ throws Exception {
+ ByteBuffer[] readBuffers = new ByteBuffer[2];
+ // will not throw NullPointerException
+ long result = readOnlyFileChannel.read(readBuffers, 0, 0);
+ assertEquals(0, result);
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int)
+ */
+ public void test_read$LByteBufferII_Length_Zero() throws Exception {
+ writeDataToFile(fileOfReadOnlyFileChannel);
+ ByteBuffer[] readBuffers = new ByteBuffer[2];
+ readBuffers[0] = ByteBuffer.allocate(LIMITED_CAPACITY);
+ readBuffers[1] = ByteBuffer.allocate(LIMITED_CAPACITY);
+ long result = readOnlyFileChannel.read(readBuffers, 1, 0);
+ assertEquals(0, result);
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int)
+ */
+ public void test_read$LByteBufferII_LimitedCapacity() throws Exception {
+ writeDataToFile(fileOfReadOnlyFileChannel);
+ ByteBuffer[] readBuffers = new ByteBuffer[2];
+ readBuffers[0] = ByteBuffer.allocate(LIMITED_CAPACITY);
+ readBuffers[1] = ByteBuffer.allocate(LIMITED_CAPACITY);
+
+ // reads to the second buffer
+ long result = readOnlyFileChannel.read(readBuffers, 1, 1);
+ assertEquals(LIMITED_CAPACITY, result);
+ assertEquals(0, readBuffers[0].position());
+ assertEquals(LIMITED_CAPACITY, readBuffers[1].position());
+
+ readBuffers[1].flip();
+ for (int i = 0; i < LIMITED_CAPACITY; i++) {
+ assertEquals(CONTENT_AS_BYTES[i], readBuffers[1].get());
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#read(ByteBuffer[], int, int)
+ */
+ public void test_read$LByteBufferII() throws Exception {
+ writeDataToFile(fileOfReadOnlyFileChannel);
+ ByteBuffer[] readBuffers = new ByteBuffer[2];
+ readBuffers[0] = ByteBuffer.allocate(CAPACITY);
+ readBuffers[1] = ByteBuffer.allocate(CAPACITY);
+
+ // writes to the second buffer
+ assertEquals(CONTENT_AS_BYTES_LENGTH, readOnlyFileChannel.read(
+ readBuffers, 1, 1));
+ assertEquals(0, readBuffers[0].position());
+ assertEquals(CONTENT_AS_BYTES_LENGTH, readBuffers[1].position());
+
+ readBuffers[1].flip();
+ for (int i = 0; i < CONTENT_AS_BYTES_LENGTH; i++) {
+ assertEquals(CONTENT_AS_BYTES[i], readBuffers[1].get());
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#isOpen()
+ */
+ public void test_isOpen() throws Exception {
+ // Regression for HARMONY-40
+ File logFile = File.createTempFile("out", "tmp");
+ logFile.deleteOnExit();
+ FileOutputStream out = new FileOutputStream(logFile, true);
+ FileChannel channel = out.getChannel();
+ out.write(1);
+ out.close();
+ assertFalse("Assert 0: Channel is still open", channel.isOpen());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#position()
+ */
+ public void test_position_append() throws Exception {
+ // Regression test for Harmony-508
+ File tmpfile = File.createTempFile("FileOutputStream", "tmp");
+ tmpfile.deleteOnExit();
+ FileOutputStream fos = new FileOutputStream(tmpfile);
+ byte[] b = new byte[10];
+ for (int i = 0; i < b.length; i++) {
+ b[i] = (byte) i;
+ }
+ fos.write(b);
+ fos.flush();
+ fos.close();
+ FileOutputStream f = new FileOutputStream(tmpfile, true);
+ // Harmony expected 10, but the RI and Android report 0.
+ assertEquals(0, f.getChannel().position());
+ }
+
+
+ /**
+ * @tests java.nio.channels.FileChannel#map(MapMode,long,long)
+ */
+ public void test_map_AbnormalMode() throws IOException {
+ try {
+ writeOnlyFileChannel.map(MapMode.READ_ONLY, 0, CONTENT_LENGTH);
+ fail("should throw NonReadableChannelException.");
+ } catch (NonReadableChannelException ex) {
+ // expected;
+ }
+ try {
+ writeOnlyFileChannel.map(MapMode.READ_WRITE, 0, CONTENT_LENGTH);
+ fail("should throw NonReadableChannelException.");
+ } catch (NonReadableChannelException ex) {
+ // expected;
+ }
+ try {
+ writeOnlyFileChannel.map(MapMode.PRIVATE, 0, CONTENT_LENGTH);
+ fail("should throw NonReadableChannelException.");
+ } catch (NonReadableChannelException ex) {
+ // expected;
+ }
+ writeOnlyFileChannel.close();
+ try {
+ writeOnlyFileChannel.map(MapMode.READ_WRITE, 0, -1);
+ fail("should throw ClosedChannelException.");
+ } catch (ClosedChannelException ex) {
+ // expected;
+ }
+
+ try {
+ readOnlyFileChannel.map(MapMode.READ_WRITE, 0, CONTENT_LENGTH);
+ fail("should throw NonWritableChannelException .");
+ } catch (NonWritableChannelException ex) {
+ // expected;
+ }
+ try {
+ readOnlyFileChannel.map(MapMode.PRIVATE, 0, CONTENT_LENGTH);
+ fail("should throw NonWritableChannelException .");
+ } catch (NonWritableChannelException ex) {
+ // expected;
+ }
+ try {
+ readOnlyFileChannel.map(MapMode.READ_WRITE, -1, CONTENT_LENGTH);
+ fail("should throw IAE.");
+ } catch (IllegalArgumentException ex) {
+ // expected;
+ }
+ try {
+ readOnlyFileChannel.map(MapMode.READ_WRITE, 0, -1);
+ fail("should throw IAE.");
+ } catch (IllegalArgumentException ex) {
+ // expected;
+ }
+
+ try {
+ readOnlyFileChannel.map(MapMode.READ_ONLY, 0, CONTENT_LENGTH + 1);
+ fail();
+ } catch (NonWritableChannelException expected) {
+ } catch (IOException expected) {
+ }
+ try {
+ readOnlyFileChannel.map(MapMode.READ_ONLY, 2, CONTENT_LENGTH - 1);
+ fail();
+ } catch (NonWritableChannelException expected) {
+ } catch (IOException expected) {
+ }
+
+ readOnlyFileChannel.close();
+ try {
+ readOnlyFileChannel.map(MapMode.READ_WRITE, 0, -1);
+ fail("should throw ClosedChannelException.");
+ } catch (ClosedChannelException ex) {
+ // expected;
+ }
+ try {
+ readOnlyFileChannel.map(MapMode.READ_ONLY, 2, CONTENT_LENGTH - 1);
+ fail("should throw IOException.");
+ } catch (IOException ex) {
+ // expected;
+ }
+
+ readWriteFileChannel.close();
+ try {
+ readWriteFileChannel.map(MapMode.READ_WRITE, 0, -1);
+ fail("should throw ClosedChannelException.");
+ } catch (ClosedChannelException ex) {
+ // expected;
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#map(MapMode,long,long)
+ */
+ public void test_map_ReadOnly_CloseChannel() throws IOException {
+ // close channel has no effect on map if mapped
+ assertEquals(0, readWriteFileChannel.size());
+ MappedByteBuffer mapped = readWriteFileChannel.map(MapMode.READ_ONLY,
+ 0, CONTENT_LENGTH);
+ assertEquals(CONTENT_LENGTH, readWriteFileChannel.size());
+ readOnlyFileChannel.close();
+ assertEquals(CONTENT_LENGTH, mapped.limit());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#map(MapMode,long,long)
+ */
+ public void test_map_Private_CloseChannel() throws IOException {
+ MappedByteBuffer mapped = readWriteFileChannel.map(MapMode.PRIVATE, 0,
+ CONTENT_LENGTH);
+ readWriteFileChannel.close();
+ mapped.put(TEST_BYTES);
+ assertEquals(CONTENT_LENGTH, mapped.limit());
+ assertEquals("test".length(), mapped.position());
+ }
+
+ /**
+ * @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) {
+ // expected;
+ }
+ 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());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#map(MapMode,long,long)
+ */
+ public void test_map_ReadOnly_NonZeroPosition() throws IOException {
+ this.writeDataToFile(fileOfReadOnlyFileChannel);
+ MappedByteBuffer mapped = readOnlyFileChannel.map(MapMode.READ_ONLY,
+ 10, CONTENT_LENGTH - 10);
+ assertEquals(CONTENT_LENGTH - 10, mapped.limit());
+ assertEquals(CONTENT_LENGTH - 10, mapped.capacity());
+ assertEquals(0, mapped.position());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#map(MapMode,long,long)
+ */
+ public void test_map_Private() throws IOException {
+ this.writeDataToFile(fileOfReadWriteFileChannel);
+ MappedByteBuffer mapped = readWriteFileChannel.map(MapMode.PRIVATE, 0,
+ CONTENT_LENGTH);
+ assertEquals(CONTENT_LENGTH, mapped.limit());
+ // test copy on write if private
+ ByteBuffer returnByPut = mapped.put(TEST_BYTES);
+ assertSame(returnByPut, mapped);
+ ByteBuffer checkBuffer = ByteBuffer.allocate(CONTENT_LENGTH);
+ mapped.force();
+ readWriteFileChannel.read(checkBuffer);
+ assertEquals(CONTENT, new String(checkBuffer.array(), "iso8859-1"));
+
+ // test overflow
+ try {
+ mapped.put(("test" + CONTENT).getBytes("iso8859-1"));
+ fail("should throw BufferOverflowException.");
+ } catch (BufferOverflowException ex) {
+ // expected;
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#map(MapMode,long,long)
+ */
+ public void test_map_Private_NonZeroPosition() throws IOException {
+ MappedByteBuffer mapped = readWriteFileChannel.map(MapMode.PRIVATE, 10,
+ CONTENT_LENGTH - 10);
+ assertEquals(CONTENT_LENGTH - 10, mapped.limit());
+ assertEquals(CONTENT_LENGTH - 10, mapped.capacity());
+ assertEquals(0, mapped.position());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#map(MapMode,long,long)
+ */
+ public void test_map_ReadWrite() throws IOException {
+ MappedByteBuffer mapped = null;
+ writeDataToFile(fileOfReadWriteFileChannel);
+ mapped = readWriteFileChannel.map(MapMode.READ_WRITE, 0, CONTENT
+ .length());
+
+ // put something will change its channel
+ ByteBuffer returnByPut = mapped.put(TEST_BYTES);
+ assertSame(returnByPut, mapped);
+ String checkString = "test" + CONTENT.substring(4);
+ ByteBuffer checkBuffer = ByteBuffer.allocate(CONTENT_LENGTH);
+ mapped.force();
+ readWriteFileChannel.position(0);
+ readWriteFileChannel.read(checkBuffer);
+ assertEquals(checkString, new String(checkBuffer.array(), "iso8859-1"));
+
+ try {
+ mapped.put(("test" + CONTENT).getBytes("iso8859-1"));
+ fail("should throw BufferOverflowException.");
+ } catch (BufferOverflowException ex) {
+ // expected;
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#map(MapMode,long,long)
+ */
+ public void test_map_ReadWrite_NonZeroPosition() throws IOException {
+ // test position non-zero
+ writeDataToFile(fileOfReadWriteFileChannel);
+ MappedByteBuffer mapped = readWriteFileChannel.map(MapMode.READ_WRITE,
+ 10, CONTENT_LENGTH - 10);
+ assertEquals(CONTENT_LENGTH - 10, mapped.limit());
+ assertEquals(CONTENT.length() - 10, mapped.capacity());
+ assertEquals(0, mapped.position());
+ mapped.put(TEST_BYTES);
+ ByteBuffer checkBuffer = ByteBuffer.allocate(CONTENT_LENGTH);
+ readWriteFileChannel.read(checkBuffer);
+ String expected = CONTENT.substring(0, 10) + "test"
+ + CONTENT.substring(10 + "test".length());
+ assertEquals(expected, new String(checkBuffer.array(), "iso8859-1"));
+ }
+
+ /**
+ * Tests map() method for the value of positions exceeding memory
+ * page size and allocation granularity size.
+ *
+ * @tests java.nio.channels.FileChannel#map(MapMode,long,long)
+ */
+ public void test_map_LargePosition() throws IOException {
+ // Regression test for HARMONY-3085
+ int[] sizes = {
+ 4096, // 4K size (normal page size for Linux & Windows)
+ 65536, // 64K size (alocation granularity size for Windows)
+ };
+ final int CONTENT_LEN = 10;
+
+ for (int i = 0; i < sizes.length; ++i) {
+ // reset the file and the channel for the iterations
+ // (for the first iteration it was done by setUp()
+ if (i > 0 ) {
+ fileOfReadOnlyFileChannel = File.createTempFile(
+ "File_of_readOnlyFileChannel", "tmp");
+ fileOfReadOnlyFileChannel.deleteOnExit();
+ readOnlyFileChannel = new FileInputStream(fileOfReadOnlyFileChannel)
+ .getChannel();
+ }
+
+ writeLargeDataToFile(fileOfReadOnlyFileChannel, sizes[i] + 2 * CONTENT_LEN);
+ MappedByteBuffer mapped = readOnlyFileChannel.map(MapMode.READ_ONLY,
+ sizes[i], CONTENT_LEN);
+ assertEquals("Incorrectly mapped file channel for " + sizes[i]
+ + " position (capacity)", CONTENT_LEN, mapped.capacity());
+ assertEquals("Incorrectly mapped file channel for " + sizes[i]
+ + " position (limit)", CONTENT_LEN, mapped.limit());
+ assertEquals("Incorrectly mapped file channel for " + sizes[i]
+ + " position (position)", 0, mapped.position());
+
+ // map not change channel's position
+ assertEquals(0, readOnlyFileChannel.position());
+
+ // Close the file and the channel before the next iteration
+ readOnlyFileChannel.close();
+ fileOfReadOnlyFileChannel.delete();
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#write(ByteBuffer)
+ */
+ public void test_writeLByteBuffer_Null() throws Exception {
+ ByteBuffer writeBuffer = null;
+
+ try {
+ writeOnlyFileChannel.write(writeBuffer);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ readWriteFileChannel.write(writeBuffer);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#write(ByteBuffer)
+ */
+ public void test_writeLByteBuffer_Closed() throws Exception {
+ ByteBuffer writeBuffer = ByteBuffer.allocate(CAPACITY);
+
+ readOnlyFileChannel.close();
+ try {
+ readOnlyFileChannel.write(writeBuffer);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ writeOnlyFileChannel.close();
+ try {
+ writeOnlyFileChannel.write(writeBuffer);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ readWriteFileChannel.close();
+ try {
+ readWriteFileChannel.write(writeBuffer);
+ fail();
+ } catch (ClosedChannelException expected) {
+ }
+
+ writeBuffer = null;
+ try {
+ readWriteFileChannel.read(writeBuffer);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (ClosedChannelException expected) {
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#write(ByteBuffer)
+ */
+ public void test_writeLByteBuffer_ReadOnly() throws Exception {
+ ByteBuffer writeBuffer = ByteBuffer.allocate(CAPACITY);
+
+ try {
+ readOnlyFileChannel.write(writeBuffer);
+ fail("should throw NonWritableChannelException");
+ } catch (NonWritableChannelException e) {
+ // expected
+ }
+
+ // first throws NonWriteableChannelException
+ writeBuffer = null;
+ try {
+ readOnlyFileChannel.write(writeBuffer);
+ fail("should throw NonWritableChannelException");
+ } catch (NonWritableChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#write(ByteBuffer)
+ */
+ public void test_writeLByteBuffer() throws Exception {
+ ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES);
+
+ int result = writeOnlyFileChannel.write(writeBuffer);
+ assertEquals(CONTENT_AS_BYTES_LENGTH, result);
+ assertEquals(CONTENT_AS_BYTES_LENGTH, writeBuffer.position());
+ writeOnlyFileChannel.close();
+
+ assertEquals(CONTENT_AS_BYTES_LENGTH, fileOfWriteOnlyFileChannel
+ .length());
+
+ fis = new FileInputStream(fileOfWriteOnlyFileChannel);
+ byte[] inputBuffer = new byte[CONTENT_AS_BYTES_LENGTH];
+ fis.read(inputBuffer);
+ assertTrue(Arrays.equals(CONTENT_AS_BYTES, inputBuffer));
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#write(ByteBuffer)
+ */
+ public void test_writeLByteBuffer_positioned() throws Exception {
+ final int pos = 5;
+ ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES);
+ writeBuffer.position(pos);
+ int result = writeOnlyFileChannel.write(writeBuffer);
+ assertEquals(CONTENT_AS_BYTES_LENGTH - pos, result);
+ assertEquals(CONTENT_AS_BYTES_LENGTH, writeBuffer.position());
+ writeOnlyFileChannel.close();
+
+ assertEquals(CONTENT_AS_BYTES_LENGTH - pos, fileOfWriteOnlyFileChannel
+ .length());
+
+ fis = new FileInputStream(fileOfWriteOnlyFileChannel);
+ byte[] inputBuffer = new byte[CONTENT_AS_BYTES_LENGTH - pos];
+ fis.read(inputBuffer);
+ String test = CONTENT.substring(pos);
+ assertTrue(Arrays.equals(test.getBytes("iso8859-1"), inputBuffer));
+ }
+
+ public void test_writeLByteBufferJ_Null() throws Exception {
+ try {
+ readWriteFileChannel.write(null, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (NonWritableChannelException expected) {
+ }
+
+ try {
+ writeOnlyFileChannel.write(null, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ readWriteFileChannel.write(null, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void test_writeLByteBufferJ_Closed() throws Exception {
+ ByteBuffer writeBuffer = ByteBuffer.allocate(CAPACITY);
+
+ writeOnlyFileChannel.close();
+ try {
+ writeOnlyFileChannel.write(writeBuffer, 0);
+ fail();
+ } catch (ClosedChannelException expected) {
+ }
+
+ readWriteFileChannel.close();
+ try {
+ readWriteFileChannel.write(writeBuffer, 0);
+ fail();
+ } catch (ClosedChannelException expected) {
+ }
+ }
+
+ public void test_writeLByteBufferJ_ReadOnly() throws Exception {
+ ByteBuffer writeBuffer = ByteBuffer.allocate(CAPACITY);
+ try {
+ readOnlyFileChannel.write(writeBuffer, 10);
+ fail();
+ } catch (NonWritableChannelException expected) {
+ }
+ }
+
+ public void test_writeLByteBufferJ_IllegalArgument() throws Exception {
+ ByteBuffer writeBuffer = ByteBuffer.allocate(CAPACITY);
+
+ try {
+ readOnlyFileChannel.write(writeBuffer, -1);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ writeOnlyFileChannel.write(writeBuffer, -1);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+
+ try {
+ readWriteFileChannel.write(writeBuffer, -1);
+ fail();
+ } catch (IllegalArgumentException expected) {
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#write(ByteBuffer,long)
+ */
+ public void test_writeLByteBufferJ() throws Exception {
+ writeDataToFile(fileOfWriteOnlyFileChannel);
+
+ final int POSITION = 4;
+ ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES);
+ int result = writeOnlyFileChannel.write(writeBuffer, POSITION);
+ assertEquals(CONTENT_AS_BYTES_LENGTH, result);
+ assertEquals(CONTENT_AS_BYTES_LENGTH, writeBuffer.position());
+ writeOnlyFileChannel.close();
+
+ assertEquals(POSITION + CONTENT_AS_BYTES_LENGTH,
+ fileOfWriteOnlyFileChannel.length());
+
+ fis = new FileInputStream(fileOfWriteOnlyFileChannel);
+ byte[] inputBuffer = new byte[POSITION + CONTENT_AS_BYTES_LENGTH];
+ fis.read(inputBuffer);
+ byte[] expectedResult = new byte[POSITION + CONTENT_AS_BYTES_LENGTH];
+ System.arraycopy(CONTENT_AS_BYTES, 0, expectedResult, 0, POSITION);
+ System.arraycopy(CONTENT_AS_BYTES, 0, expectedResult, POSITION,
+ CONTENT_AS_BYTES_LENGTH);
+ assertTrue(Arrays.equals(expectedResult, inputBuffer));
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#write(ByteBuffer[])
+ */
+ public void test_write$LByteBuffer() throws Exception {
+ ByteBuffer[] writeBuffers = new ByteBuffer[2];
+ MockFileChannel mockFileChannel = new MockFileChannel();
+ mockFileChannel.write(writeBuffers);
+ // verify that calling write(ByteBuffer[] srcs) leads to the method
+ // write(srcs, 0, srcs.length)
+ assertTrue(mockFileChannel.isWriteCalled);
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#write(ByteBuffer[],int,int)
+ */
+ public void test_write$LByteBufferII_Null() throws Exception {
+ ByteBuffer[] writeBuffers = null;
+
+ try {
+ readOnlyFileChannel.write(writeBuffers, 1, 2);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ writeOnlyFileChannel.write(writeBuffers, 1, 2);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ readWriteFileChannel.write(writeBuffers, 1, 2);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ // first throws NullPointerException
+ readWriteFileChannel.close();
+ try {
+ readWriteFileChannel.write(writeBuffers, 0, 0);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#write(ByteBuffer[],int,int)
+ */
+ public void test_write$LByteBufferII_Closed() throws Exception {
+ ByteBuffer[] writeBuffers = new ByteBuffer[2];
+ writeBuffers[0] = ByteBuffer.allocate(CAPACITY);
+ writeBuffers[1] = ByteBuffer.allocate(CAPACITY);
+
+ readOnlyFileChannel.close();
+ try {
+ readOnlyFileChannel.write(writeBuffers, 0, 2);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ writeOnlyFileChannel.close();
+ try {
+ writeOnlyFileChannel.write(writeBuffers, 0, 2);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ readWriteFileChannel.close();
+ try {
+ readWriteFileChannel.write(writeBuffers, 0, 2);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ // throws ClosedChannelException first
+ writeBuffers[0] = null;
+ try {
+ readWriteFileChannel.write(writeBuffers, 0, 2);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#write(ByteBuffer[],int,int)
+ */
+ public void test_write$LByteBufferII_ReadOnly() throws Exception {
+ ByteBuffer[] writeBuffers = new ByteBuffer[2];
+ writeBuffers[0] = ByteBuffer.allocate(CAPACITY);
+ writeBuffers[1] = ByteBuffer.allocate(CAPACITY);
+
+ try {
+ readOnlyFileChannel.write(writeBuffers, 0, 2);
+ fail();
+ } catch (NonWritableChannelException e) {
+ }
+
+ try {
+ readOnlyFileChannel.write(writeBuffers, 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ writeBuffers = null;
+ try {
+ readOnlyFileChannel.write(writeBuffers, 0, 1);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ readOnlyFileChannel.close();
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#write(ByteBuffer[],int,int)
+ */
+ public void test_write$LByteBufferII_EmptyBuffers() throws Exception {
+ ByteBuffer[] writeBuffers = new ByteBuffer[2];
+ try {
+ writeOnlyFileChannel.write(writeBuffers, 0, 2);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ readWriteFileChannel.write(writeBuffers, 0, 2);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#write(ByteBuffer[],int,int)
+ */
+ public void test_write$LByteBufferII() throws Exception {
+ ByteBuffer[] writeBuffers = new ByteBuffer[2];
+ writeBuffers[0] = ByteBuffer.wrap(CONTENT_AS_BYTES);
+ writeBuffers[1] = ByteBuffer.wrap(CONTENT_AS_BYTES);
+
+ long result = writeOnlyFileChannel.write(writeBuffers, 0, 2);
+ assertEquals(CONTENT_AS_BYTES_LENGTH * 2, result);
+ assertEquals(CONTENT_AS_BYTES_LENGTH, writeBuffers[0].position());
+ assertEquals(CONTENT_AS_BYTES_LENGTH, writeBuffers[1].position());
+ writeOnlyFileChannel.close();
+
+ assertEquals(CONTENT_AS_BYTES_LENGTH * 2, fileOfWriteOnlyFileChannel
+ .length());
+
+ fis = new FileInputStream(fileOfWriteOnlyFileChannel);
+ byte[] inputBuffer = new byte[CONTENT_AS_BYTES_LENGTH];
+ fis.read(inputBuffer);
+ byte[] expectedResult = new byte[CONTENT_AS_BYTES_LENGTH * 2];
+ System.arraycopy(CONTENT_AS_BYTES, 0, expectedResult, 0,
+ CONTENT_AS_BYTES_LENGTH);
+ System.arraycopy(CONTENT_AS_BYTES, 0, expectedResult,
+ CONTENT_AS_BYTES_LENGTH, CONTENT_AS_BYTES_LENGTH);
+ assertTrue(Arrays.equals(CONTENT_AS_BYTES, inputBuffer));
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long)
+ */
+ public void test_transferFromLReadableByteChannelJJ_Closed()
+ throws Exception {
+ readByteChannel = DatagramChannel.open();
+ readOnlyFileChannel.close();
+ try {
+ readOnlyFileChannel.transferFrom(readByteChannel, 0, 0);
+ fail("should throw ClosedChannelException.");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ writeOnlyFileChannel.close();
+ try {
+ writeOnlyFileChannel.transferFrom(readByteChannel, 0, 10);
+ fail("should throw ClosedChannelException.");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ readWriteFileChannel.close();
+ try {
+ readWriteFileChannel.transferFrom(readByteChannel, 0, 0);
+ fail("should throw ClosedChannelException.");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ // should throw ClosedChannelException first.
+ try {
+ readWriteFileChannel.transferFrom(readByteChannel, 0, -1);
+ fail("should throw ClosedChannelException.");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long)
+ */
+ public void test_transferFromLReadableByteChannelJJ_SourceClosed()
+ throws Exception {
+ readByteChannel = DatagramChannel.open();
+ readByteChannel.close();
+
+ try {
+ readOnlyFileChannel.transferFrom(readByteChannel, 0, 10);
+ fail("should throw ClosedChannelException.");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ try {
+ writeOnlyFileChannel.transferFrom(readByteChannel, 0, 10);
+ fail("should throw ClosedChannelException.");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ try {
+ readWriteFileChannel.transferFrom(readByteChannel, 0, 10);
+ fail("should throw ClosedChannelException.");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ // should throw ClosedChannelException first.
+ try {
+ readWriteFileChannel.transferFrom(readByteChannel, 0, -1);
+ fail("should throw ClosedChannelException.");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long)
+ */
+ public void test_transferFromLReadableByteChannelJJ_IllegalArgument()
+ throws Exception {
+ readByteChannel = DatagramChannel.open();
+ try {
+ writeOnlyFileChannel.transferFrom(readByteChannel, 10, -1);
+ fail("should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ readWriteFileChannel.transferFrom(readByteChannel, -1, -10);
+ fail("should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long)
+ */
+ public void test_transferFromLReadableByteChannelJJ_NonWritable()
+ throws Exception {
+ readByteChannel = DatagramChannel.open();
+ try {
+ readOnlyFileChannel.transferFrom(readByteChannel, 0, 0);
+ fail("should throw NonWritableChannelException.");
+ } catch (NonWritableChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long)
+ */
+ public void test_transferFromLReadableByteChannelJJ_SourceNonReadable()
+ throws Exception {
+ try {
+ readWriteFileChannel.transferFrom(writeOnlyFileChannel, 0, 0);
+ fail("should throw NonReadableChannelException.");
+ } catch (NonReadableChannelException e) {
+ // expected
+ }
+
+ // not throws NonReadableChannelException first if position beyond file
+ // size.
+ readWriteFileChannel.transferFrom(writeOnlyFileChannel, 10, 10);
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long)
+ */
+ public void test_transferFromLReadableByteChannelJJ_PositionBeyondSize()
+ throws Exception {
+ // init data to file.
+ writeDataToFile(fileOfReadOnlyFileChannel);
+ writeDataToFile(fileOfWriteOnlyFileChannel);
+
+ final int READONLYFILECHANNELPOSITION = 2;
+ readOnlyFileChannel.position(READONLYFILECHANNELPOSITION);
+
+ final int POSITION = CONTENT_AS_BYTES_LENGTH * 2;
+ final int LENGTH = 5;
+ long result = writeOnlyFileChannel.transferFrom(readOnlyFileChannel,
+ POSITION, LENGTH);
+ assertEquals(0, result);
+ assertEquals(0, writeOnlyFileChannel.position());
+ assertEquals(READONLYFILECHANNELPOSITION, readOnlyFileChannel
+ .position());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long)
+ */
+ public void test_transferFromLReadableByteChannelJJ_FileChannel()
+ throws Exception {
+ // init data to file.
+ writeDataToFile(fileOfReadOnlyFileChannel);
+ writeDataToFile(fileOfWriteOnlyFileChannel);
+
+ final int READONLYFILECHANNELPOSITION = 2;
+ final int WRITEONLYFILECHANNELPOSITION = 4;
+ readOnlyFileChannel.position(READONLYFILECHANNELPOSITION);
+ writeOnlyFileChannel.position(WRITEONLYFILECHANNELPOSITION);
+
+ final int POSITION = 3;
+ final int LENGTH = 5;
+ long result = writeOnlyFileChannel.transferFrom(readOnlyFileChannel,
+ POSITION, LENGTH);
+ assertEquals(LENGTH, result);
+ assertEquals(WRITEONLYFILECHANNELPOSITION, writeOnlyFileChannel
+ .position());
+ assertEquals(READONLYFILECHANNELPOSITION + LENGTH, readOnlyFileChannel
+ .position());
+ writeOnlyFileChannel.close();
+
+ final int EXPECTED_LENGTH = POSITION + LENGTH;
+ fis = new FileInputStream(fileOfWriteOnlyFileChannel);
+ byte[] resultContent = new byte[EXPECTED_LENGTH];
+ fis.read(resultContent);
+
+ byte[] expectedContent = new byte[EXPECTED_LENGTH];
+ System.arraycopy(CONTENT_AS_BYTES, 0, expectedContent, 0, POSITION);
+ System.arraycopy(CONTENT_AS_BYTES, READONLYFILECHANNELPOSITION,
+ expectedContent, POSITION, LENGTH);
+ assertTrue(Arrays.equals(expectedContent, resultContent));
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long)
+ */
+ public void test_transferFromLReadableByteChannelJJ_DatagramChannel()
+ throws Exception {
+ // connects two datagramChannels.
+ datagramChannelReceiver = DatagramChannel.open();
+ datagramChannelReceiver.socket().bind(
+ new InetSocketAddress(InetAddress.getLocalHost(), 0));
+ datagramChannelSender = DatagramChannel.open();
+ datagramChannelSender.socket().bind(
+ new InetSocketAddress(InetAddress.getLocalHost(), 0));
+ datagramChannelReceiver.socket().setSoTimeout(TIME_OUT);
+ datagramChannelReceiver.connect(datagramChannelSender.socket()
+ .getLocalSocketAddress());
+ datagramChannelSender.socket().setSoTimeout(TIME_OUT);
+ ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES);
+ datagramChannelSender.socket().setSoTimeout(TIME_OUT);
+ // sends data from datagramChannelSender to datagramChannelReceiver.
+ datagramChannelSender.send(writeBuffer, datagramChannelReceiver
+ .socket().getLocalSocketAddress());
+ datagramChannelReceiver.socket().setSoTimeout(TIME_OUT);
+
+ // transfers data from datagramChannelReceiver to fileChannel.
+ long result = writeOnlyFileChannel.transferFrom(
+ datagramChannelReceiver, 0, CONTENT_AS_BYTES_LENGTH);
+ assertEquals(CONTENT_AS_BYTES_LENGTH, result);
+ assertEquals(0, writeOnlyFileChannel.position());
+ writeOnlyFileChannel.close();
+
+ // gets content from file.
+ fis = new FileInputStream(fileOfWriteOnlyFileChannel);
+ assertEquals(CONTENT_AS_BYTES_LENGTH, fileOfWriteOnlyFileChannel
+ .length());
+ byte[] resultContent = new byte[CONTENT_AS_BYTES_LENGTH];
+ fis.read(resultContent);
+
+ // compares contents.
+ assertTrue(Arrays.equals(CONTENT_AS_BYTES, resultContent));
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long)
+ */
+ public void test_transferFromLReadableByteChannelJJ_SocketChannel()
+ throws Exception {
+ // connects two socketChannels.
+ socketChannelReceiver = SocketChannel.open();
+ serverSocketChannel = ServerSocketChannel.open();
+ serverSocketChannel.socket().bind(
+ new InetSocketAddress(InetAddress.getLocalHost(), 0));
+ socketChannelReceiver.socket().setSoTimeout(TIME_OUT);
+ socketChannelReceiver.connect(serverSocketChannel.socket()
+ .getLocalSocketAddress());
+ serverSocketChannel.socket().setSoTimeout(TIME_OUT);
+ socketChannelSender = serverSocketChannel.accept();
+ socketChannelSender.socket().setSoTimeout(TIME_OUT);
+
+ // sends data from socketChannelSender to socketChannelReceiver.
+ ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES);
+ socketChannelSender.write(writeBuffer);
+
+ // transfers data from socketChannelReceiver to fileChannel.
+ long result = readWriteFileChannel.transferFrom(socketChannelReceiver,
+ 0, CONTENT_AS_BYTES_LENGTH);
+ assertEquals(CONTENT_AS_BYTES_LENGTH, result);
+ assertEquals(0, readWriteFileChannel.position());
+ readWriteFileChannel.close();
+
+ // gets content from file.
+ fis = new FileInputStream(fileOfReadWriteFileChannel);
+ assertEquals(CONTENT_AS_BYTES_LENGTH, fileOfReadWriteFileChannel
+ .length());
+ byte[] resultContent = new byte[CONTENT_AS_BYTES_LENGTH];
+ fis.read(resultContent);
+
+ // compares content.
+ assertTrue(Arrays.equals(CONTENT_AS_BYTES, resultContent));
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferFrom(ReadableByteChannel,long,long)
+ */
+ public void test_transferFromLReadableByteChannelJJ_Pipe() throws Exception {
+ // inits data in file.
+ writeDataToFile(fileOfWriteOnlyFileChannel);
+
+ // inits pipe.
+ pipe = Pipe.open();
+
+ // writes content to pipe.
+ ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES);
+ pipe.sink().write(writeBuffer);
+
+ // transfers data from pipe to fileChannel.
+ final int OFFSET = 2;
+ final int LENGTH = 4;
+ long result = writeOnlyFileChannel.transferFrom(pipe.source(), OFFSET,
+ LENGTH);
+ assertEquals(LENGTH, result);
+ writeOnlyFileChannel.close();
+
+ // gets content from file.
+ fis = new FileInputStream(fileOfWriteOnlyFileChannel);
+ byte[] resultBytes = new byte[OFFSET + LENGTH];
+ fis.read(resultBytes);
+
+ // compares content.
+ byte[] expectedBytes = new byte[OFFSET + LENGTH];
+ System.arraycopy(CONTENT_AS_BYTES, 0, expectedBytes, 0, OFFSET);
+ System.arraycopy(CONTENT_AS_BYTES, 0, expectedBytes, OFFSET, LENGTH);
+
+ assertTrue(Arrays.equals(expectedBytes, resultBytes));
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel)
+ */
+ public void test_transferToJJLWritableByteChannel_Null() throws Exception {
+ writableByteChannel = null;
+ try {
+ readOnlyFileChannel.transferTo(0, 10, writableByteChannel);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ writeOnlyFileChannel.transferTo(0, 10, writableByteChannel);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (NonReadableChannelException expected) {
+ }
+
+ try {
+ readWriteFileChannel.transferTo(0, 10, writableByteChannel);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ readOnlyFileChannel.close();
+ try {
+ writeOnlyFileChannel.transferTo(-1, 0, writableByteChannel);
+ fail();
+ } catch (NullPointerException expected) {
+ } catch (NonReadableChannelException expected) {
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel)
+ */
+ public void test_transferToJJLWritableByteChannel_Closed() throws Exception {
+ writableByteChannel = DatagramChannel.open();
+ readOnlyFileChannel.close();
+ try {
+ readOnlyFileChannel.transferTo(0, 10, writableByteChannel);
+ fail("should throw ClosedChannelException.");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ writeOnlyFileChannel.close();
+ try {
+ writeOnlyFileChannel.transferTo(0, 10, writableByteChannel);
+ fail("should throw ClosedChannelException.");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ readWriteFileChannel.close();
+ try {
+ readWriteFileChannel.transferTo(0, 10, writableByteChannel);
+ fail("should throw ClosedChannelException.");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ // should throw ClosedChannelException first.
+ try {
+ readWriteFileChannel.transferTo(0, -1, writableByteChannel);
+ fail("should throw ClosedChannelException.");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ }
+
+ public void test_transferToJJLWritableByteChannel_SourceClosed() throws Exception {
+ writableByteChannel = DatagramChannel.open();
+ writableByteChannel.close();
+
+ try {
+ readOnlyFileChannel.transferTo(0, 10, writableByteChannel);
+ fail();
+ } catch (ClosedChannelException expected) {
+ }
+
+ try {
+ writeOnlyFileChannel.transferTo(0, 10, writableByteChannel);
+ fail();
+ } catch (ClosedChannelException expected) {
+ } catch (NonReadableChannelException expected) {
+ }
+
+ try {
+ readWriteFileChannel.transferTo(0, 10, writableByteChannel);
+ fail();
+ } catch (ClosedChannelException expected) {
+ }
+
+ try {
+ readWriteFileChannel.transferTo(0, -1, writableByteChannel);
+ fail();
+ } catch (ClosedChannelException expected) {
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel)
+ */
+ public void test_transferToJJLWritableByteChannel_IllegalArgument()
+ throws Exception {
+ writableByteChannel = DatagramChannel.open();
+ try {
+ readOnlyFileChannel.transferTo(10, -1, writableByteChannel);
+ fail("should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+
+ try {
+ readWriteFileChannel.transferTo(-1, -10, writableByteChannel);
+ fail("should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ public void test_transferToJJLWritableByteChannel_NonReadable() throws Exception {
+ writableByteChannel = DatagramChannel.open();
+ try {
+ writeOnlyFileChannel.transferTo(0, 10, writableByteChannel);
+ fail();
+ } catch (NonReadableChannelException expected) {
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel)
+ */
+ public void test_transferToJJLWritableByteChannel_TargetNonWritable()
+ throws Exception {
+ try {
+ readWriteFileChannel.transferTo(0, 0, readOnlyFileChannel);
+ fail("should throw NonWritableChannelException.");
+ } catch (NonWritableChannelException e) {
+ // expected
+ }
+
+ // first throws NonWritableChannelException even position out of file
+ // size.
+ try {
+ readWriteFileChannel.transferTo(10, 10, readOnlyFileChannel);
+ fail("should throw NonWritableChannelException.");
+ } catch (NonWritableChannelException e) {
+ // expected
+ }
+
+ // regression test for Harmony-941
+ // first throws NonWritableChannelException even arguments are illegal.
+ try {
+ readWriteFileChannel.transferTo(-1, 10, readOnlyFileChannel);
+ fail("should throw NonWritableChannelException.");
+ } catch (NonWritableChannelException e) {
+ // expected
+ }
+
+ try {
+ readWriteFileChannel.transferTo(0, -1, readOnlyFileChannel);
+ fail("should throw NonWritableChannelException.");
+ } catch (NonWritableChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel)
+ */
+ public void test_transferToJJLWritableByteChannel_PositionBeyondSize()
+ throws Exception {
+ // init data to file.
+ writeDataToFile(fileOfReadOnlyFileChannel);
+ writeDataToFile(fileOfWriteOnlyFileChannel);
+
+ final int WRITEONLYFILECHANNELPOSITION = 2;
+ writeOnlyFileChannel.position(WRITEONLYFILECHANNELPOSITION);
+
+ final int POSITION = CONTENT_AS_BYTES_LENGTH * 2;
+ final int LENGTH = 5;
+ long result = readOnlyFileChannel.transferTo(POSITION, LENGTH,
+ writeOnlyFileChannel);
+ assertEquals(0, result);
+ assertEquals(0, readOnlyFileChannel.position());
+ assertEquals(WRITEONLYFILECHANNELPOSITION, writeOnlyFileChannel
+ .position());
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel)
+ */
+ public void test_transferToJJLWritableByteChannel_FileChannel()
+ throws Exception {
+ // init data to file.
+ writeDataToFile(fileOfReadOnlyFileChannel);
+ writeDataToFile(fileOfWriteOnlyFileChannel);
+
+ final int READONLYFILECHANNELPOSITION = 2;
+ final int WRITEONLYFILECHANNELPOSITION = 4;
+ readOnlyFileChannel.position(READONLYFILECHANNELPOSITION);
+ writeOnlyFileChannel.position(WRITEONLYFILECHANNELPOSITION);
+
+ final int POSITION = 3;
+ final int LENGTH = 5;
+ long result = readOnlyFileChannel.transferTo(POSITION, LENGTH,
+ writeOnlyFileChannel);
+ assertEquals(LENGTH, result);
+ assertEquals(READONLYFILECHANNELPOSITION, readOnlyFileChannel
+ .position());
+ assertEquals(WRITEONLYFILECHANNELPOSITION + LENGTH,
+ writeOnlyFileChannel.position());
+ writeOnlyFileChannel.close();
+
+ final int EXPECTED_LENGTH = WRITEONLYFILECHANNELPOSITION + LENGTH;
+ fis = new FileInputStream(fileOfWriteOnlyFileChannel);
+ byte[] resultContent = new byte[EXPECTED_LENGTH];
+ fis.read(resultContent);
+
+ byte[] expectedContent = new byte[EXPECTED_LENGTH];
+ System.arraycopy(CONTENT_AS_BYTES, 0, expectedContent, 0,
+ WRITEONLYFILECHANNELPOSITION);
+ System.arraycopy(CONTENT_AS_BYTES, POSITION, expectedContent,
+ WRITEONLYFILECHANNELPOSITION, LENGTH);
+ assertTrue(Arrays.equals(expectedContent, resultContent));
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel)
+ */
+ public void test_transferToJJLWritableByteChannel_SocketChannel()
+ throws Exception {
+ // inits data into file.
+ writeDataToFile(fileOfReadOnlyFileChannel);
+
+ // connects two socketChannels.
+ socketChannelReceiver = SocketChannel.open();
+ socketChannelReceiver.socket().bind(
+ new InetSocketAddress(InetAddress.getLocalHost(), 0));
+ serverSocketChannel = ServerSocketChannel.open();
+ serverSocketChannel.socket().bind(
+ new InetSocketAddress(InetAddress.getLocalHost(), 0));
+ socketChannelReceiver.socket().setSoTimeout(TIME_OUT);
+ socketChannelReceiver.connect(serverSocketChannel.socket()
+ .getLocalSocketAddress());
+ serverSocketChannel.socket().setSoTimeout(TIME_OUT);
+ socketChannelSender = serverSocketChannel.accept();
+ socketChannelSender.socket().setSoTimeout(TIME_OUT);
+
+ // position here should have no effect on transferTo since it uses
+ // offset from file_begin
+ final int POSITION = 10;
+ readOnlyFileChannel.position(POSITION);
+
+ // transfers data from file to socketChannelSender.
+ final int OFFSET = 2;
+ long result = readOnlyFileChannel.transferTo(OFFSET,
+ CONTENT_AS_BYTES_LENGTH * 2, socketChannelSender);
+ final int LENGTH = CONTENT_AS_BYTES_LENGTH - OFFSET;
+ assertEquals(LENGTH, result);
+ assertEquals(POSITION, readOnlyFileChannel.position());
+ readOnlyFileChannel.close();
+ socketChannelSender.close();
+
+ // gets contents from socketChannelReceiver.
+ ByteBuffer readBuffer = ByteBuffer.allocate(LENGTH + 1);
+ int totalRead = 0;
+ int countRead = 0;
+ long beginTime = System.currentTimeMillis();
+ while ((countRead = socketChannelReceiver.read(readBuffer)) != -1) {
+ totalRead += countRead;
+ // TIMEOUT
+ if (System.currentTimeMillis() - beginTime > TIME_OUT) {
+ break;
+ }
+ }
+ assertEquals(LENGTH, totalRead);
+
+ // compares contents.
+ readBuffer.flip();
+ for (int i = OFFSET; i < CONTENT_AS_BYTES_LENGTH; i++) {
+ assertEquals(CONTENT_AS_BYTES[i], readBuffer.get());
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel)
+ */
+ public void test_transferToJJLWritableByteChannel_DatagramChannel()
+ throws Exception {
+ // inits data to file.
+ writeDataToFile(fileOfReadOnlyFileChannel);
+
+ // connects two datagramChannel
+ datagramChannelReceiver = DatagramChannel.open();
+ datagramChannelReceiver.socket().bind(
+ new InetSocketAddress(InetAddress.getLocalHost(), 0));
+ datagramChannelSender = DatagramChannel.open();
+ datagramChannelSender.socket().bind(
+ new InetSocketAddress(InetAddress.getLocalHost(), 0));
+ datagramChannelSender.socket().setSoTimeout(TIME_OUT);
+ datagramChannelSender.connect(datagramChannelReceiver.socket()
+ .getLocalSocketAddress());
+ datagramChannelReceiver.socket().setSoTimeout(TIME_OUT);
+ datagramChannelReceiver.connect(datagramChannelSender.socket()
+ .getLocalSocketAddress());
+
+ // transfers data from fileChannel to datagramChannelSender
+ long result = readOnlyFileChannel.transferTo(0,
+ CONTENT_AS_BYTES_LENGTH, datagramChannelSender);
+ assertEquals(CONTENT_AS_BYTES_LENGTH, result);
+ assertEquals(0, readOnlyFileChannel.position());
+ readOnlyFileChannel.close();
+ datagramChannelSender.close();
+
+ // gets contents from datagramChannelReceiver
+ ByteBuffer readBuffer = ByteBuffer.allocate(CONTENT_AS_BYTES_LENGTH);
+ long beginTime = System.currentTimeMillis();
+ int totalRead = 0;
+ while (totalRead < CONTENT_AS_BYTES_LENGTH) {
+ totalRead += datagramChannelReceiver.read(readBuffer);
+ if (System.currentTimeMillis() - beginTime > TIME_OUT) {
+ break;
+ }
+ }
+ assertEquals(CONTENT_AS_BYTES_LENGTH, totalRead);
+
+ // compares contents.
+ readBuffer.flip();
+ for (int i = 0; i < CONTENT_AS_BYTES_LENGTH; i++) {
+ assertEquals(CONTENT_AS_BYTES[i], readBuffer.get());
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileChannel#transferTo(long,long,WritableByteChannel)
+ */
+ public void test_transferToJJLWritableByteChannel_Pipe() throws Exception {
+ // inits data in file.
+ writeDataToFile(fileOfReadOnlyFileChannel);
+
+ // inits pipe.
+ pipe = Pipe.open();
+
+ // transfers data from fileChannel to pipe.
+ final int OFFSET = 2;
+ final int LENGTH = 4;
+ long result = readOnlyFileChannel.transferTo(OFFSET, LENGTH, pipe
+ .sink());
+ assertEquals(LENGTH, result);
+ assertEquals(0, readOnlyFileChannel.position());
+ readOnlyFileChannel.close();
+
+ // gets content from pipe.
+ ByteBuffer readBuffer = ByteBuffer.allocate(LENGTH);
+ result = pipe.source().read(readBuffer);
+ assertEquals(LENGTH, result);
+
+ // compares content.
+ readBuffer.flip();
+ for (int i = OFFSET; i < OFFSET + LENGTH; i++) {
+ assertEquals(CONTENT_AS_BYTES[i], readBuffer.get());
+ }
+ }
+
+ /**
+ * Regression test for Harmony-3324
+ * Make sure we could delete the file after we called transferTo() method.
+ */
+ public void test_transferTo_couldDelete() throws Exception {
+ // init data in files
+ writeDataToFile(fileOfReadOnlyFileChannel);
+ writeDataToFile(fileOfWriteOnlyFileChannel);
+
+ // call transferTo() method
+ readOnlyFileChannel.transferTo(0 , 2, writeOnlyFileChannel);
+
+ // delete both files
+ readOnlyFileChannel.close();
+ writeOnlyFileChannel.close();
+ boolean rDel = fileOfReadOnlyFileChannel.delete();
+ boolean wDel = fileOfWriteOnlyFileChannel.delete();
+
+ // make sure both files were deleted
+ assertTrue("File " + readOnlyFileChannel + " exists", rDel);
+ assertTrue("File " + writeOnlyFileChannel + " exists", wDel);
+ }
+
+ /**
+ * Regression test for Harmony-3324
+ * Make sure we could delete the file after we called transferFrom() method.
+ */
+ public void test_transferFrom_couldDelete() throws Exception {
+ // init data in files
+ writeDataToFile(fileOfReadOnlyFileChannel);
+ writeDataToFile(fileOfWriteOnlyFileChannel);
+
+ // call transferTo() method
+ writeOnlyFileChannel.transferFrom(readOnlyFileChannel, 0 , 2);
+
+ // delete both files
+ readOnlyFileChannel.close();
+ writeOnlyFileChannel.close();
+ boolean rDel = fileOfReadOnlyFileChannel.delete();
+ boolean wDel = fileOfWriteOnlyFileChannel.delete();
+
+ // make sure both files were deleted
+ assertTrue("File " + readOnlyFileChannel + " exists", rDel);
+ assertTrue("File " + writeOnlyFileChannel + " exists", wDel);
+ }
+
+ private class MockFileChannel extends FileChannel {
+
+ private boolean isLockCalled = false;
+
+ private boolean isTryLockCalled = false;
+
+ private boolean isReadCalled = false;
+
+ private boolean isWriteCalled = false;
+
+ public void force(boolean arg0) throws IOException {
+ // do nothing
+ }
+
+ public FileLock lock(long position, long size, boolean shared)
+ throws IOException {
+ // verify that calling lock() leads to the method
+ // lock(0, Long.MAX_VALUE, false).
+ if (0 == position && Long.MAX_VALUE == size && false == shared) {
+ isLockCalled = true;
+ }
+ return null;
+ }
+
+ public MappedByteBuffer map(MapMode arg0, long arg1, long arg2)
+ throws IOException {
+ return null;
+ }
+
+ public long position() throws IOException {
+ return 0;
+ }
+
+ public FileChannel position(long arg0) throws IOException {
+ return null;
+ }
+
+ public int read(ByteBuffer arg0) throws IOException {
+ return 0;
+ }
+
+ public int read(ByteBuffer arg0, long arg1) throws IOException {
+ return 0;
+ }
+
+ public long read(ByteBuffer[] srcs, int offset, int length)
+ throws IOException {
+ // verify that calling read(ByteBuffer[] srcs) leads to the method
+ // read(srcs, 0, srcs.length)
+ if (0 == offset && length == srcs.length) {
+ isReadCalled = true;
+ }
+ return 0;
+ }
+
+ public long size() throws IOException {
+ return 0;
+ }
+
+ public long transferFrom(ReadableByteChannel arg0, long arg1, long arg2)
+ throws IOException {
+ return 0;
+ }
+
+ public long transferTo(long arg0, long arg1, WritableByteChannel arg2)
+ throws IOException {
+ return 0;
+ }
+
+ public FileChannel truncate(long arg0) throws IOException {
+ return null;
+ }
+
+ public FileLock tryLock(long position, long size, boolean shared)
+ throws IOException {
+ // verify that calling tryLock() leads to the method
+ // tryLock(0, Long.MAX_VALUE, false).
+ if (0 == position && Long.MAX_VALUE == size && false == shared) {
+ isTryLockCalled = true;
+ }
+ return null;
+ }
+
+ public int write(ByteBuffer arg0) throws IOException {
+ return 0;
+ }
+
+ public int write(ByteBuffer arg0, long arg1) throws IOException {
+ return 0;
+ }
+
+ public long write(ByteBuffer[] srcs, int offset, int length)
+ throws IOException {
+ // verify that calling write(ByteBuffer[] srcs) leads to the method
+ // write(srcs, 0, srcs.length)
+ if(0 == offset && length == srcs.length){
+ isWriteCalled = true;
+ }
+ return 0;
+ }
+
+ protected void implCloseChannel() throws IOException {
+
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockInterruptionExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockInterruptionExceptionTest.java
new file mode 100644
index 0000000..b60096c
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockInterruptionExceptionTest.java
@@ -0,0 +1,55 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.FileLockInterruptionException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for FileLockInterruptionException
+ */
+public class FileLockInterruptionExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.FileLockInterruptionException#FileLockInterruptionException()}
+ */
+ public void test_Constructor() {
+ FileLockInterruptionException e = new FileLockInterruptionException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new FileLockInterruptionException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this,
+ new FileLockInterruptionException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockTest.java
new file mode 100644
index 0000000..12142e8
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/FileLockTest.java
@@ -0,0 +1,199 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.FileChannel;
+import java.nio.channels.FileLock;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests class FileLock.
+ */
+public class FileLockTest extends TestCase {
+
+ private FileChannel readWriteChannel;
+
+ private MockFileLock mockLock;
+
+ class MockFileLock extends FileLock {
+
+ boolean isValid = true;
+
+ protected MockFileLock(FileChannel channel, long position, long size,
+ boolean shared) {
+ super(channel, position, size, shared);
+ }
+
+ public boolean isValid() {
+ return isValid;
+ }
+
+ public void release() throws IOException {
+ isValid = false;
+ }
+ }
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ File tempFile = File.createTempFile("testing", "tmp");
+ tempFile.deleteOnExit();
+ RandomAccessFile randomAccessFile = new RandomAccessFile(tempFile, "rw");
+ readWriteChannel = randomAccessFile.getChannel();
+ mockLock = new MockFileLock(readWriteChannel, 10, 100, false);
+ }
+
+ protected void tearDown() throws IOException {
+ if (readWriteChannel != null) {
+ readWriteChannel.close();
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileLock#FileLock(FileChannel, long, long,
+ * boolean)
+ */
+ public void test_Constructor_Ljava_nio_channels_FileChannelJJZ() {
+ FileLock fileLock1 = new MockFileLock(null, 0, 0, false);
+ assertNull(fileLock1.channel());
+
+ try {
+ new MockFileLock(readWriteChannel, -1, 0, false);
+ fail("should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException ex) {
+ // expected
+ }
+ try {
+ new MockFileLock(readWriteChannel, 0, -1, false);
+ fail("should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException ex) {
+ // expected
+ }
+ // Harmony-682 regression test
+ try {
+ new MockFileLock(readWriteChannel, Long.MAX_VALUE, 1, false);
+ fail("should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException ex) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.FileLock#channel()
+ */
+ public void test_channel() {
+ assertSame(readWriteChannel, mockLock.channel());
+ FileLock lock = new MockFileLock(null, 0, 10, true);
+ assertNull(lock.channel());
+ }
+
+ /**
+ * @tests java.nio.channels.FileLock#position()
+ */
+ public void test_position() {
+ FileLock fileLock1 = new MockFileLock(readWriteChannel, 20, 100, true);
+ assertEquals(20, fileLock1.position());
+
+ final long position = ((long) Integer.MAX_VALUE + 1);
+ FileLock fileLock2 = new MockFileLock(readWriteChannel, position, 100,
+ true);
+ assertEquals(position, fileLock2.position());
+ }
+
+ /**
+ * @tests java.nio.channels.FileLock#size()
+ */
+ public void test_size() {
+ FileLock fileLock1 = new MockFileLock(readWriteChannel, 20, 100, true);
+ assertEquals(100, fileLock1.size());
+
+ final long position = 0x0FFFFFFFFFFFFFFFL;
+ final long size = ((long) Integer.MAX_VALUE + 1);
+ FileLock fileLock2 = new MockFileLock(readWriteChannel, position, size,
+ true);
+ assertEquals(size, fileLock2.size());
+ }
+
+ /**
+ * @tests java.nio.channels.FileLock#isShared()
+ */
+ public void test_isShared() {
+ assertFalse(mockLock.isShared());
+ FileLock lock = new MockFileLock(null, 0, 10, true);
+ assertTrue(lock.isShared());
+ }
+
+ /**
+ * @tests java.nio.channels.FileLock#overlaps(long, long)
+ */
+ public void test_overlaps_JJ() {
+ assertTrue(mockLock.overlaps(0, 11));
+ assertFalse(mockLock.overlaps(0, 10));
+ assertTrue(mockLock.overlaps(100, 110));
+ assertTrue(mockLock.overlaps(99, 110));
+ assertFalse(mockLock.overlaps(-1, 10));
+ //Harmony-671 regression test
+ assertTrue(mockLock.overlaps(1, 120));
+ assertTrue(mockLock.overlaps(20, 50));
+ }
+
+ /**
+ * @tests java.nio.channels.FileLock#isValid()
+ */
+ public void test_isValid() throws IOException {
+ FileLock fileLock = readWriteChannel.lock();
+ assertTrue(fileLock.isValid());
+ fileLock.release();
+ assertFalse(fileLock.isValid());
+ }
+
+ /**
+ * @tests java.nio.channels.FileLock#release()
+ */
+ public void test_release() throws Exception {
+ File file = File.createTempFile("test", "tmp");
+ file.deleteOnExit();
+ FileOutputStream fout = new FileOutputStream(file);
+ FileChannel fileChannel = fout.getChannel();
+ FileLock fileLock = fileChannel.lock();
+ fileChannel.close();
+ try {
+ fileLock.release();
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ // release after release
+ fout = new FileOutputStream(file);
+ fileChannel = fout.getChannel();
+ fileLock = fileChannel.lock();
+ fileLock.release();
+ fileChannel.close();
+ try {
+ fileLock.release();
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ //expected
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalBlockingModeExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalBlockingModeExceptionTest.java
new file mode 100644
index 0000000..a8cdf83
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalBlockingModeExceptionTest.java
@@ -0,0 +1,55 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.IllegalBlockingModeException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for IllegalBlockingModeException
+ */
+public class IllegalBlockingModeExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.IllegalBlockingModeException#IllegalBlockingModeException()}
+ */
+ public void test_Constructor() {
+ IllegalBlockingModeException e = new IllegalBlockingModeException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new IllegalBlockingModeException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest
+ .verifyGolden(this, new IllegalBlockingModeException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalSelectorExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalSelectorExceptionTest.java
new file mode 100644
index 0000000..2fa3171
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/IllegalSelectorExceptionTest.java
@@ -0,0 +1,54 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.IllegalSelectorException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for IllegalSelectorException
+ */
+public class IllegalSelectorExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.IllegalSelectorException#IllegalSelectorException()}
+ */
+ public void test_Constructor() {
+ IllegalSelectorException e = new IllegalSelectorException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new IllegalSelectorException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new IllegalSelectorException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MapModeTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MapModeTest.java
new file mode 100644
index 0000000..33234eb
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MapModeTest.java
@@ -0,0 +1,52 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.FileChannel;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for FileChannel.MapMode
+ */
+public class MapModeTest extends TestCase {
+
+ /**
+ * java.nio.channels.FileChannel.MapMode#PRIVATE,READONLY,READWRITE
+ */
+ public void test_PRIVATE_READONLY_READWRITE() {
+ assertNotNull(FileChannel.MapMode.PRIVATE);
+ assertNotNull(FileChannel.MapMode.READ_ONLY);
+ assertNotNull(FileChannel.MapMode.READ_WRITE);
+
+ assertFalse(FileChannel.MapMode.PRIVATE
+ .equals(FileChannel.MapMode.READ_ONLY));
+ assertFalse(FileChannel.MapMode.PRIVATE
+ .equals(FileChannel.MapMode.READ_WRITE));
+ assertFalse(FileChannel.MapMode.READ_ONLY
+ .equals(FileChannel.MapMode.READ_WRITE));
+ }
+
+ /**
+ * java.nio.channels.FileChannel.MapMode#toString()
+ */
+ public void test_toString() {
+ assertNotNull(FileChannel.MapMode.PRIVATE.toString());
+ assertNotNull(FileChannel.MapMode.READ_ONLY.toString());
+ assertNotNull(FileChannel.MapMode.READ_WRITE.toString());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockServerSocketChannel.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockServerSocketChannel.java
new file mode 100644
index 0000000..2058a7a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockServerSocketChannel.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.io.IOException;
+import java.net.ServerSocket;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.nio.channels.spi.SelectorProvider;
+
+class MockServerSocketChannel extends ServerSocketChannel {
+
+ protected MockServerSocketChannel(SelectorProvider arg0) {
+ super(arg0);
+ }
+
+ public ServerSocket socket() {
+ return null;
+ }
+
+ public SocketChannel accept() throws IOException {
+ return null;
+ }
+
+ protected void implCloseSelectableChannel() throws IOException {
+ }
+
+ protected void implConfigureBlocking(boolean arg0) throws IOException {
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockSocketChannel.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockSocketChannel.java
new file mode 100644
index 0000000..9d130ca
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/MockSocketChannel.java
@@ -0,0 +1,75 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.io.IOException;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.SocketChannel;
+import java.nio.channels.spi.SelectorProvider;
+
+class MockSocketChannel extends SocketChannel {
+
+ protected MockSocketChannel(SelectorProvider arg0) {
+ super(arg0);
+ }
+
+ public Socket socket() {
+ return null;
+ }
+
+ public boolean isConnected() {
+ return false;
+ }
+
+ public boolean isConnectionPending() {
+ return false;
+ }
+
+ public boolean connect(SocketAddress arg0) throws IOException {
+ return false;
+ }
+
+ public boolean finishConnect() throws IOException {
+ return false;
+ }
+
+ public int read(ByteBuffer arg0) throws IOException {
+ return 0;
+ }
+
+ public long read(ByteBuffer[] arg0, int arg1, int arg2) throws IOException {
+ return 0;
+ }
+
+ public int write(ByteBuffer arg0) throws IOException {
+ return 0;
+ }
+
+ public long write(ByteBuffer[] arg0, int arg1, int arg2) throws IOException {
+ return 0;
+ }
+
+ protected void implCloseSelectableChannel() throws IOException {
+ }
+
+ protected void implConfigureBlocking(boolean arg0) throws IOException {
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NoConnectionPendingExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NoConnectionPendingExceptionTest.java
new file mode 100644
index 0000000..2ba7ba6
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NoConnectionPendingExceptionTest.java
@@ -0,0 +1,55 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.NoConnectionPendingException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for NoConnectionPendingException
+ */
+public class NoConnectionPendingExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.NoConnectionPendingException#NoConnectionPendingException()}
+ */
+ public void test_Constructor() {
+ NoConnectionPendingException e = new NoConnectionPendingException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new NoConnectionPendingException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest
+ .verifyGolden(this, new NoConnectionPendingException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonReadableChannelExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonReadableChannelExceptionTest.java
new file mode 100644
index 0000000..8c44f17
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonReadableChannelExceptionTest.java
@@ -0,0 +1,54 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.NonReadableChannelException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for NonReadableChannelException
+ */
+public class NonReadableChannelExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.NonReadableChannelException#NonReadableChannelException()}
+ */
+ public void test_Constructor() {
+ NonReadableChannelException e = new NonReadableChannelException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new NonReadableChannelException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new NonReadableChannelException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonWritableChannelExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonWritableChannelExceptionTest.java
new file mode 100644
index 0000000..459d85a
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NonWritableChannelExceptionTest.java
@@ -0,0 +1,54 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.NonWritableChannelException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for NonWritableChannelException
+ */
+public class NonWritableChannelExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.NonWritableChannelException#NonWritableChannelException()}
+ */
+ public void test_Constructor() {
+ NonWritableChannelException e = new NonWritableChannelException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new NonWritableChannelException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new NonWritableChannelException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetBoundExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetBoundExceptionTest.java
new file mode 100644
index 0000000..d1c2d86
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetBoundExceptionTest.java
@@ -0,0 +1,54 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.NotYetBoundException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for NotYetBoundException
+ */
+public class NotYetBoundExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.NotYetBoundException#NotYetBoundException()}
+ */
+ public void test_Constructor() {
+ NotYetBoundException e = new NotYetBoundException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new NotYetBoundException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new NotYetBoundException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetConnectedExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetConnectedExceptionTest.java
new file mode 100644
index 0000000..09e4c1c
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/NotYetConnectedExceptionTest.java
@@ -0,0 +1,54 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.NotYetConnectedException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for NotYetConnectedException
+ */
+public class NotYetConnectedExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.NotYetConnectedException#NotYetConnectedException()}
+ */
+ public void test_Constructor() {
+ NotYetConnectedException e = new NotYetConnectedException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new NotYetConnectedException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new NotYetConnectedException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/OverlappingFileLockExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/OverlappingFileLockExceptionTest.java
new file mode 100644
index 0000000..d06f807
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/OverlappingFileLockExceptionTest.java
@@ -0,0 +1,55 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.OverlappingFileLockException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for OverlappingFileLockException
+ */
+public class OverlappingFileLockExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.OverlappingFileLockException#OverlappingFileLockException()}
+ */
+ public void test_Constructor() {
+ OverlappingFileLockException e = new OverlappingFileLockException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new OverlappingFileLockException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest
+ .verifyGolden(this, new OverlappingFileLockException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/PipeTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/PipeTest.java
new file mode 100644
index 0000000..53f19c4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/PipeTest.java
@@ -0,0 +1,59 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.io.IOException;
+import java.net.NetPermission;
+import java.nio.channels.Pipe;
+import java.nio.channels.Pipe.SinkChannel;
+import java.nio.channels.Pipe.SourceChannel;
+import java.security.Permission;
+
+import junit.framework.TestCase;
+
+/*
+ * Tests for Pipe and its default implementation
+ */
+public class PipeTest extends TestCase {
+
+ /**
+ * @tests java.nio.channels.Pipe#open()
+ */
+ public void test_open() throws IOException{
+ Pipe pipe = Pipe.open();
+ assertNotNull(pipe);
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe#sink()
+ */
+ public void test_sink() throws IOException {
+ Pipe pipe = Pipe.open();
+ SinkChannel sink = pipe.sink();
+ assertTrue(sink.isBlocking());
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe#source()
+ */
+ public void test_source() throws IOException {
+ Pipe pipe = Pipe.open();
+ SourceChannel source = pipe.source();
+ assertTrue(source.isBlocking());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectableChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectableChannelTest.java
new file mode 100644
index 0000000..25b5f00
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectableChannelTest.java
@@ -0,0 +1,89 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.io.IOException;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.SelectableChannel;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.spi.SelectorProvider;
+import junit.framework.TestCase;
+
+/*
+ * Tests for SelectableChannel
+ */
+public class SelectableChannelTest extends TestCase {
+
+ /**
+ * @tests SelectableChannel#register(Selector, int)
+ */
+ public void test_register_LSelectorI() throws IOException {
+ MockSelectableChannel msc = new MockSelectableChannel();
+ // Verify that calling register(Selector, int) leads to the method
+ // register(Selector, int, Object) being called with a null value
+ // for the third argument.
+ msc.register(Selector.open(), SelectionKey.OP_ACCEPT);
+ assertTrue(msc.isCalled);
+ }
+
+ private class MockSelectableChannel extends SelectableChannel {
+
+ private boolean isCalled = false;
+
+ public Object blockingLock() {
+ return null;
+ }
+
+ public SelectableChannel configureBlocking(boolean block)
+ throws IOException {
+ return null;
+ }
+
+ public boolean isBlocking() {
+ return false;
+ }
+
+ public boolean isRegistered() {
+ return false;
+ }
+
+ public SelectionKey keyFor(Selector sel) {
+ return null;
+ }
+
+ public SelectorProvider provider() {
+ return null;
+ }
+
+ public SelectionKey register(Selector sel, int ops, Object att)
+ throws ClosedChannelException {
+ if (null == att) {
+ isCalled = true;
+ }
+ return null;
+ }
+
+ public int validOps() {
+ return 0;
+ }
+
+ protected void implCloseChannel() throws IOException {
+ // empty
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectionKeyTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectionKeyTest.java
new file mode 100644
index 0000000..ed33752
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectionKeyTest.java
@@ -0,0 +1,321 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.nio.channels.CancelledKeyException;
+import java.nio.channels.SelectableChannel;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.SocketChannel;
+
+import junit.framework.TestCase;
+import tests.support.Support_PortManager;
+
+/*
+ * Tests for SelectionKey and its default implementation
+ */
+public class SelectionKeyTest extends TestCase {
+
+ Selector selector;
+
+ SocketChannel sc;
+
+ SelectionKey selectionKey;
+
+ private static String LOCAL_ADDR = "127.0.0.1";
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ selector = Selector.open();
+ sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ selectionKey = sc.register(selector, SelectionKey.OP_CONNECT);
+ }
+
+ protected void tearDown() throws Exception {
+ selectionKey.cancel();
+ selectionKey = null;
+ selector.close();
+ selector = null;
+ super.tearDown();
+ }
+
+ static class MockSelectionKey extends SelectionKey {
+ private int interestOps;
+
+ MockSelectionKey(int ops) {
+ interestOps = ops;
+ }
+
+ public void cancel() {
+ // do nothing
+ }
+
+ public SelectableChannel channel() {
+ return null;
+ }
+
+ public int interestOps() {
+ return 0;
+ }
+
+ public SelectionKey interestOps(int operations) {
+ return null;
+ }
+
+ public boolean isValid() {
+ return true;
+ }
+
+ public int readyOps() {
+ return interestOps;
+ }
+
+ public Selector selector() {
+ return null;
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.SelectionKey#attach(Object)
+ */
+ public void test_attach() {
+ MockSelectionKey mockSelectionKey = new MockSelectionKey(SelectionKey.OP_ACCEPT);
+ // no previous, return null
+ Object o = new Object();
+ Object check = mockSelectionKey.attach(o);
+ assertNull(check);
+
+ // null parameter is ok
+ check = mockSelectionKey.attach(null);
+ assertSame(o, check);
+
+ check = mockSelectionKey.attach(o);
+ assertNull(check);
+ }
+
+ /**
+ * @tests java.nio.channels.SelectionKey#attachment()
+ */
+ public void test_attachment() {
+ MockSelectionKey mockSelectionKey = new MockSelectionKey(SelectionKey.OP_ACCEPT);
+ assertNull(mockSelectionKey.attachment());
+ Object o = new Object();
+ mockSelectionKey.attach(o);
+ assertSame(o, mockSelectionKey.attachment());
+ }
+
+ /**
+ * @tests java.nio.channels.SelectionKey#channel()
+ */
+ public void test_channel() {
+ assertSame(sc, selectionKey.channel());
+ // can be invoked even canceled
+ selectionKey.cancel();
+ assertSame(sc, selectionKey.channel());
+ }
+
+ /**
+ * @tests java.nio.channels.SelectionKey#interestOps()
+ */
+ public void test_interestOps() {
+ assertEquals(SelectionKey.OP_CONNECT, selectionKey.interestOps());
+ }
+
+ /**
+ * @tests java.nio.channels.SelectionKey#interestOps(int)
+ */
+ public void test_interestOpsI() {
+ selectionKey.interestOps(SelectionKey.OP_WRITE);
+ assertEquals(SelectionKey.OP_WRITE, selectionKey.interestOps());
+
+ try {
+ selectionKey.interestOps(SelectionKey.OP_ACCEPT);
+ fail("should throw IAE.");
+ } catch (IllegalArgumentException ex) {
+ // expected;
+ }
+
+ try {
+ selectionKey.interestOps(~sc.validOps());
+ fail("should throw IAE.");
+ } catch (IllegalArgumentException ex) {
+ // expected;
+ }
+ try {
+ selectionKey.interestOps(-1);
+ fail("should throw IAE.");
+ } catch (IllegalArgumentException ex) {
+ // expected;
+ }
+
+ }
+
+ /**
+ * @tests java.nio.channels.SelectionKey#isValid()
+ */
+ public void test_isValid() {
+ assertTrue(selectionKey.isValid());
+ }
+
+ /**
+ * @tests java.nio.channels.SelectionKey#isValid()
+ */
+ public void test_isValid_KeyCancelled() {
+ selectionKey.cancel();
+ assertFalse(selectionKey.isValid());
+ }
+
+ /**
+ * @tests java.nio.channels.SelectionKey#isValid()
+ */
+ public void test_isValid_ChannelColsed() throws IOException {
+ sc.close();
+ assertFalse(selectionKey.isValid());
+ }
+
+ /**
+ * @tests java.nio.channels.SelectionKey#isValid()
+ */
+ public void test_isValid_SelectorClosed() throws IOException {
+ selector.close();
+ assertFalse(selectionKey.isValid());
+ }
+
+ /**
+ * @tests java.nio.channels.SelectionKey#isAcceptable()
+ */
+ public void test_isAcceptable() throws IOException {
+ MockSelectionKey mockSelectionKey1 = new MockSelectionKey(SelectionKey.OP_ACCEPT);
+ assertTrue(mockSelectionKey1.isAcceptable());
+ MockSelectionKey mockSelectionKey2 = new MockSelectionKey(SelectionKey.OP_CONNECT);
+ assertFalse(mockSelectionKey2.isAcceptable());
+ }
+
+ /**
+ * @tests java.nio.channels.SelectionKey#isConnectable()
+ */
+ public void test_isConnectable() {
+ MockSelectionKey mockSelectionKey1 = new MockSelectionKey(SelectionKey.OP_CONNECT);
+ assertTrue(mockSelectionKey1.isConnectable());
+ MockSelectionKey mockSelectionKey2 = new MockSelectionKey(SelectionKey.OP_ACCEPT);
+ assertFalse(mockSelectionKey2.isConnectable());
+ }
+
+ /**
+ * @tests java.nio.channels.SelectionKey#isReadable()
+ */
+ public void test_isReadable() {
+ MockSelectionKey mockSelectionKey1 = new MockSelectionKey(SelectionKey.OP_READ);
+ assertTrue(mockSelectionKey1.isReadable());
+ MockSelectionKey mockSelectionKey2 = new MockSelectionKey(SelectionKey.OP_ACCEPT);
+ assertFalse(mockSelectionKey2.isReadable());
+ }
+
+ /**
+ * @tests java.nio.channels.SelectionKey#isWritable()
+ */
+ public void test_isWritable() {
+ MockSelectionKey mockSelectionKey1 = new MockSelectionKey(SelectionKey.OP_WRITE);
+ assertTrue(mockSelectionKey1.isWritable());
+ MockSelectionKey mockSelectionKey2 = new MockSelectionKey(SelectionKey.OP_ACCEPT);
+ assertFalse(mockSelectionKey2.isWritable());
+ }
+
+ /**
+ * @tests java.nio.channels.SelectionKey#cancel()
+ */
+ public void test_cancel() {
+ selectionKey.cancel();
+ try {
+ selectionKey.isAcceptable();
+ fail("should throw CancelledKeyException.");
+ } catch (CancelledKeyException ex) {
+ // expected
+ }
+ try {
+ selectionKey.isConnectable();
+ fail("should throw CancelledKeyException.");
+ } catch (CancelledKeyException ex) {
+ // expected
+ }
+ try {
+ selectionKey.isReadable();
+ fail("should throw CancelledKeyException.");
+ } catch (CancelledKeyException ex) {
+ // expected
+ }
+ try {
+ selectionKey.isWritable();
+ fail("should throw CancelledKeyException.");
+ } catch (CancelledKeyException ex) {
+ // expected
+ }
+
+ try {
+ selectionKey.readyOps();
+ fail("should throw CancelledKeyException.");
+ } catch (CancelledKeyException ex) {
+ // expected
+ }
+
+ try {
+ selectionKey.interestOps(SelectionKey.OP_CONNECT);
+ fail("should throw CancelledKeyException.");
+ } catch (CancelledKeyException ex) {
+ // expected
+ }
+
+ try {
+ selectionKey.interestOps();
+ fail("should throw CancelledKeyException.");
+ } catch (CancelledKeyException ex) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.SelectionKey#readyOps()
+ */
+ public void test_readyOps() throws IOException {
+ int port = Support_PortManager.getNextPort();
+ ServerSocket ss = new ServerSocket(port);
+ try {
+ sc.connect(new InetSocketAddress(LOCAL_ADDR, port));
+ assertEquals(0, selectionKey.readyOps());
+ assertFalse(selectionKey.isConnectable());
+ selector.select();
+ assertEquals(SelectionKey.OP_CONNECT, selectionKey.readyOps());
+ } finally {
+ ss.close();
+ ss = null;
+ }
+
+ }
+
+ /**
+ * @tests java.nio.channels.SelectionKey#selector()
+ */
+ public void test_selector() {
+ assertSame(selector, selectionKey.selector());
+ selectionKey.cancel();
+ assertSame(selector, selectionKey.selector());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectorTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectorTest.java
new file mode 100644
index 0000000..fd29ac8
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SelectorTest.java
@@ -0,0 +1,689 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.nio.ByteBuffer;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.ClosedSelectorException;
+import java.nio.channels.Pipe;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.nio.channels.spi.SelectorProvider;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+import junit.framework.TestCase;
+import tests.support.Support_PortManager;
+
+/*
+ * Tests for Selector and its default implementation
+ */
+public class SelectorTest extends TestCase {
+
+ private static final int WAIT_TIME = 100;
+
+ private static final int PORT = Support_PortManager.getNextPort();
+
+ private static final InetSocketAddress LOCAL_ADDRESS = new InetSocketAddress(
+ "127.0.0.1", PORT);
+
+ Selector selector;
+
+ ServerSocketChannel ssc;
+
+ enum SelectType {
+ NULL, TIMEOUT, NOW
+ };
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ ssc = ServerSocketChannel.open();
+ ssc.configureBlocking(false);
+ ServerSocket ss = ssc.socket();
+ InetSocketAddress address = new InetSocketAddress(PORT);
+ ss.bind(address);
+ selector = Selector.open();
+ }
+
+ protected void tearDown() throws Exception {
+ try {
+ ssc.close();
+ } catch (Exception e) {
+ // do nothing
+ }
+ try {
+ selector.close();
+ } catch (Exception e) {
+ // do nothing
+ }
+ super.tearDown();
+ }
+
+ /**
+ * @tests java.nio.channels.Selector#open()
+ */
+ public void test_open() throws IOException {
+ assertNotNull(selector);
+ }
+
+ /**
+ * @tests Selector#isOpen()
+ */
+ public void test_isOpen() throws IOException {
+ assertTrue(selector.isOpen());
+ selector.close();
+ assertFalse(selector.isOpen());
+ }
+
+ /**
+ * @tests java.nio.channels.Selector#provider()
+ */
+ public void test_provider() throws IOException {
+ // should be system default provider
+ assertNotNull(selector.provider());
+ assertSame(SelectorProvider.provider(), selector.provider());
+ }
+
+ /**
+ * @tests java.nio.channels.Selector#keys()
+ */
+ public void test_keys() throws IOException {
+ SelectionKey key = ssc.register(selector, SelectionKey.OP_ACCEPT);
+
+ Set<SelectionKey> keySet = selector.keys();
+ Set<SelectionKey> keySet2 = selector.keys();
+
+ assertSame(keySet, keySet2);
+ assertEquals(1,keySet.size());
+ SelectionKey key2 = keySet.iterator().next();
+ assertEquals(key,key2);
+
+ // Any attempt to modify keys will cause UnsupportedOperationException
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ SelectionKey key3 = sc.register(selector, SelectionKey.OP_READ);
+ try {
+ keySet2.add(key3);
+ fail("should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ try {
+ keySet2.remove(key3);
+ fail("should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+ try {
+ keySet2.clear();
+ fail("should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+
+ selector.close();
+ try {
+ selector.keys();
+ fail("should throw ClosedSelectorException");
+ } catch (ClosedSelectorException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.Selector#keys()
+ */
+ public void test_selectedKeys() throws IOException {
+ SocketChannel sc = SocketChannel.open();
+ ssc.register(selector, SelectionKey.OP_ACCEPT);
+ try {
+ int count = 0;
+ sc.connect(LOCAL_ADDRESS);
+ count = blockingSelect(SelectType.NULL, 0);
+ assertEquals(1, count);
+ Set<SelectionKey> selectedKeys = selector.selectedKeys();
+ Set<SelectionKey> selectedKeys2 = selector.selectedKeys();
+ assertSame(selectedKeys, selectedKeys2);
+
+ assertEquals(1, selectedKeys.size());
+ assertEquals(ssc.keyFor(selector), selectedKeys.iterator().next());
+ // add one key into selectedKeys
+ try {
+ selectedKeys.add(ssc.keyFor(selector));
+ fail("Should throw UnsupportedOperationException");
+ } catch (UnsupportedOperationException e) {
+ // expected
+ }
+
+ // no exception should be thrown
+ selectedKeys.clear();
+
+ Set<SelectionKey> selectedKeys3 = selector.selectedKeys();
+ assertSame(selectedKeys, selectedKeys3);
+
+ ssc.keyFor(selector).cancel();
+ assertEquals(0, selectedKeys.size());
+ selector.close();
+ try {
+ selector.selectedKeys();
+ fail("should throw ClosedSelectorException");
+ } catch (ClosedSelectorException e) {
+ // expected
+ }
+ } finally {
+ sc.close();
+ }
+ }
+
+ /**
+ * @tests java.nio.channel.Selector#selectNow()
+ */
+ public void test_selectNow() throws IOException {
+ assert_select_OP_ACCEPT(SelectType.NOW, 0);
+ assert_select_OP_CONNECT(SelectType.NOW, 0);
+ assert_select_OP_READ(SelectType.NOW, 0);
+ assert_select_OP_WRITE(SelectType.NOW, 0);
+ }
+
+ /**
+ * @tests java.nio.channel.Selector#selectNow()
+ */
+ public void test_selectNow_SelectorClosed() throws IOException {
+ assert_select_SelectorClosed(SelectType.NOW, 0);
+ }
+
+ /**
+ * @test java.nio.channels.Selector#selectNow()
+ */
+ public void test_selectNow_Timeout() throws IOException {
+ // make sure selectNow doesn't block
+ selector.selectNow();
+ }
+
+ /**
+ * @tests java.nio.channel.Selector#select()
+ */
+ public void test_select() throws IOException {
+ assert_select_OP_ACCEPT(SelectType.NULL, 0);
+ assert_select_OP_CONNECT(SelectType.NULL, 0);
+ assert_select_OP_READ(SelectType.NULL, 0);
+ assert_select_OP_WRITE(SelectType.NULL, 0);
+ }
+
+ /**
+ * @tests java.nio.channel.Selector#select()
+ */
+ public void test_select_SelectorClosed() throws IOException {
+ assert_select_SelectorClosed(SelectType.NULL, 0);
+ }
+
+ /**
+ * @tests java.nio.channel.Selector#select(long)
+ */
+ public void test_selectJ() throws IOException {
+ assert_select_OP_ACCEPT(SelectType.TIMEOUT, 0);
+ assert_select_OP_CONNECT(SelectType.TIMEOUT, 0);
+ assert_select_OP_READ(SelectType.TIMEOUT, 0);
+ assert_select_OP_WRITE(SelectType.TIMEOUT, 0);
+
+ assert_select_OP_ACCEPT(SelectType.TIMEOUT, WAIT_TIME);
+ assert_select_OP_CONNECT(SelectType.TIMEOUT, WAIT_TIME);
+ assert_select_OP_READ(SelectType.TIMEOUT, WAIT_TIME);
+ assert_select_OP_WRITE(SelectType.TIMEOUT, WAIT_TIME);
+ }
+
+ /**
+ * @tests java.nio.channel.Selector#select(long)
+ */
+ public void test_selectJ_SelectorClosed() throws IOException {
+ assert_select_SelectorClosed(SelectType.TIMEOUT, 0);
+ selector = Selector.open();
+ assert_select_SelectorClosed(SelectType.TIMEOUT, WAIT_TIME);
+ }
+
+ /**
+ * @tests java.nio.channel.Selector#select(long)
+ */
+ public void test_selectJ_Exception() throws IOException {
+ try {
+ selector.select(-1);
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @test java.nio.channels.Selector#select(long)
+ */
+ public void test_selectJ_Timeout() throws IOException {
+ // make sure select(timeout) doesn't block
+ selector.select(WAIT_TIME);
+ }
+
+ /**
+ * @test java.nio.channels.Selector#select(long)
+ */
+ public void test_selectJ_Empty_Keys() throws IOException {
+ // regression test, see HARMONY-3888.
+ // make sure select(long) does wait for specified amount of
+ // time if keys.size() == 0 (initial state of selector).
+
+ final long SELECT_TIMEOUT = 2000;
+
+ long time1 = System.currentTimeMillis();
+ selector.select(SELECT_TIMEOUT);
+ long time2 = System.currentTimeMillis();
+ assertEquals("elapsed time", SELECT_TIMEOUT, (time2 - time1),
+ SELECT_TIMEOUT * 0.05); // 5% accuracy
+ }
+
+ /**
+ * @tests java.nio.channels.Selector#wakeup()
+ */
+ public void test_wakeup() throws IOException {
+ /*
+ * make sure the test does not block on select
+ */
+ selector.wakeup();
+ selectOnce(SelectType.NULL, 0);
+ selector.wakeup();
+ selectOnce(SelectType.TIMEOUT, 0);
+
+ // try to wakeup select. The invocation sequence of wakeup and select
+ // doesn't affect test result.
+ new Thread() {
+ public void run() {
+
+ try {
+ Thread.sleep(WAIT_TIME);
+ } catch (InterruptedException e) {
+ // ignore
+ }
+ selector.wakeup();
+ }
+ }.start();
+ selectOnce(SelectType.NULL, 0);
+
+ // try to wakeup select. The invocation sequence of wakeup and select
+ // doesn't affect test result.
+ new Thread() {
+ public void run() {
+
+ try {
+ Thread.sleep(WAIT_TIME);
+ } catch (InterruptedException e) {
+ // ignore
+ }
+ selector.wakeup();
+ }
+ }.start();
+ selectOnce(SelectType.TIMEOUT, 0);
+ }
+
+ public void test_keySetViewsModifications() throws IOException {
+ Set<SelectionKey> keys = selector.keys();
+
+ SelectionKey key1 = ssc.register(selector, SelectionKey.OP_ACCEPT);
+
+ assertTrue(keys.contains(key1));
+
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ SelectionKey key2 = sc.register(selector, SelectionKey.OP_READ);
+
+ assertTrue(keys.contains(key1));
+ assertTrue(keys.contains(key2));
+
+ key1.cancel();
+ assertTrue(keys.contains(key1));
+
+ selector.selectNow();
+ assertFalse(keys.contains(key1));
+ assertTrue(keys.contains(key2));
+ }
+
+ /**
+ * This test cancels a key while selecting to verify that the cancelled
+ * key set is processed both before and after the call to the underlying
+ * operating system.
+ */
+ public void test_cancelledKeys() throws Exception {
+ final AtomicReference<Throwable> failure = new AtomicReference<Throwable>();
+ final AtomicBoolean complete = new AtomicBoolean();
+
+ final Pipe pipe = Pipe.open();
+ pipe.source().configureBlocking(false);
+ final SelectionKey key = pipe.source().register(selector, SelectionKey.OP_READ);
+
+ Thread thread = new Thread() {
+ public void run() {
+ try {
+ // make sure to call key.cancel() while the main thread is selecting
+ Thread.sleep(500);
+ key.cancel();
+ assertFalse(key.isValid());
+ pipe.sink().write(ByteBuffer.allocate(4)); // unblock select()
+ } catch (Throwable e) {
+ failure.set(e);
+ } finally {
+ complete.set(true);
+ }
+ }
+ };
+ assertTrue(key.isValid());
+
+ thread.start();
+ do {
+ assertEquals(0, selector.select(5000)); // blocks
+ assertEquals(0, selector.selectedKeys().size());
+ } while (!complete.get()); // avoid spurious interrupts
+ assertFalse(key.isValid());
+
+ thread.join();
+ assertNull(failure.get());
+ }
+
+ public void testOpChange() throws Exception {
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ sc.register(selector, SelectionKey.OP_CONNECT);
+ try {
+ sc.connect(LOCAL_ADDRESS);
+ int count = blockingSelect(SelectType.TIMEOUT, 100);
+ assertEquals(1, count);
+ Set<SelectionKey> selectedKeys = selector.selectedKeys();
+ assertEquals(1, selectedKeys.size());
+ SelectionKey key = selectedKeys.iterator().next();
+ assertEquals(sc.keyFor(selector), key);
+ assertEquals(SelectionKey.OP_CONNECT, key.readyOps());
+ // select again, it should return 0
+ count = selectOnce(SelectType.TIMEOUT, 100);
+ assertEquals(0, count);
+ // but selectedKeys remains the same as previous
+ assertSame(selectedKeys, selector.selectedKeys());
+ sc.finishConnect();
+
+ // same selector, but op is changed
+ SelectionKey key1 = sc.register(selector, SelectionKey.OP_WRITE);
+ assertEquals(key, key1);
+ count = blockingSelect(SelectType.TIMEOUT, 100);
+ assertEquals(1, count);
+ selectedKeys = selector.selectedKeys();
+ assertEquals(1, selectedKeys.size());
+ key = selectedKeys.iterator().next();
+ assertEquals(key, key1);
+ assertEquals(SelectionKey.OP_WRITE, key.readyOps());
+
+ selectedKeys.clear();
+ } finally {
+ try {
+ ssc.accept().close();
+ } catch (Exception e) {
+ // do nothing
+ }
+ try {
+ sc.close();
+ } catch (IOException e) {
+ // do nothing
+ }
+ }
+ }
+
+ public void test_nonBlockingConnect() throws IOException {
+ SocketChannel channel = null;
+ try {
+ channel = SocketChannel.open();
+ channel.configureBlocking(false);
+ Selector selector = Selector.open();
+ channel.register(selector, SelectionKey.OP_CONNECT);
+ channel.connect(LOCAL_ADDRESS);
+ channel.finishConnect();
+ selector.select();
+ assertEquals(1, selector.selectedKeys().size());
+ } finally {
+ channel.close();
+ }
+ }
+
+ private void assert_select_SelectorClosed(SelectType type, int timeout)
+ throws IOException {
+ // selector is closed
+ selector.close();
+ try {
+ selectOnce(type, timeout);
+ fail("should throw ClosedSelectorException");
+ } catch (ClosedSelectorException e) {
+ // expected
+ }
+ }
+
+ private void assert_select_OP_ACCEPT(SelectType type, int timeout)
+ throws IOException, ClosedChannelException {
+ SocketChannel sc = SocketChannel.open();
+ SocketChannel client = null;
+ try {
+ ssc.register(selector, SelectionKey.OP_ACCEPT);
+ sc.connect(LOCAL_ADDRESS);
+ int count = blockingSelect(type, timeout);
+ assertEquals(1, count);
+ Set<SelectionKey> selectedKeys = selector.selectedKeys();
+ assertEquals(1, selectedKeys.size());
+ SelectionKey key = selectedKeys.iterator().next();
+ assertEquals(ssc.keyFor(selector), key);
+ assertEquals(SelectionKey.OP_ACCEPT, key.readyOps());
+ // select again, it should return 0
+ count = selectOnce(type, timeout);
+ assertEquals(0,count);
+ // but selectedKeys remains the same as previous
+ assertSame(selectedKeys, selector.selectedKeys());
+ client = ssc.accept();
+ selectedKeys.clear();
+ } finally {
+ try {
+ sc.close();
+ } catch (IOException e) {
+ // do nothing
+ }
+ if (null != client) {
+ client.close();
+ }
+ }
+ ssc.keyFor(selector).cancel();
+ }
+
+ private void assert_select_OP_CONNECT(SelectType type, int timeout)
+ throws IOException, ClosedChannelException {
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ sc.register(selector, SelectionKey.OP_CONNECT);
+ try {
+ sc.connect(LOCAL_ADDRESS);
+ int count = blockingSelect(type, timeout);
+ assertEquals(1, count);
+ Set<SelectionKey> selectedKeys = selector.selectedKeys();
+ assertEquals(1, selectedKeys.size());
+ SelectionKey key = selectedKeys.iterator().next();
+ assertEquals(sc.keyFor(selector), key);
+ assertEquals(SelectionKey.OP_CONNECT, key.readyOps());
+ // select again, it should return 0
+ count = selectOnce(type, timeout);
+ assertEquals(0, count);
+ // but selectedKeys remains the same as previous
+ assertSame(selectedKeys, selector.selectedKeys());
+ sc.finishConnect();
+ selectedKeys.clear();
+ } finally {
+ try {
+ ssc.accept().close();
+ } catch (Exception e) {
+ // do nothing
+ }
+
+ try {
+ sc.close();
+ } catch (IOException e) {
+ // do nothing
+ }
+ }
+ }
+
+ private void assert_select_OP_READ(SelectType type, int timeout)
+ throws IOException {
+ SocketChannel sc = SocketChannel.open();
+ SocketChannel client = null;
+ SocketChannel sc2 = SocketChannel.open();
+ SocketChannel client2 = null;
+ try {
+ ssc.configureBlocking(true);
+ sc.connect(LOCAL_ADDRESS);
+ client = ssc.accept();
+ sc.configureBlocking(false);
+ sc.register(selector, SelectionKey.OP_READ);
+ client.configureBlocking(true);
+
+ sc2.connect(LOCAL_ADDRESS);
+ client2 = ssc.accept();
+ sc2.configureBlocking(false);
+ sc2.register(selector, SelectionKey.OP_READ);
+ client2.configureBlocking(true);
+
+ client.write(ByteBuffer.wrap("a".getBytes()));
+ int count = blockingSelect(type, timeout);
+ assertEquals(1, count);
+ Set<SelectionKey> selectedKeys = selector.selectedKeys();
+ assertEquals(1, selectedKeys.size());
+ SelectionKey key = selectedKeys.iterator().next();
+ assertEquals(sc.keyFor(selector), key);
+ assertEquals(SelectionKey.OP_READ, key.readyOps());
+ // select again, it should return 0
+ count = selectOnce(type, timeout);
+ assertEquals(0, count);
+ // but selectedKeys remains the same as previous
+ assertSame(selectedKeys, selector.selectedKeys());
+
+ sc.read(ByteBuffer.allocate(8));
+
+ // the second SocketChannel should be selected this time
+ client2.write(ByteBuffer.wrap("a".getBytes()));
+ count = blockingSelect(type, timeout);
+ assertEquals(1, count);
+ // selectedKeys still includes the key of sc, because the key of sc
+ // is not removed last time.
+ selectedKeys = selector.selectedKeys();
+ assertEquals(2, selectedKeys.size());
+ } finally {
+ if (null != client) {
+ try {
+ client.close();
+ } catch (Exception e) {
+ // ignore
+ }
+ }
+ if (null != client2) {
+ try {
+ client2.close();
+ } catch (Exception e) {
+ // ignore
+ }
+ }
+ try {
+ sc.close();
+ } catch (Exception e) {
+ // ignore
+ }
+ try {
+ sc2.close();
+ } catch (Exception e) {
+ // ignore
+ }
+ ssc.configureBlocking(false);
+ }
+ }
+
+ private void assert_select_OP_WRITE(SelectType type, int timeout)
+ throws IOException {
+ SocketChannel sc = SocketChannel.open();
+ SocketChannel client = null;
+ try {
+ sc.connect(LOCAL_ADDRESS);
+ ssc.configureBlocking(true);
+ client = ssc.accept();
+ sc.configureBlocking(false);
+ sc.register(selector, SelectionKey.OP_WRITE);
+ int count = blockingSelect(type, timeout);
+ assertEquals(1, count);
+ Set<SelectionKey> selectedKeys = selector.selectedKeys();
+ assertEquals(1, selectedKeys.size());
+ SelectionKey key = selectedKeys.iterator().next();
+ assertEquals(sc.keyFor(selector), key);
+ assertEquals(SelectionKey.OP_WRITE, key.readyOps());
+ // select again, it should return 0
+ count = selectOnce(type, timeout);
+ assertEquals(0, count);
+ // but selectedKeys remains the same as previous
+ assertSame(selectedKeys, selector.selectedKeys());
+ } finally {
+ if (null != client) {
+ client.close();
+ }
+ try {
+ sc.close();
+ } catch (IOException e) {
+ // do nothing
+ }
+ ssc.configureBlocking(false);
+ }
+ }
+
+ private int blockingSelect(SelectType type, int timeout) throws IOException {
+ int ret = 0;
+ do {
+ ret = selectOnce(type, timeout);
+ if (ret > 0) {
+ return ret;
+ }
+ try {
+ Thread.sleep(100);
+ } catch (InterruptedException e) {
+ // ignore
+ }
+ } while (true);
+ }
+
+ private int selectOnce(SelectType type, int timeout) throws IOException {
+ int ret = 0;
+ switch (type) {
+ case NULL:
+ ret = selector.select();
+ break;
+ case TIMEOUT:
+ ret = selector.select(timeout);
+ break;
+ case NOW:
+ ret = selector.selectNow();
+ break;
+ }
+ return ret;
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ServerSocketChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ServerSocketChannelTest.java
new file mode 100644
index 0000000..fdbbc48
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/ServerSocketChannelTest.java
@@ -0,0 +1,682 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.nio.ByteBuffer;
+import java.nio.channels.AsynchronousCloseException;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.IllegalBlockingModeException;
+import java.nio.channels.NotYetBoundException;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.nio.channels.spi.SelectorProvider;
+
+import junit.framework.TestCase;
+import tests.support.Support_PortManager;
+
+/*
+ * test for ServerSocketChannel
+ */
+public class ServerSocketChannelTest extends TestCase {
+
+ private static final int CAPACITY_NORMAL = 200;
+
+ private static final int CAPACITY_64KB = 65536;
+
+ private static final int TIME_UNIT = 200;
+
+ private InetSocketAddress localAddr1;
+
+ private ServerSocketChannel serverChannel;
+
+ private SocketChannel clientChannel;
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ this.localAddr1 = new InetSocketAddress(
+ "127.0.0.1", Support_PortManager
+ .getNextPort());
+ this.serverChannel = ServerSocketChannel.open();
+ this.clientChannel = SocketChannel.open();
+ }
+
+ protected void tearDown() throws Exception {
+ if (null != this.serverChannel) {
+ try {
+ this.serverChannel.close();
+ } catch (Exception e) {
+ //ignore
+ }
+
+ }
+ if (null != this.clientChannel) {
+ try {
+ this.clientChannel.close();
+ } catch (Exception e) {
+ //ignore
+ }
+ }
+ super.tearDown();
+ }
+
+ // -------------------------------------------------------------------
+ // Test for methods in abstract class.
+ // -------------------------------------------------------------------
+
+ /*
+ * Test method for 'java.nio.channels.ServerSocketChannel.validOps()'
+ */
+ public void testValidOps() {
+ MockServerSocketChannel testMSChnlnull = new MockServerSocketChannel(
+ null);
+ MockServerSocketChannel testMSChnl = new MockServerSocketChannel(
+ SelectorProvider.provider());
+ assertEquals(SelectionKey.OP_ACCEPT, this.serverChannel.validOps());
+ assertEquals(SelectionKey.OP_ACCEPT, testMSChnl.validOps());
+ assertEquals(SelectionKey.OP_ACCEPT, testMSChnlnull.validOps());
+
+ }
+
+ /*
+ * Test method for 'java.nio.channels.ServerSocketChannel.open()'
+ */
+ public void testOpen() {
+ MockServerSocketChannel testMSChnl = new MockServerSocketChannel(null);
+ MockServerSocketChannel testMSChnlnotnull = new MockServerSocketChannel(
+ SelectorProvider.provider());
+ assertEquals(SelectionKey.OP_ACCEPT, testMSChnlnotnull.validOps());
+ assertNull(testMSChnl.provider());
+ assertNotNull(testMSChnlnotnull.provider());
+ assertNotNull(this.serverChannel.provider());
+ assertEquals(testMSChnlnotnull.provider(), this.serverChannel
+ .provider());
+ }
+
+ // -------------------------------------------------------------------
+ // Test for socket()
+ // -------------------------------------------------------------------
+
+ /*
+ * Test method for 'java.nio.channels.ServerSocketChannel.socket()'
+ */
+ public void testSocket_Block_BeforeClose() throws Exception {
+ assertTrue(this.serverChannel.isOpen());
+ assertTrue(this.serverChannel.isBlocking());
+ ServerSocket s1 = this.serverChannel.socket();
+ assertFalse(s1.isClosed());
+ assertSocketNotAccepted(s1);
+ ServerSocket s2 = this.serverChannel.socket();
+ // same
+ assertSame(s1, s2);
+
+ // socket close makes the channel close
+ s1.close();
+ assertFalse(this.serverChannel.isOpen());
+
+ }
+
+ public void testSocket_NonBlock_BeforeClose() throws Exception {
+ assertTrue(this.serverChannel.isOpen());
+ this.serverChannel.configureBlocking(false);
+ ServerSocket s1 = this.serverChannel.socket();
+ assertFalse(s1.isClosed());
+ assertSocketNotAccepted(s1);
+ ServerSocket s2 = this.serverChannel.socket();
+ // same
+ assertSame(s1, s2);
+
+ // socket close makes the channel close
+ s1.close();
+ assertFalse(this.serverChannel.isOpen());
+
+ }
+
+ public void testSocket_Block_Closed() throws Exception {
+ this.serverChannel.close();
+ assertFalse(this.serverChannel.isOpen());
+ assertTrue(this.serverChannel.isBlocking());
+ ServerSocket s1 = this.serverChannel.socket();
+ assertTrue(s1.isClosed());
+ assertSocketNotAccepted(s1);
+ ServerSocket s2 = this.serverChannel.socket();
+ // same
+ assertSame(s1, s2);
+ }
+
+ public void testSocket_NonBlock_Closed() throws Exception {
+ this.serverChannel.configureBlocking(false);
+ this.serverChannel.close();
+ assertFalse(this.serverChannel.isBlocking());
+ assertFalse(this.serverChannel.isOpen());
+ ServerSocket s1 = this.serverChannel.socket();
+ assertTrue(s1.isClosed());
+ assertSocketNotAccepted(s1);
+ ServerSocket s2 = this.serverChannel.socket();
+ // same
+ assertSame(s1, s2);
+ }
+
+ private void assertSocketNotAccepted(ServerSocket s) throws IOException {
+ assertFalse(s.isBound());
+ assertNull(s.getInetAddress());
+ assertEquals(-1, s.getLocalPort());
+ assertNull(s.getLocalSocketAddress());
+ try {
+ assertEquals(0, s.getSoTimeout());
+ } catch (IOException expected) {
+ // Android doesn't cache the timeout, so the getsockopt(2) fails and throws.
+ }
+ }
+
+ public void testChannelBasicStatus() {
+ ServerSocket gotSocket = this.serverChannel.socket();
+ assertFalse(gotSocket.isClosed());
+ assertTrue(this.serverChannel.isBlocking());
+ assertFalse(this.serverChannel.isRegistered());
+ assertEquals(SelectionKey.OP_ACCEPT, this.serverChannel.validOps());
+ assertEquals(SelectorProvider.provider(), this.serverChannel.provider());
+ }
+
+ // -------------------------------------------------------------------
+ // Test for accept()
+ // -------------------------------------------------------------------
+
+ /*
+ * Test method for 'java.nio.channels.ServerSocketChannel.accept()'
+ */
+
+ public void testAccept_Block_NotYetBound() throws IOException {
+ assertTrue(this.serverChannel.isOpen());
+ assertTrue(this.serverChannel.isBlocking());
+ try {
+ this.serverChannel.accept();
+ fail("Should throw NotYetBoundException");
+ } catch (NotYetBoundException e) {
+ // correct
+ }
+ }
+
+ public void testAccept_NonBlock_NotYetBound() throws IOException {
+ assertTrue(this.serverChannel.isOpen());
+ this.serverChannel.configureBlocking(false);
+ try {
+ this.serverChannel.accept();
+ fail("Should throw NotYetBoundException");
+ } catch (NotYetBoundException e) {
+ // correct
+ }
+ }
+
+ public void testAccept_ClosedChannel() throws Exception {
+ this.serverChannel.close();
+ assertFalse(this.serverChannel.isOpen());
+ try {
+ this.serverChannel.accept();
+ fail("Should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // OK.
+ }
+ }
+
+ public void testAccept_Block_NoConnect() throws IOException {
+ assertTrue(this.serverChannel.isBlocking());
+ ServerSocket gotSocket = this.serverChannel.socket();
+ gotSocket.bind(localAddr1);
+ // blocking mode , will block and wait for ever...
+ // so must close the server channel with another thread.
+ new Thread() {
+ public void run() {
+ try {
+ Thread.sleep(TIME_UNIT);
+ ServerSocketChannelTest.this.serverChannel.close();
+ } catch (Exception e) {
+ fail("Fail to close the server channel because of"
+ + e.getClass().getName());
+ }
+ }
+ }.start();
+ try {
+ this.serverChannel.accept();
+ fail("Should throw a AsynchronousCloseException");
+ } catch (AsynchronousCloseException e) {
+ // OK.
+ }
+ }
+
+ public void testAccept_NonBlock_NoConnect() throws IOException {
+ ServerSocket gotSocket = this.serverChannel.socket();
+ gotSocket.bind(localAddr1);
+ this.serverChannel.configureBlocking(false);
+ // non-blocking mode , will immediately return
+ assertNull(this.serverChannel.accept());
+ }
+
+ /**
+ * @tests ServerSocketChannel#accept().socket()
+ */
+ public void test_read_Blocking_RealData() throws IOException {
+ serverChannel.socket().bind(localAddr1);
+ ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
+
+ for (int i = 0; i < CAPACITY_NORMAL; i++) {
+ buf.put((byte) i);
+ }
+ clientChannel.connect(localAddr1);
+ Socket serverSocket = serverChannel.accept().socket();
+ InputStream in = serverSocket.getInputStream();
+ buf.flip();
+ clientChannel.write(buf);
+ clientChannel.close();
+ assertReadResult(in,CAPACITY_NORMAL);
+ }
+
+ /**
+ * Asserts read content. The read content should contain <code>size</code>
+ * bytes, and the value should be a sequence from 0 to size-1
+ * ([0,1,...size-1]). Otherwise, the method throws Exception.
+ *
+ */
+ private void assertReadResult(InputStream in, int size) throws IOException{
+ byte[] readContent = new byte[size + 1];
+ int count = 0;
+ int total = 0;
+ while ((count = in.read(readContent, total, size + 1 - total)) != -1) {
+ total = total + count;
+ }
+ assertEquals(size, total);
+ for (int i = 0; i < size; i++) {
+ assertEquals((byte) i, readContent[i]);
+ }
+ }
+
+ /**
+ * @tests ServerSocketChannel#accept().socket()
+ */
+ public void test_read_NonBlocking_RealData() throws Exception {
+ serverChannel.configureBlocking(false);
+ serverChannel.socket().bind(localAddr1);
+ ByteBuffer buf = ByteBuffer.allocate(CAPACITY_NORMAL);
+ for (int i = 0; i < CAPACITY_NORMAL; i++) {
+ buf.put((byte) i);
+ }
+ buf.flip();
+ clientChannel.connect(localAddr1);
+ Socket serverSocket = serverChannel.accept().socket();
+ InputStream in = serverSocket.getInputStream();
+ clientChannel.write(buf);
+ clientChannel.close();
+ assertReadResult(in,CAPACITY_NORMAL);
+ }
+
+ /**
+ * @tests ServerSocketChannel#accept().socket()
+ */
+ public void test_write_Blocking_RealData() throws IOException {
+ assertTrue(serverChannel.isBlocking());
+ ServerSocket serverSocket = serverChannel.socket();
+ serverSocket.bind(localAddr1);
+
+ byte[] writeContent = new byte[CAPACITY_NORMAL];
+ for (int i = 0; i < writeContent.length; i++) {
+ writeContent[i] = (byte) i;
+ }
+ clientChannel.connect(localAddr1);
+ Socket socket = serverChannel.accept().socket();
+ OutputStream out = socket.getOutputStream();
+ out.write(writeContent);
+ out.flush();
+ socket.close();
+ assertWriteResult(CAPACITY_NORMAL);
+ }
+
+
+ /**
+ * @tests ServerSocketChannel#accept().socket()
+ */
+ public void test_write_NonBlocking_RealData() throws Exception {
+ serverChannel.configureBlocking(false);
+ ServerSocket serverSocket = serverChannel.socket();
+ serverSocket.bind(localAddr1);
+
+ byte[] writeContent = new byte[CAPACITY_NORMAL];
+ for (int i = 0; i < CAPACITY_NORMAL; i++) {
+ writeContent[i] = (byte) i;
+ }
+ clientChannel.connect(localAddr1);
+ Socket clientSocket = serverChannel.accept().socket();
+ OutputStream out = clientSocket.getOutputStream();
+ out.write(writeContent);
+ clientSocket.close();
+ assertWriteResult(CAPACITY_NORMAL);
+ }
+
+ /**
+ * @throws InterruptedException
+ * @tests ServerSocketChannel#accept().socket()
+ */
+ public void test_read_LByteBuffer_Blocking_ReadWriteRealLargeData()
+ throws IOException, InterruptedException {
+ serverChannel.socket().bind(localAddr1);
+ ByteBuffer buf = ByteBuffer.allocate(CAPACITY_64KB);
+ for (int i = 0; i < CAPACITY_64KB; i++) {
+ buf.put((byte) i);
+ }
+ buf.flip();
+ clientChannel.connect(localAddr1);
+ WriteChannelThread writeThread = new WriteChannelThread(clientChannel, buf);
+ writeThread.start();
+ Socket socket = serverChannel.accept().socket();
+ InputStream in = socket.getInputStream();
+ assertReadResult(in,CAPACITY_64KB);
+ writeThread.join();
+ // check if the thread threw any exceptions
+ if (writeThread.exception != null) {
+ throw writeThread.exception;
+ }
+ }
+
+ class WriteChannelThread extends Thread {
+ SocketChannel channel;
+ ByteBuffer buffer;
+ IOException exception;
+
+ public WriteChannelThread(SocketChannel channel, ByteBuffer buffer) {
+ this.channel = channel;
+ this.buffer = buffer;
+ }
+
+ public void run() {
+ try {
+ channel.write(buffer);
+ channel.close();
+ } catch (IOException e) {
+ exception = e;
+ }
+ }
+ }
+
+ /**
+ * @tests ServerSocketChannel#accept().socket()
+ */
+ public void test_read_LByteBuffer_NonBlocking_ReadWriteRealLargeData()
+ throws Exception {
+ serverChannel.configureBlocking(false);
+ serverChannel.socket().bind(localAddr1);
+ ByteBuffer buf = ByteBuffer.allocate(CAPACITY_64KB);
+ for (int i = 0; i < CAPACITY_64KB; i++) {
+ buf.put((byte) i);
+ }
+ buf.flip();
+ clientChannel.connect(localAddr1);
+ WriteChannelThread writeThread = new WriteChannelThread(clientChannel, buf);
+ writeThread.start();
+ Socket socket = serverChannel.accept().socket();
+ InputStream in = socket.getInputStream();
+ assertReadResult(in,CAPACITY_64KB);
+ writeThread.join();
+ // check if the thread threw any exceptions
+ if (writeThread.exception != null) {
+ throw writeThread.exception;
+ }
+ }
+
+ /**
+ * @tests ServerSocketChannel#accept().socket()
+ */
+ public void test_write_LByteBuffer_NonBlocking_ReadWriteRealLargeData()
+ throws Exception {
+ serverChannel.configureBlocking(false);
+ serverChannel.socket().bind(localAddr1);
+ byte[] writeContent = new byte[CAPACITY_64KB];
+ for (int i = 0; i < writeContent.length; i++) {
+ writeContent[i] = (byte) i;
+ }
+ clientChannel.connect(localAddr1);
+ Socket socket = serverChannel.accept().socket();
+ WriteSocketThread writeThread = new WriteSocketThread(socket, writeContent);
+ writeThread.start();
+ assertWriteResult(CAPACITY_64KB);
+ writeThread.join();
+ // check if the thread threw any exceptions
+ if (writeThread.exception != null) {
+ throw writeThread.exception;
+ }
+ }
+
+ class WriteSocketThread extends Thread {
+ Socket socket;
+ byte[] buffer;
+ IOException exception;
+
+ public WriteSocketThread(Socket socket, byte[] buffer) {
+ this.socket = socket;
+ this.buffer = buffer;
+ }
+
+ public void run() {
+ try {
+ OutputStream out = socket.getOutputStream();
+ out.write(buffer);
+ socket.close();
+ } catch (IOException e) {
+ exception = e;
+ }
+ }
+ }
+
+ /**
+ * @tests ServerSocketChannel#accept().socket()
+ */
+ public void test_write_LByteBuffer_Blocking_ReadWriteRealLargeData()
+ throws Exception {
+ serverChannel.socket().bind(localAddr1);
+ byte[] writeContent = new byte[CAPACITY_64KB];
+ for (int i = 0; i < writeContent.length; i++) {
+ writeContent[i] = (byte) i;
+ }
+ clientChannel.connect(localAddr1);
+ Socket socket = serverChannel.accept().socket();
+ WriteSocketThread writeThread = new WriteSocketThread(socket, writeContent);
+ writeThread.start();
+ assertWriteResult(CAPACITY_64KB);
+ writeThread.join();
+ // check if the thread threw any exceptions
+ if (writeThread.exception != null) {
+ throw writeThread.exception;
+ }
+ }
+
+ /**
+ * Uses SocketChannel.read(ByteBuffer) to verify write result.
+ */
+ private void assertWriteResult(int size) throws IOException{
+ ByteBuffer buf = ByteBuffer.allocate(size + 1);
+ int count = 0;
+ int total = 0;
+ long beginTime = System.currentTimeMillis();
+ while ((count = clientChannel.read(buf)) != -1) {
+ total = total + count;
+ // 10s timeout to avoid dead loop
+ if (System.currentTimeMillis() - beginTime > 10000){
+ break;
+ }
+ }
+ assertEquals(total, size);
+ buf.flip();
+ for (int i = 0; i < count; i++) {
+ assertEquals((byte) i, buf.get(i));
+ }
+ }
+
+ /**
+ * @tests ServerSocketChannel#socket().getSoTimeout()
+ */
+ public void test_accept_SOTIMEOUT() throws IOException {
+ // regression test for Harmony-707
+ final int SO_TIMEOUT = 10;
+ ServerSocketChannel sc = ServerSocketChannel.open();
+ try {
+ ServerSocket ss = sc.socket();
+ ss.bind(localAddr1);
+ sc.configureBlocking(false);
+ ss.setSoTimeout(SO_TIMEOUT);
+ SocketChannel client = sc.accept();
+ // non blocking mode, returns null since there are no pending connections.
+ assertNull(client);
+ int soTimeout = ss.getSoTimeout();
+ // Harmony fails here.
+ assertEquals(SO_TIMEOUT, soTimeout);
+ } finally {
+ sc.close();
+ }
+ }
+
+ /**
+ * @tests ServerSocket#socket().accept()
+ */
+ public void test_socket_accept_Blocking_NotBound() throws IOException {
+ // regression test for Harmony-748
+ ServerSocket gotSocket = serverChannel.socket();
+ serverChannel.configureBlocking(true);
+ try {
+ gotSocket.accept();
+ fail("Should throw an IllegalBlockingModeException");
+ } catch (IllegalBlockingModeException e) {
+ // expected
+ }
+ serverChannel.close();
+ try {
+ gotSocket.accept();
+ fail("Should throw an IllegalBlockingModeException");
+ } catch (IllegalBlockingModeException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests ServerSocket#socket().accept()
+ */
+ public void test_socket_accept_Nonblocking_NotBound() throws IOException {
+ // regression test for Harmony-748
+ ServerSocket gotSocket = serverChannel.socket();
+ serverChannel.configureBlocking(false);
+ try {
+ gotSocket.accept();
+ fail("Should throw an IllegalBlockingModeException");
+ } catch (IllegalBlockingModeException e) {
+ // expected
+ }
+ serverChannel.close();
+ try {
+ gotSocket.accept();
+ fail("Should throw an IllegalBlockingModeException");
+ } catch (IllegalBlockingModeException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests ServerSocket#socket().accept()
+ */
+ public void test_socket_accept_Nonblocking_Bound() throws IOException {
+ // regression test for Harmony-748
+ serverChannel.configureBlocking(false);
+ ServerSocket gotSocket = serverChannel.socket();
+ gotSocket.bind(localAddr1);
+ try {
+ gotSocket.accept();
+ fail("Should throw an IllegalBlockingModeException");
+ } catch (IllegalBlockingModeException e) {
+ // expected
+ }
+ serverChannel.close();
+ try {
+ gotSocket.accept();
+ fail("Should throw a ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests ServerSocket#socket().accept()
+ */
+ public void test_socket_accept_Blocking_Bound() throws IOException {
+ // regression test for Harmony-748
+ serverChannel.configureBlocking(true);
+ ServerSocket gotSocket = serverChannel.socket();
+ gotSocket.bind(localAddr1);
+ serverChannel.close();
+ try {
+ gotSocket.accept();
+ fail("Should throw a ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ }
+ /**
+ * Regression test for HARMONY-4961
+ */
+ public void test_socket_getLocalPort() throws IOException {
+ serverChannel.socket().bind(localAddr1);
+ clientChannel.connect(localAddr1);
+ SocketChannel myChannel = serverChannel.accept();
+ int port = myChannel.socket().getLocalPort();
+ assertEquals(localAddr1.getPort(), port);
+ myChannel.close();
+ clientChannel.close();
+ serverChannel.close();
+ }
+
+ /**
+ * Regression test for HARMONY-6375
+ */
+ public void test_accept_configureBlocking() throws Exception {
+ InetSocketAddress localAddr = new InetSocketAddress("localhost", 0);
+ serverChannel.socket().bind(localAddr);
+
+ // configure the channel non-blocking
+ // when it is accepting in main thread
+ new Thread() {
+ public void run() {
+ try {
+ Thread.sleep(TIME_UNIT);
+ serverChannel.configureBlocking(false);
+ serverChannel.close();
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ }.start();
+
+ try {
+ serverChannel.accept();
+ fail("should throw AsynchronousCloseException");
+ } catch (AsynchronousCloseException e) {
+ // expected
+ }
+ serverChannel.close();
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SinkChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SinkChannelTest.java
new file mode 100644
index 0000000..9e96fad
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SinkChannelTest.java
@@ -0,0 +1,505 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.Pipe;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for Pipe.SinkChannel class
+ */
+public class SinkChannelTest extends TestCase {
+
+ private static final int BUFFER_SIZE = 5;
+
+ private static final String ISO8859_1 = "ISO8859-1";
+
+ private Pipe pipe;
+
+ private Pipe.SinkChannel sink;
+
+ private Pipe.SourceChannel source;
+
+ private ByteBuffer buffer;
+
+ private ByteBuffer positionedBuffer;
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ pipe = Pipe.open();
+ sink = pipe.sink();
+ source = pipe.source();
+ buffer = ByteBuffer.wrap("bytes".getBytes(ISO8859_1));
+ positionedBuffer = ByteBuffer.wrap("12345bytes".getBytes(ISO8859_1));
+ positionedBuffer.position(BUFFER_SIZE);
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SinkChannel#validOps()
+ */
+ public void test_validOps() {
+ assertEquals(SelectionKey.OP_WRITE, sink.validOps());
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer)
+ */
+ public void test_write_LByteBuffer() throws IOException {
+ ByteBuffer[] bufArray = { buffer, positionedBuffer };
+ boolean[] sinkBlockingMode = { true, true, false, false };
+ boolean[] sourceBlockingMode = { true, false, true, false };
+ int oldPosition;
+ int currentPosition;
+ for (int i = 0; i < sinkBlockingMode.length; ++i) {
+ sink.configureBlocking(sinkBlockingMode[i]);
+ source.configureBlocking(sourceBlockingMode[i]);
+ // if sink and source both are blocking mode, source only needs read
+ // once to get what sink write.
+ boolean isBlocking = sinkBlockingMode[i] && sourceBlockingMode[i];
+ for (ByteBuffer buf : bufArray) {
+ buf.mark();
+ oldPosition = buf.position();
+ sink.write(buf);
+ ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
+ int totalCount = 0;
+ do {
+ int count = source.read(readBuf);
+ if (count > 0) {
+ totalCount += count;
+ }
+ } while (totalCount != BUFFER_SIZE && !isBlocking);
+ currentPosition = buf.position();
+ assertEquals(BUFFER_SIZE, currentPosition - oldPosition);
+ assertEquals("bytes", new String(readBuf.array(), ISO8859_1));
+ buf.reset();
+ }
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer)
+ */
+ public void test_write_LByteBuffer_mutliThread() throws IOException,
+ InterruptedException {
+ final int THREAD_NUM = 20;
+ final byte[] strbytes = "bytes".getBytes(ISO8859_1);
+ Thread[] thread = new Thread[THREAD_NUM];
+ for (int i = 0; i < THREAD_NUM; i++) {
+ thread[i] = new Thread() {
+ public void run() {
+ try {
+ sink.write(ByteBuffer.wrap(strbytes));
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
+ };
+ }
+ for (int i = 0; i < THREAD_NUM; i++) {
+ thread[i].start();
+ }
+ for (int i = 0; i < THREAD_NUM; i++) {
+ thread[i].join();
+ }
+ ByteBuffer readBuf = ByteBuffer.allocate(THREAD_NUM * BUFFER_SIZE);
+
+ long totalCount = 0;
+ do {
+ long count = source.read(readBuf);
+ if (count < 0) {
+ break;
+ }
+ totalCount += count;
+ } while (totalCount != (THREAD_NUM * BUFFER_SIZE));
+
+ StringBuffer buf = new StringBuffer();
+ for (int i = 0; i < THREAD_NUM; i++) {
+ buf.append("bytes");
+ }
+ String readString = buf.toString();
+ assertEquals(readString, new String(readBuf.array(), ISO8859_1));
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer)
+ */
+ public void test_write_LByteBuffer_Exception() throws IOException {
+ // write null ByteBuffer
+ ByteBuffer nullBuf = null;
+ try {
+ sink.write(nullBuf);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ public void test_write_LByteBuffer_SourceClosed() throws IOException {
+ source.close();
+ try {
+ int written = sink.write(buffer);
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+
+ public void test_write_LByteBuffer_SinkClosed() throws IOException {
+ sink.close();
+ try {
+ sink.write(buffer);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException expected) {
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer[])
+ */
+ public void test_write_$LByteBuffer() throws IOException {
+ ByteBuffer[] bufArray = { buffer, positionedBuffer };
+ boolean[] sinkBlockingMode = { true, true, false, false };
+ boolean[] sourceBlockingMode = { true, false, true, false };
+ for (int i = 0; i < sinkBlockingMode.length; ++i) {
+ sink.configureBlocking(sinkBlockingMode[i]);
+ source.configureBlocking(sourceBlockingMode[i]);
+ buffer.position(0);
+ positionedBuffer.position(BUFFER_SIZE);
+ sink.write(bufArray);
+ // if sink and source both are blocking mode, source only needs read
+ // once to get what sink write.
+ boolean isBlocking = sinkBlockingMode[i] && sourceBlockingMode[i];
+ for (int j = 0; j < bufArray.length; ++j) {
+ ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
+ int totalCount = 0;
+ do {
+ int count = source.read(readBuf);
+ if (count < 0) {
+ break;
+ }
+ totalCount += count;
+ } while (totalCount != BUFFER_SIZE && !isBlocking);
+ assertEquals("bytes", new String(readBuf.array(), ISO8859_1));
+ }
+ assertEquals(BUFFER_SIZE, buffer.position());
+ assertEquals(10, positionedBuffer.position());
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer[])
+ */
+ public void test_write_$LByteBuffer_Exception() throws IOException {
+ // write null ByteBuffer[]
+ ByteBuffer[] nullBufArrayRef = null;
+ try {
+ sink.write(nullBufArrayRef);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ // write ByteBuffer[] contains null element
+ ByteBuffer nullBuf = null;
+ ByteBuffer[] nullBufArray = { buffer, nullBuf };
+ try {
+ sink.write(nullBufArray);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ public void test_write_$LByteBuffer_SourceClosed() throws IOException {
+ ByteBuffer[] bufArray = { buffer };
+ source.close();
+ try {
+ long written = sink.write(bufArray);
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer[])
+ */
+ public void test_write_$LByteBuffer_SinkClosed() throws IOException {
+ ByteBuffer[] bufArray = { buffer };
+ sink.close();
+ try {
+ sink.write(bufArray);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ ByteBuffer[] nullBufArrayRef = null;
+ try {
+ sink.write(nullBufArrayRef);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ ByteBuffer nullBuf = null;
+ ByteBuffer[] nullBufArray = { nullBuf };
+ // write ByteBuffer[] contains null element
+ try {
+ sink.write(nullBufArray);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SinkChannel#write(ByteBuffer[], int, int)
+ */
+ public void test_write_$LByteBufferII() throws IOException {
+ ByteBuffer[] bufArray = { buffer, positionedBuffer };
+ boolean[] sinkBlockingMode = { true, true, false, false };
+ boolean[] sourceBlockingMode = { true, false, true, false };
+ for (int i = 0; i < sinkBlockingMode.length; ++i) {
+ sink.configureBlocking(sinkBlockingMode[i]);
+ source.configureBlocking(sourceBlockingMode[i]);
+ positionedBuffer.position(BUFFER_SIZE);
+ sink.write(bufArray, 1, 1);
+ // if sink and source both are blocking mode, source only needs read
+ // once to get what sink write.
+ boolean isBlocking = sinkBlockingMode[i] && sourceBlockingMode[i];
+ ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
+ int totalCount = 0;
+ do {
+ int count = source.read(readBuf);
+ if (count < 0) {
+ break;
+ }
+ totalCount += count;
+ } while (totalCount != BUFFER_SIZE && !isBlocking);
+ assertEquals("bytes", new String(readBuf.array(), ISO8859_1));
+ assertEquals(10, positionedBuffer.position());
+ }
+ }
+
+ public void test_write_$LByteBufferII_Exception() throws IOException {
+ try {
+ sink.write(null, 0, 1);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ try {
+ sink.write(new ByteBuffer[2], 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ // write ByteBuffer[] contains null element
+ ByteBuffer nullBuf = null;
+ ByteBuffer[] nullBufArray = { nullBuf };
+ try {
+ sink.write(nullBufArray, 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ sink.write(nullBufArray, 0, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ ByteBuffer[] bufArray = { buffer, nullBuf };
+ try {
+ sink.write(bufArray, 0, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ sink.write(bufArray, -1, 0);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ sink.write(bufArray, -1, 1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ sink.write(bufArray, 0, 3);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ sink.write(bufArray, 0, 2);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ public void test_write_$LByteBufferII_SourceClosed() throws IOException {
+ ByteBuffer[] bufArray = { buffer };
+ source.close();
+
+ try {
+ long written = sink.write(bufArray, 0, 1);
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+
+ public void test_write_$LByteBufferII_SinkClosed() throws IOException {
+ ByteBuffer[] bufArray = { buffer };
+ sink.close();
+ try {
+ sink.write(bufArray, 0, 1);
+ fail();
+ } catch (ClosedChannelException expected) {
+ }
+
+ try {
+ sink.write(null, 0, 1);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ try {
+ sink.write(new ByteBuffer[2], 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+
+ // write ByteBuffer[] contains null element
+ ByteBuffer nullBuf = null;
+ ByteBuffer[] nullBufArray = { nullBuf };
+ try {
+ sink.write(nullBufArray, 0, 1);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ // illegal array index
+ try {
+ sink.write(nullBufArray, 0, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ ByteBuffer[] bufArray2 = { buffer, nullBuf };
+ // illegal array index
+ try {
+ sink.write(bufArray2, 0, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ sink.write(bufArray2, -1, 0);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ sink.write(bufArray2, -1, 1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ sink.write(bufArray2, 0, 3);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ sink.write(bufArray2, 0, 2);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ }
+
+ public void test_close() throws IOException {
+ sink.close();
+ assertFalse(sink.isOpen());
+ }
+
+ public void test_socketChannel_read_close() throws Exception {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(new InetSocketAddress(InetAddress.getLocalHost(),49999));
+ SocketChannel sc = SocketChannel.open();
+ ByteBuffer buf = null;
+ try{
+ sc.write(buf);
+ fail("should throw NPE");
+ }catch (NullPointerException e){
+ // expected
+ }
+ sc.connect(new InetSocketAddress(InetAddress.getLocalHost(),49999));
+ SocketChannel sock = ssc.accept();
+ ssc.close();
+ sc.close();
+ try{
+ sc.write(buf);
+ fail("should throw NPE");
+ }catch (NullPointerException e){
+ // expected
+ }
+ sock.close();
+ }
+
+ public void test_socketChannel_read_write() throws Exception {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(new InetSocketAddress(InetAddress.getLocalHost(),49999));
+ SocketChannel sc = SocketChannel.open();
+ sc.connect(new InetSocketAddress(InetAddress.getLocalHost(),49999));
+ SocketChannel sock = ssc.accept();
+ ByteBuffer[] buf = {ByteBuffer.allocate(10),null};
+ try {
+ sc.write(buf,0,2);
+ fail("should throw NPE");
+ } catch (NullPointerException expected) {
+ }
+ ssc.close();
+ sc.close();
+ ByteBuffer target = ByteBuffer.allocate(10);
+ assertEquals(-1, sock.read(target));
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SocketChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SocketChannelTest.java
new file mode 100644
index 0000000..7325ba1
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SocketChannelTest.java
@@ -0,0 +1,3628 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.BindException;
+import java.net.ConnectException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.nio.Buffer;
+import java.nio.ByteBuffer;
+import java.nio.channels.AlreadyConnectedException;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.ConnectionPendingException;
+import java.nio.channels.IllegalBlockingModeException;
+import java.nio.channels.NoConnectionPendingException;
+import java.nio.channels.NotYetConnectedException;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+import java.nio.channels.UnresolvedAddressException;
+import java.nio.channels.UnsupportedAddressTypeException;
+import java.nio.channels.spi.SelectorProvider;
+
+import junit.framework.TestCase;
+import tests.support.Support_PortManager;
+
+/**
+ * Tests for SocketChannel and its default implementation.
+ */
+public class SocketChannelTest extends TestCase {
+
+ private static final int CAPACITY_NORMAL = 200;
+
+ private InetSocketAddress localAddr1;
+
+ private InetSocketAddress localAddr2;
+
+ private SocketChannel channel1;
+
+ private SocketChannel channel2;
+
+ private ServerSocket server1;
+
+ private ServerSocket server2;
+
+ private final static int TIMEOUT = 60000;
+
+ private final static int EOF = -1;
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ this.localAddr1 = new InetSocketAddress("127.0.0.1",
+ Support_PortManager.getNextPort());
+ this.localAddr2 = new InetSocketAddress("127.0.0.1",
+ Support_PortManager.getNextPort());
+ this.channel1 = SocketChannel.open();
+ this.channel2 = SocketChannel.open();
+ this.server1 = new ServerSocket(localAddr1.getPort());
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ if (null != this.channel1) {
+ try {
+ this.channel1.close();
+ } catch (Exception e) {
+ //ignore
+ }
+ }
+ if (null != this.channel2) {
+ try {
+ this.channel2.close();
+ } catch (Exception e) {
+ //ignore
+ }
+ }
+ if (null != this.server1) {
+ try {
+ this.server1.close();
+ } catch (Exception e) {
+ //ignore
+ }
+ }
+ if (null != this.server2) {
+ try {
+ this.server2.close();
+ } catch (Exception e) {
+ //ignore
+ }
+ }
+ }
+
+ // -------------------------------------------------------------------
+ // Test for methods in abstract class.
+ // -------------------------------------------------------------------
+ /*
+ * Test method for 'java.nio.channels.SocketChannel.validOps()'
+ */
+ public void testValidOps() {
+ MockSocketChannel testMSChannel = new MockSocketChannel(null);
+ assertEquals(13, this.channel1.validOps());
+ assertEquals(13, testMSChannel.validOps());
+ }
+
+ /*
+ * Test method for 'java.nio.channels.SocketChannel.open()'
+ */
+ public void testOpen() throws IOException {
+ java.nio.ByteBuffer[] buf = new java.nio.ByteBuffer[1];
+ buf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
+ MockSocketChannel testMSChannel = new MockSocketChannel(null);
+ MockSocketChannel testMSChannelnotnull = new MockSocketChannel(
+ SelectorProvider.provider());
+ assertNull(testMSChannel.provider());
+ assertNotNull(testMSChannelnotnull.provider());
+ assertNotNull(this.channel1);
+ assertEquals(this.channel1.provider(), testMSChannelnotnull.provider());
+ try {
+ this.channel1.write(buf);
+ fail("Should throw NotYetConnectedException");
+ } catch (NotYetConnectedException e) {
+ // correct
+ }
+ }
+
+ /*
+ * Test method for 'java.nio.channels.SocketChannel.open(SocketAddress)'
+ */
+ public void testOpenSocketAddress_Null() throws IOException {
+ SocketChannel channel1IP = null;
+ try {
+ channel1IP = SocketChannel.open(null);
+ fail("Should throw an IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // correct
+ }
+ assertNull(channel1IP);
+ }
+
+ /*
+ * Test method for 'java.nio.channels.SocketChannel.read(ByteBuffer[])'
+ */
+ public void testReadByteBufferArray() throws IOException {
+ java.nio.ByteBuffer[] byteBuf = null;
+ MockSocketChannel testMSChannelnull = new MockSocketChannel(null);
+ MockSocketChannel testMSChannel = new MockSocketChannel(
+ SelectorProvider.provider());
+ ServerSocket testServer = new ServerSocket(Support_PortManager
+ .getNextPort());
+ try {
+ try {
+ this.channel1.read(byteBuf);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ byteBuf = new java.nio.ByteBuffer[CAPACITY_NORMAL];
+ try {
+ this.channel1.read(byteBuf);
+ fail("Should throw NotYetConnectedException");
+ } catch (NotYetConnectedException e) {
+ // correct
+ }
+ long readNum = CAPACITY_NORMAL;
+ readNum = testMSChannel.read(byteBuf);
+ assertEquals(0, readNum);
+ readNum = CAPACITY_NORMAL;
+ readNum = testMSChannelnull.read(byteBuf);
+ assertEquals(0, readNum);
+ } finally {
+ testServer.close();
+ }
+ }
+
+ /*
+ * Test method for 'java.nio.channels.SocketChannel.read(ByteBuffer[])'
+ */
+ public void testReadByteBufferArray_BufNull() throws IOException {
+ java.nio.ByteBuffer[] byteBuf = null;
+ MockSocketChannel testMSChannelnull = new MockSocketChannel(null);
+ MockSocketChannel testMSChannel = new MockSocketChannel(
+ SelectorProvider.provider());
+ try {
+ this.channel1.read(byteBuf);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ try {
+ testMSChannel.read(byteBuf);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ try {
+ testMSChannelnull.read(byteBuf);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ }
+
+ /*
+ * Test method for 'java.nio.channels.SocketChannel.write(ByteBuffer[])'
+ */
+ public void testWriteByteBufferArray() throws IOException {
+ java.nio.ByteBuffer[] byteBuf = null;
+ MockSocketChannel testMSChannelnull = new MockSocketChannel(null);
+ MockSocketChannel testMSChannel = new MockSocketChannel(
+ SelectorProvider.provider());
+ try {
+ this.channel1.write(byteBuf);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ byteBuf = new java.nio.ByteBuffer[CAPACITY_NORMAL];
+ try {
+ this.channel1.write(byteBuf);
+ fail("Should throw NotYetConnectedException");
+ } catch (NotYetConnectedException e) {
+ // correct
+ }
+ testMSChannel.write(byteBuf);
+ testMSChannelnull.write(byteBuf);
+ }
+
+ /*
+ * Test method for 'java.nio.channels.SocketChannel.write(ByteBuffer[])'
+ */
+ public void testWriteByteBufferArray_BufNull() throws IOException {
+ java.nio.ByteBuffer[] byteBuf = null;
+ MockSocketChannel testMSChannelnull = new MockSocketChannel(null);
+ MockSocketChannel testMSChannel = new MockSocketChannel(
+ SelectorProvider.provider());
+ try {
+ this.channel1.write(byteBuf);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ try {
+ testMSChannel.write(byteBuf);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ try {
+ testMSChannelnull.write(byteBuf);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ }
+
+ public void testSocket_BasicStatusBeforeConnect() throws IOException {
+ assertFalse(this.channel1.isConnected());// not connected
+ Socket s1 = this.channel1.socket();
+ assertSocketBeforeConnect(s1);
+ Socket s2 = this.channel1.socket();
+ // same
+ assertSame(s1, s2);
+ }
+
+ public void testSocket_Block_BasicStatusAfterConnect() throws IOException {
+ assertFalse(this.channel1.isConnected());// not connected
+ assertTrue(this.channel1.connect(localAddr1));
+
+ assertTrue(this.channel1.isConnected());
+ Socket s1 = this.channel1.socket();
+
+ assertSocketAfterConnect(s1, localAddr1);
+ Socket s2 = this.channel1.socket();
+ // same
+ assertSame(s1, s2);
+ }
+
+ public void testSocket_NonBlock_BasicStatusAfterConnect() throws Exception {
+ assertFalse(this.channel1.isConnected());// not connected
+ this.channel1.configureBlocking(false);
+ boolean connected = channel1.connect(localAddr1);
+ Socket s1 = null;
+ Socket s2 = null;
+ if (!connected) {
+ assertFalse(this.channel1.isConnected());
+ assertTrue(this.channel1.isConnectionPending());
+ s1 = this.channel1.socket();
+ // status of not connected
+ assertSocketBeforeConnect(s1);
+ s2 = this.channel1.socket();
+ // same
+ assertSame(s1, s2);
+ }
+
+ if (tryFinish()) {
+ assertTrue(this.channel1.isConnected());
+ s1 = this.channel1.socket();
+ assertSocketAfterConnect(s1, localAddr1);
+ s2 = this.channel1.socket();
+ // same
+ assertSame(s1, s2);
+ }
+ }
+
+ public void testSocket_Block_ActionsBeforeConnect() throws IOException {
+ assertFalse(this.channel1.isConnected());// not connected
+ Socket s = this.channel1.socket();
+ assertSocketAction_Block_BeforeConnect(s);
+ }
+
+ public void testSocket_Block_ActionsAfterConnect() throws IOException {
+ assertFalse(this.channel1.isConnected());// not connected
+ assertTrue(this.channel1.connect(localAddr1));
+ assertTrue(this.channel1.isConnected());
+ Socket s = this.channel1.socket();
+ assertSocketAction_Block_AfterConnect(s);
+
+ }
+
+ public void testSocket_NonBlock_ActionsAfterConnectBeforeFinish()
+ throws IOException {
+ assertFalse(this.channel1.isConnected());// not connected
+ this.channel1.configureBlocking(false);
+ boolean connected = channel1.connect(localAddr1);
+ if (!connected) {
+ assertFalse(this.channel1.isConnected());
+ assertTrue(this.channel1.isConnectionPending());
+ Socket s1 = this.channel1.socket();
+ // Action of not connected
+ assertSocketAction_NonBlock_BeforeConnect(s1);
+ Socket s2 = this.channel1.socket();
+ // same
+ assertSame(s1, s2);
+ }
+ }
+
+ public void testSocket_NonBlock_ActionsAfterConnectAfterFinish()
+ throws Exception {
+ assertFalse(this.channel1.isConnected());// not connected
+ this.channel1.configureBlocking(false);
+ channel1.connect(localAddr1);
+ if (tryFinish()) {
+ Socket s1 = this.channel1.socket();
+ assertSocketAction_NonBlock_AfterConnect(s1);
+ Socket s2 = this.channel1.socket();
+ // same
+ assertSame(s1, s2);
+ }
+ }
+
+ public void testSocket_getInetAddress() throws Exception {
+ Socket socket = channel1.socket();
+ assertNull(socket.getInetAddress());
+
+ channel1.connect(localAddr1);
+
+ assertNotNull(socket.getInetAddress());
+ assertEquals(localAddr1.getAddress(), socket.getInetAddress());
+ }
+
+ public void testSocket_getRemoteSocketAddress() throws Exception {
+ Socket socket = channel1.socket();
+ assertNull(socket.getRemoteSocketAddress());
+
+ channel1.connect(localAddr1);
+
+ assertNotNull(socket.getRemoteSocketAddress());
+ assertEquals(localAddr1, socket.getRemoteSocketAddress());
+ }
+
+ public void testSocket_getPort() throws Exception {
+ Socket socket = channel1.socket();
+ assertEquals(0, socket.getPort());
+
+ channel1.connect(localAddr1);
+
+ assertEquals(localAddr1.getPort(), socket.getPort());
+ }
+
+ public void testSocket_getLocalAddress() throws Exception {
+ Socket socket = channel1.socket();
+ assertNotNull(socket.getLocalAddress());
+
+ channel1.connect(localAddr1);
+
+ assertNotNull(socket.getLocalAddress());
+ }
+
+ public void testSocket_getLocalSocketAddress() throws Exception {
+ Socket socket = channel1.socket();
+ assertNull(socket.getLocalSocketAddress());
+
+ channel1.connect(localAddr1);
+
+ assertNotNull(socket.getLocalSocketAddress());
+ }
+
+ public void testSocket_getLocalPort() throws Exception {
+ Socket socket = channel1.socket();
+ assertEquals(-1, socket.getLocalPort());
+
+ channel1.connect(localAddr1);
+
+ assertTrue(-1 != socket.getLocalPort());
+ assertTrue(0 != socket.getLocalPort());
+ }
+
+ public void testSocket_bind() throws Exception {
+ Socket socket = channel1.socket();
+ socket.bind(new InetSocketAddress("127.0.0.1", 0));
+ assertEquals("127.0.0.1", socket.getLocalAddress().getHostAddress());
+ assertTrue(socket.getLocalPort() != -1);
+ }
+
+ private void assertSocketBeforeConnect(Socket s) throws IOException {
+ assertFalse(s.isBound());
+ assertFalse(s.isClosed());
+ assertFalse(s.isConnected());
+ assertFalse(s.getKeepAlive());
+ try {
+ s.getInputStream();
+ fail("Should throw SocketException.");
+ } catch (SocketException e) {
+ // OK.
+ }
+ assertFalse(s.getOOBInline());
+ try {
+ s.getOutputStream();
+ fail("Should throw SocketException.");
+ } catch (SocketException e) {
+ // OK.
+ }
+ assertEquals(-1, s.getSoLinger());
+ assertFalse(s.getTcpNoDelay());
+
+ assertFalse(s.isInputShutdown());
+ assertFalse(s.isOutputShutdown());
+
+ assertNull(s.getInetAddress());
+ assertEquals(s.getLocalAddress().getHostAddress(), "0.0.0.0");
+ // RI fails here. RI returns 0 while spec says unbound socket should
+ // return -1.
+ assertEquals(-1, s.getLocalPort());
+ assertFalse(s.getReuseAddress());
+ assertNull(s.getLocalSocketAddress());
+
+ // not connected
+ assertEquals(0, s.getPort());
+ assertTrue(s.getReceiveBufferSize() >= 8192);
+ assertNull(s.getRemoteSocketAddress());
+ assertTrue(s.getSendBufferSize() >= 8192);
+ assertEquals(0, s.getSoTimeout());
+ assertEquals(0, s.getTrafficClass());
+
+ }
+
+ private void assertSocketAfterConnect(Socket s, InetSocketAddress address)
+ throws IOException {
+ assertTrue(s.isBound());
+ assertFalse(s.isClosed());
+ assertTrue(s.isConnected());
+ assertFalse(s.getKeepAlive());
+
+ assertNotNull(s.getInputStream());
+ assertNotNull(s.getOutputStream());
+
+ assertFalse(s.getOOBInline());
+ assertEquals(-1, s.getSoLinger());
+ assertFalse(s.getTcpNoDelay());
+
+ assertFalse(s.isInputShutdown());
+ assertFalse(s.isOutputShutdown());
+
+ assertSame(s.getInetAddress(), address.getAddress());
+
+ assertEquals(s.getLocalAddress(), this.localAddr1.getAddress());
+ assertEquals(s.getPort(), address.getPort());
+ assertNotNull(s.getLocalSocketAddress());
+ assertTrue(s.getReceiveBufferSize() >= 8192);
+ assertEquals(s.getRemoteSocketAddress(), (SocketAddress) address);
+ // assertFalse(s.getReuseAddress());
+ assertTrue(s.getSendBufferSize() >= 8192);
+ assertEquals(0, s.getSoTimeout());
+ assertEquals(0, s.getTrafficClass());
+ }
+
+ private void assertSocketAction_Block_BeforeConnect(Socket s)
+ throws IOException {
+ assertFalse(this.channel1.isConnected());
+ this.server2 = new ServerSocket(localAddr2.getPort());
+ s.connect(localAddr2);
+ assertTrue(this.channel1.isConnected());
+ assertTrue(s.isConnected());
+
+ assertSocketAfterConnect(s, localAddr2);
+
+ try {
+ s.bind(localAddr2);
+ fail("Should throw AlreadyConnectedException");
+ } catch (AlreadyConnectedException e) {
+ // OK.
+ }
+
+ s.close();
+ assertTrue(s.isClosed());
+ assertFalse(this.channel1.isOpen());
+ }
+
+ private void assertSocketAction_NonBlock_BeforeConnect(Socket s)
+ throws IOException {
+ assertFalse(this.channel1.isConnected());
+ this.server2 = new ServerSocket(localAddr2.getPort());
+ try {
+ s.connect(localAddr2);
+ fail("Should throw IllegalBlockingModeException");
+ } catch (IllegalBlockingModeException e1) {
+ // OK.
+ }
+
+ if (this.channel1.isConnectionPending()) {
+ try {
+ s.bind(localAddr2);
+ fail("Should throw ConnectionPendingException");
+ } catch (ConnectionPendingException e1) {
+ // OK.
+ }
+ } else {
+ try {
+ s.bind(localAddr2);
+ fail("Should throw BindException");
+ } catch (BindException e1) {
+ // OK.
+ }
+ }
+
+ assertFalse(this.channel1.isConnected());
+ assertFalse(s.isConnected());
+
+ s.close();
+ assertTrue(s.isClosed());
+ assertFalse(this.channel1.isOpen());
+ }
+
+ private void assertSocketAction_Block_AfterConnect(Socket s)
+ throws IOException {
+ assertEquals(s.getPort(), localAddr1.getPort());
+ assertTrue(this.channel1.isConnected());
+ assertTrue(s.isConnected());
+ try {
+ s.connect(localAddr2);
+ fail("Should throw AlreadyConnectedException");
+ } catch (AlreadyConnectedException e) {
+ // OK.
+ }
+
+ try {
+ s.bind(localAddr2);
+ fail("Should throw AlreadyConnectedException");
+ } catch (AlreadyConnectedException e) {
+ // OK.
+ }
+
+ s.close();
+ assertTrue(s.isClosed());
+ assertFalse(this.channel1.isOpen());
+ }
+
+ private void assertSocketAction_NonBlock_AfterConnect(Socket s)
+ throws IOException {
+ assertEquals(s.getPort(), localAddr1.getPort());
+ assertTrue(this.channel1.isConnected());
+ assertTrue(s.isConnected());
+
+ if (this.channel1.isConnectionPending()) {
+ try {
+ s.connect(localAddr2);
+ fail("Should throw AlreadyConnectedException");
+ } catch (AlreadyConnectedException e) {
+ // OK.
+ }
+ } else {
+ try {
+ s.connect(localAddr2);
+ fail("Should throw IllegalBlockingModeException");
+ } catch (IllegalBlockingModeException e) {
+ // OK.
+ }
+ }
+
+ try {
+ s.bind(localAddr2);
+ fail("Should throw AlreadyConnectedException");
+ } catch (AlreadyConnectedException e) {
+ // OK.
+ }
+
+ s.close();
+ assertTrue(s.isClosed());
+ assertFalse(this.channel1.isOpen());
+ }
+
+ // -------------------------------------------------------------------
+ // Tests for connect(), finishConnect(),isConnected(),isConnectionPending()
+ // These methods are very close, so we test them together, call them "CFII".
+ // -------------------------------------------------------------------
+ /**
+ * connect-->finish-->close
+ */
+ public void testCFII_Norml_NoServer_Block() throws Exception {
+ // ensure
+ ensureServerClosed();
+ assertTrue(this.channel1.isBlocking());
+ statusNotConnected_NotPending();
+ // connect
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw a ConnectException here.");
+ } catch (ConnectException e) {
+ // OK.
+ }
+ statusChannelClosed();
+ try {
+ this.channel1.finishConnect();
+ fail("Should throw a ClosedChannelException here.");
+ } catch (ClosedChannelException e) {
+ // OK.
+ }
+ }
+
+ /**
+ * connect-->finish-->close
+ */
+ public void testCFII_Norml_NoServer_NonBlock() throws Exception {
+ connectNoServerNonBlock();
+
+ this.channel1.close();
+ statusChannelClosed();
+ }
+
+ /**
+ * connect-->finish-->close
+ */
+ public void testCFII_Norml_Server_Block() throws Exception {
+ connectServerBlock();
+
+ this.channel1.close();
+ statusChannelClosed();
+
+ }
+
+ /**
+ * connect-->finish-->close
+ */
+ public void testCFII_Norml_Server_NonBlock() throws Exception {
+ connectServerNonBlock();
+
+ this.channel1.close();
+ statusChannelClosed();
+ }
+
+ /**
+ * connect-->server closed-->finish-->close
+ */
+ public void testCFII_ServerClosed_Block() throws Exception {
+ // ensure
+ ensureServerOpen();
+ assertTrue(this.channel1.isBlocking());
+ statusNotConnected_NotPending();
+ // connect
+ assertTrue(this.channel1.connect(localAddr1));
+ statusConnected_NotPending();
+
+ ensureServerClosed();
+
+ tryFinish();
+
+ this.channel1.close();
+ statusChannelClosed();
+
+ }
+
+ /**
+ * connect-->server closed-->finish-->close
+ */
+ public void testCFII_ServerClosed_NonBlock() throws Exception {
+ // ensure
+ ensureServerOpen();
+ this.channel1.configureBlocking(false);
+ statusNotConnected_NotPending();
+ // connect
+ boolean connected = channel1.connect(localAddr1);
+ if (!connected) {
+ statusNotConnected_Pending();
+ }
+ ensureServerClosed();
+
+ tryFinish();
+
+ this.channel1.close();
+ statusChannelClosed();
+ }
+
+ /**
+ * connect-->finish-->server closed-->close
+ */
+ public void testCFII_ServerClosedAfterFinish_Block() throws Exception {
+ connectServerBlock();
+
+ ensureServerClosed();
+ assertTrue(this.channel1.isOpen());
+ this.channel1.close();
+ statusChannelClosed();
+
+ }
+
+ /**
+ * connect-->finish-->server closed-->close
+ */
+ public void testCFII_ServerClosedAfterFinish_NonBlock() throws Exception {
+ connectServerNonBlock();
+
+ ensureServerClosed();
+ assertTrue(this.channel1.isOpen());
+ this.channel1.close();
+ statusChannelClosed();
+ }
+
+ /**
+ * no server-->connect-->server open-->finish-->close
+ */
+ public void testCFII_ServerStartLater_Block() throws Exception {
+ // ensure
+ ensureServerClosed();
+ assertTrue(this.channel1.isBlocking());
+ statusNotConnected_NotPending();
+ // connect
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw a ConnectException here.");
+ } catch (ConnectException e) {
+ // OK.
+ }
+ statusChannelClosed();
+ ensureServerOpen();
+ try {
+ this.channel1.finishConnect();
+ fail("Should throw a ClosedChannelException here.");
+ } catch (ClosedChannelException e) {
+ // OK.
+ }
+ }
+
+ /**
+ * no server-->connect-->server open-->finish-->close
+ */
+ public void testCFII_ServerStartLater_NonBlock() throws Exception {
+ // ensure
+ ensureServerClosed();
+ this.channel1.configureBlocking(false);
+ statusNotConnected_NotPending();
+ // connect
+ assertFalse(this.channel1.connect(localAddr1));
+ statusNotConnected_Pending();
+
+ ensureServerOpen();
+
+ try {
+ assertFalse(this.channel1.finishConnect());
+ statusNotConnected_Pending();
+ this.channel1.close();
+ } catch (ConnectException e) {
+ // FIXME: assertEquals(e.getMessage(), "Connection refused");
+ }
+ }
+
+ /**
+ * connect-->finish-->finish-->close
+ */
+ public void testCFII_FinishTwice_NoServer_NonBlock() throws Exception {
+ // ensure
+ ensureServerClosed();
+ this.channel1.configureBlocking(false);
+ statusNotConnected_NotPending();
+ // connect
+ assertFalse(this.channel1.connect(localAddr1));
+ statusNotConnected_Pending();
+ try {
+ assertFalse(this.channel1.finishConnect());
+ statusNotConnected_Pending();
+ assertFalse(this.channel1.finishConnect());
+ statusNotConnected_Pending();
+ this.channel1.close();
+ } catch (ConnectException e) {
+ // FIXME: assertEquals(e.getMessage(), "Connection refused");
+ }
+ statusChannelClosed();
+ }
+
+ /**
+ * connect-->finish-->finish-->close
+ */
+ public void testCFII_FinishTwice_Server_Block() throws Exception {
+ connectServerBlock();
+ tryFinish();
+ this.channel1.close();
+ statusChannelClosed();
+
+ }
+
+ /**
+ * connect-->finish-->finish-->close
+ */
+ public void testCFII_FinishTwice_Server_NonBlock() throws Exception {
+ connectServerNonBlock();
+ tryFinish();
+ this.channel1.close();
+ statusChannelClosed();
+ }
+
+ /**
+ * connect-->finish-->connect-->close
+ */
+ public void testCFII_ConnectAfterFinish_NoServer_Block() throws Exception {
+ // ensure
+ ensureServerClosed();
+ assertTrue(this.channel1.isBlocking());
+ statusNotConnected_NotPending();
+ // connect
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw a ConnectException here.");
+ } catch (ConnectException e) {
+ // OK.
+ }
+ statusChannelClosed();
+ try {
+ this.channel1.finishConnect();
+ fail("Should throw a ClosedChannelException here.");
+ } catch (ClosedChannelException e) {
+ // OK.
+ }
+ statusChannelClosed();
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw a ClosedChannelException here.");
+ } catch (ClosedChannelException e) {
+ // OK.
+ }
+ statusChannelClosed();
+ }
+
+ /**
+ * connect-->finish-->connect-->close
+ */
+ public void testCFII_ConnectAfterFinish_NoServer_NonBlock()
+ throws Exception {
+ // ensure
+ ensureServerClosed();
+ this.channel1.configureBlocking(false);
+ statusNotConnected_NotPending();
+ // connect
+ assertFalse(this.channel1.connect(localAddr1));
+ statusNotConnected_Pending();
+ try {
+ assertFalse(this.channel1.finishConnect());
+ statusNotConnected_Pending();
+ } catch (ConnectException e) {
+ // FIXME: assertEquals(e.getMessage(), "Connection refused");
+ }
+
+ if (this.channel1.isOpen()) {
+
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw a ConnectionPendingException here.");
+ } catch (ConnectionPendingException e) {
+ // OK.
+ }
+ statusNotConnected_Pending();
+
+ // connect another addr
+ try {
+ this.channel1.connect(localAddr2);
+ fail("Should throw a ConnectionPendingException here.");
+ } catch (ConnectionPendingException e) {
+ // OK.
+ }
+ statusNotConnected_Pending();
+
+ // connect if server closed
+ ensureServerClosed();
+
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw a ConnectionPendingException here.");
+ } catch (ConnectionPendingException e) {
+ // OK.
+ }
+ statusNotConnected_Pending();
+
+ this.channel1.close();
+ }
+ statusChannelClosed();
+ }
+
+ /**
+ * connect-->finish-->connect-->close
+ */
+ public void testCFII_ConnectAfterFinish_Server_Block() throws Exception {
+ connectServerBlock();
+
+ if (!this.channel1.isConnected()) {
+ System.err
+ .println("Connection fail, testCFII_ConnectAfterFinish_Server_Block is not finished.");
+ return;
+ }
+
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw an AlreadyConnectedException here.");
+ } catch (AlreadyConnectedException e) {
+ // OK.
+ }
+ statusConnected_NotPending();
+
+ // connect another addr
+ try {
+ this.channel1.connect(localAddr2);
+ fail("Should throw an AlreadyConnectedException here.");
+ } catch (AlreadyConnectedException e) {
+ // OK.
+ }
+ statusConnected_NotPending();
+
+ // connect if server closed
+ ensureServerClosed();
+
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw an AlreadyConnectedException here.");
+ } catch (AlreadyConnectedException e) {
+ // OK.
+ }
+ statusConnected_NotPending();
+
+ this.channel1.close();
+ statusChannelClosed();
+
+ }
+
+ /**
+ * connect-->finish-->connect-->close
+ */
+ public void testCFII_ConnectAfterFinish_Server_NonBlock() throws Exception {
+ connectServerNonBlock();
+
+ if (!this.channel1.isConnected()) {
+ System.err
+ .println("Connection fail, testCFII_ConnectAfterFinish_Server_Block is not finished.");
+ return;
+ }
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw an AlreadyConnectedException or a ConnectionPendingException here.");
+ } catch (AlreadyConnectedException e) {
+ // OK.
+ }
+
+ statusConnected_NotPending();
+
+ // connect another addr
+ try {
+ this.channel1.connect(localAddr2);
+ fail("Should throw an AlreadyConnectedException here.");
+ } catch (AlreadyConnectedException e) {
+ // OK.
+ }
+ statusConnected_NotPending();
+
+ // connect if server closed
+ ensureServerClosed();
+
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw an AlreadyConnectedException here.");
+ } catch (AlreadyConnectedException e) {
+ // OK.
+ }
+ statusConnected_NotPending();
+
+ this.channel1.close();
+ statusChannelClosed();
+ }
+
+ /**
+ * connect-->connect-->finish-->close
+ */
+ public void testCFII_ConnectTwice_NoServer_NonBlock() throws Exception {
+ // ensure
+ ensureServerClosed();
+ this.channel1.configureBlocking(false);
+ statusNotConnected_NotPending();
+ // connect
+ assertFalse(this.channel1.connect(localAddr1));
+ statusNotConnected_Pending();
+
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw a ConnectionPendingException here.");
+ } catch (ConnectionPendingException e) {
+ // OK.
+ }
+ statusNotConnected_Pending();
+
+ // connect another addr
+ try {
+ this.channel1.connect(localAddr2);
+ fail("Should throw a ConnectionPendingException here.");
+ } catch (ConnectionPendingException e) {
+ // OK.
+ }
+ statusNotConnected_Pending();
+
+ // connect if server closed
+ ensureServerClosed();
+
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw a ConnectionPendingException here.");
+ } catch (ConnectionPendingException e) {
+ // OK.
+ }
+ statusNotConnected_Pending();
+
+ try {
+ assertFalse(this.channel1.finishConnect());
+ statusNotConnected_Pending();
+ this.channel1.close();
+ } catch (ConnectException e) {
+ // FIXME: assertEquals(e.getMessage(), "Connection refused");
+ }
+
+ statusChannelClosed();
+ }
+
+ /**
+ * connect-->connect-->finish-->close
+ */
+ public void testCFII_ConnectTwice_Server_Block() throws Exception {
+ // ensure
+ ensureServerOpen();
+ assertTrue(this.channel1.isBlocking());
+ statusNotConnected_NotPending();
+ // connect
+ assertTrue(this.channel1.connect(localAddr1));
+ statusConnected_NotPending();
+
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw an AlreadyConnectedException here.");
+ } catch (AlreadyConnectedException e) {
+ // OK.
+ }
+ statusConnected_NotPending();
+
+ // connect another addr
+ try {
+ this.channel1.connect(localAddr2);
+ fail("Should throw an AlreadyConnectedException here.");
+ } catch (AlreadyConnectedException e) {
+ // OK.
+ }
+ statusConnected_NotPending();
+
+ // connect if server closed
+ ensureServerClosed();
+
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw an AlreadyConnectedException here.");
+ } catch (AlreadyConnectedException e) {
+ // OK.
+ }
+ statusConnected_NotPending();
+
+ tryFinish();
+
+ this.channel1.close();
+ statusChannelClosed();
+
+ }
+
+ /**
+ * connect-->connect-->finish-->close
+ */
+ public void testCFII_ConnectTwice_Server_NonBlock() throws Exception {
+ // ensure
+ ensureServerOpen();
+ this.channel1.configureBlocking(false);
+ statusNotConnected_NotPending();
+ // connect
+ boolean connected = channel1.connect(localAddr1);
+ if (!connected) {
+ statusNotConnected_Pending();
+
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw a ConnectionPendingException here.");
+ } catch (ConnectionPendingException e) {
+ // OK.
+ }
+ statusNotConnected_Pending();
+
+ // connect another addr
+ try {
+ this.channel1.connect(localAddr2);
+ fail("Should throw a ConnectionPendingException here.");
+ } catch (ConnectionPendingException e) {
+ // OK.
+ }
+ statusNotConnected_Pending();
+
+ // connect if server closed
+ ensureServerClosed();
+
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw a ConnectionPendingException here.");
+ } catch (ConnectionPendingException e) {
+ // OK.
+ }
+ statusNotConnected_Pending();
+ }
+ tryFinish();
+
+ this.channel1.close();
+ statusChannelClosed();
+ }
+
+ /**
+ * finish-->connect-->finish-->close
+ */
+ public void testCFII_FinishFirst_NoServer_Block() throws Exception {
+ // ensure
+ ensureServerClosed();
+ assertTrue(this.channel1.isBlocking());
+ statusNotConnected_NotPending();
+ // finish
+ try {
+ this.channel1.finishConnect();
+ fail("Should throw NoConnectionPendingException");
+ } catch (NoConnectionPendingException e) {
+ // OK.
+ }
+ statusNotConnected_NotPending();
+ // connect
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw a ConnectException here.");
+ } catch (ConnectException e) {
+ // OK.
+ }
+ statusChannelClosed();
+ try {
+ this.channel1.finishConnect();
+ fail("Should throw a ClosedChannelException here.");
+ } catch (ClosedChannelException e) {
+ // OK.
+ }
+ statusChannelClosed();
+ }
+
+ /**
+ * finish-->connect-->finish-->close
+ */
+ public void testCFII_FinishFirst_NoServer_NonBlock() throws Exception {
+ // ensure
+ ensureServerClosed();
+ this.channel1.configureBlocking(false);
+ statusNotConnected_NotPending();
+ // finish
+ try {
+ this.channel1.finishConnect();
+ fail("Should throw NoConnectionPendingException");
+ } catch (NoConnectionPendingException e) {
+ // OK.
+ }
+ statusNotConnected_NotPending();
+ // connect
+ assertFalse(this.channel1.connect(localAddr1));
+ statusNotConnected_Pending();
+
+ try {
+ assertFalse(this.channel1.finishConnect());
+ statusNotConnected_Pending();
+ this.channel1.close();
+ } catch (ConnectException e) {
+ // FIXME: assertEquals(e.getMessage(), "Connection refused");
+ }
+
+ statusChannelClosed();
+ }
+
+ /**
+ * finish-->connect-->finish-->close
+ */
+ public void testCFII_FinishFirst_Server_Block() throws Exception {
+ // ensure
+ ensureServerOpen();
+ assertTrue(this.channel1.isBlocking());
+ statusNotConnected_NotPending();
+ // finish
+ try {
+ this.channel1.finishConnect();
+ fail("Should throw NoConnectionPendingException");
+ } catch (NoConnectionPendingException e) {
+ // OK.
+ }
+ statusNotConnected_NotPending();
+ // connect
+ assertTrue(this.channel1.connect(localAddr1));
+ statusConnected_NotPending();
+
+ tryFinish();
+
+ this.channel1.close();
+ statusChannelClosed();
+
+ }
+
+ /**
+ * finish-->connect-->finish-->close
+ */
+ public void testCFII_FinishFirst_Server_NonBlock() throws Exception {
+ // ensure
+ ensureServerOpen();
+ this.channel1.configureBlocking(false);
+ statusNotConnected_NotPending();
+ // finish
+ try {
+ this.channel1.finishConnect();
+ fail("Should throw NoConnectionPendingException");
+ } catch (NoConnectionPendingException e) {
+ // OK.
+ }
+ statusNotConnected_NotPending();
+ // connect
+ boolean connected = channel1.connect(localAddr1);
+ if (!connected) {
+ statusNotConnected_Pending();
+ }
+ tryFinish();
+
+ this.channel1.close();
+ statusChannelClosed();
+ }
+
+ public void testCFII_Null() throws Exception {
+ statusNotConnected_NotPending();
+ try {
+ this.channel1.connect(null);
+ fail("Should throw an IllegalArgumentException here.");
+ } catch (IllegalArgumentException e) {
+ // OK.
+ }
+ }
+
+ public void testCFII_UnsupportedType() throws Exception {
+ class SubSocketAddress extends SocketAddress {
+ private static final long serialVersionUID = 1L;
+
+ //empty
+ public SubSocketAddress() {
+ super();
+ }
+ }
+ statusNotConnected_NotPending();
+ SocketAddress newTypeAddress = new SubSocketAddress();
+ try {
+ this.channel1.connect(newTypeAddress);
+ fail("Should throw an UnsupportedAddressTypeException here.");
+ } catch (UnsupportedAddressTypeException e) {
+ // OK.
+ }
+ }
+
+ public void testCFII_Unresolved() throws IOException {
+ statusNotConnected_NotPending();
+ InetSocketAddress unresolved = new InetSocketAddress(
+ "unresolved address", 1080);
+ try {
+ this.channel1.connect(unresolved);
+ fail("Should throw an UnresolvedAddressException here.");
+ } catch (UnresolvedAddressException e) {
+ // OK.
+ }
+ }
+
+ public void testCFII_EmptyHost() throws Exception {
+ statusNotConnected_NotPending();
+ ServerSocket server = new ServerSocket(0);
+ int port = server.getLocalPort();
+ server.close();
+ try {
+ this.channel1.connect(new InetSocketAddress("", port));
+ fail("Should throw ConnectException");
+ } catch (ConnectException e) {
+ // correct
+ }
+ }
+
+ public void testCFII_CloseFirst() throws Exception {
+ this.channel1.close();
+ statusChannelClosed();
+ ensureServerOpen();
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw ClosedChannelException.");
+ } catch (ClosedChannelException e) {
+ // OK.
+ }
+ statusChannelClosed();
+ try {
+ this.channel1.finishConnect();
+ fail("Should throw ClosedChannelException.");
+ } catch (ClosedChannelException e) {
+ // OK.
+ }
+ statusChannelClosed();
+ try {
+ this.channel1.configureBlocking(false);
+ fail("Should throw ClosedChannelException.");
+ } catch (ClosedChannelException e) {
+ // OK.
+ }
+ statusChannelClosed();
+ }
+
+ public void testCFII_StatusAfterFinish() throws Exception {
+ // 1. close server, finish must return false, check the status
+ ensureServerClosed();
+
+ // 1.1 block mode
+ assertTrue(this.channel1.isBlocking());
+ try {
+ channel1.connect(localAddr1);
+ fail("Should throw ConnectException");
+ } catch (ConnectException e) {
+ // OK.
+ }
+ assertFalse(this.channel1.isOpen());
+
+ assertFalse(this.channel1.isOpen());
+ assertTrue(this.channel1.isBlocking());
+ assertFalse(this.channel1.isConnectionPending());
+
+ // 1.2 non block mode
+ this.channel1 = SocketChannel.open();
+ this.channel1.configureBlocking(false);
+ assertFalse(this.channel1.connect(localAddr1));
+ try {
+ assertFalse(this.channel1.finishConnect());
+ statusNotConnected_Pending();
+ this.channel1.close();
+ } catch (ConnectException e) {
+ System.out.println(e.getMessage());
+ }
+
+ // 2. start server, finish usually return true, check the status
+ ensureServerOpen();
+
+ // 2.1 block mode
+ this.channel1 = SocketChannel.open();
+ assertTrue(this.channel1.isBlocking());
+ assertTrue(this.channel1.connect(localAddr1));
+ assertTrue(this.channel1.finishConnect());
+ statusConnected_NotPending();
+ this.channel1.close();
+
+ // 2.2 non block mode
+ this.channel1 = SocketChannel.open();
+ this.channel1.configureBlocking(false);
+ assertFalse(this.channel1.connect(localAddr1));
+ tryFinish();
+ this.channel1.close();
+ }
+
+ private void ensureServerClosed() throws IOException {
+ if (null != this.server1) {
+ this.server1.close();
+ assertTrue(this.server1.isClosed());
+ }
+ if (null != this.server2) {
+ this.server2.close();
+ assertTrue(this.server2.isClosed());
+ }
+ }
+
+ private void ensureServerOpen() throws IOException {
+ ensureServerClosed();
+ this.server1 = new ServerSocket(localAddr1.getPort());
+ this.server2 = new ServerSocket(localAddr2.getPort());
+ assertTrue(this.server1.isBound());
+ assertTrue(this.server2.isBound());
+ }
+
+ private void connectNoServerNonBlock() throws Exception {
+ // ensure
+ ensureServerClosed();
+ this.channel1.configureBlocking(false);
+ statusNotConnected_NotPending();
+ // connect
+ assertFalse(this.channel1.connect(localAddr1));
+ statusNotConnected_Pending();
+ try {
+ assertFalse(this.channel1.finishConnect());
+ statusNotConnected_Pending();
+ } catch (ConnectException e) {
+ // FIXME: assertEquals(e.getMessage(), "Connection refused");
+ }
+ }
+
+ private void connectServerNonBlock() throws Exception {
+ // ensure
+ ensureServerOpen();
+ this.channel1.configureBlocking(false);
+ statusNotConnected_NotPending();
+ // connect
+ boolean connected = channel1.connect(localAddr1);
+ if (!connected) {
+ statusNotConnected_Pending();
+ }
+ tryFinish();
+ }
+
+ private void connectServerBlock() throws Exception {
+ // ensure
+ ensureServerOpen();
+ assertTrue(this.channel1.isBlocking());
+ statusNotConnected_NotPending();
+ // connect
+ assertTrue(this.channel1.connect(localAddr1));
+ statusConnected_NotPending();
+ tryFinish();
+ }
+
+ private void statusChannelClosed() {
+ assertFalse(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertFalse(this.channel1.isOpen());
+ }
+
+ private void statusNotConnected_NotPending() {
+ assertFalse(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ }
+
+ private void statusNotConnected_Pending() {
+ assertFalse(this.channel1.isConnected());
+ assertTrue(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ }
+
+ private void statusConnected_NotPending() {
+ assertTrue(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ }
+
+ private boolean tryFinish() throws IOException {
+ /*
+ * the result of finish will be asserted in multi-thread tests.
+ */
+ boolean connected = false;
+ assertTrue(this.channel1.isOpen());
+ try {
+ connected = this.channel1.finishConnect();
+ } catch (SocketException e) {
+ // Finish connection failed, probably due to reset by peer error.
+ }
+ if (connected) {
+ statusConnected_NotPending();
+ }
+ return connected;
+ }
+
+ // -------------------------------------------------------------------
+ // Original tests. Test method for CFII with real data.
+ // -------------------------------------------------------------------
+
+ /**
+ *
+ * 'SocketChannelImpl.connect(SocketAddress)'
+ */
+ public void testCFII_Data_ConnectWithServer() throws Exception {
+ ensureServerOpen();
+ java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer
+ .allocate(CAPACITY_NORMAL);
+ java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1];
+ writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
+ assertFalse(this.channel1.isRegistered());
+ assertTrue(this.channel1.isBlocking());
+
+ this.channel1.connect(localAddr1);
+
+ assertTrue(this.channel1.isBlocking());
+ assertTrue(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf));
+ assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBufArr, 0, 1));
+
+ this.channel1.configureBlocking(false);
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw AlreadyConnectedException");
+ } catch (AlreadyConnectedException e) {
+ // correct
+ }
+
+ assertFalse(this.channel1.isRegistered());
+ tryFinish();
+ }
+
+ /*
+ * Test method for 'SocketChannelImpl.connect(SocketAddress)'
+ */
+ public void testCFII_Data_ConnectWithServer_nonBlocking() throws Exception {
+ ensureServerOpen();
+ java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer
+ .allocate(CAPACITY_NORMAL);
+ java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1];
+ writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
+ assertFalse(this.channel1.isRegistered());
+ assertTrue(this.channel1.isBlocking());
+ this.channel1.configureBlocking(false);
+ this.channel1.connect(localAddr1);
+
+ assertFalse(this.channel1.isBlocking());
+ boolean connected = channel1.isConnected();
+ if (!connected) {
+ assertTrue(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ }
+ if (tryFinish()) {
+ assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf));
+ assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBufArr, 0, 1));
+
+ this.channel1.configureBlocking(false);
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw AlreadyConnectedException");
+ } catch (AlreadyConnectedException e) {
+ // correct
+ }
+ }
+
+ assertFalse(this.channel1.isRegistered());
+ tryFinish();
+ }
+
+ /*
+ * Test method for 'SocketChannelImpl.finishConnect()'
+ */
+ public void testCFII_Data_FinishConnect_nonBlocking() throws IOException {
+ ensureServerOpen();
+
+ java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer
+ .allocate(CAPACITY_NORMAL);
+ java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1];
+ writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
+
+ this.channel1.configureBlocking(false);
+ try {
+ this.channel1.finishConnect();
+ fail("Should throw NoConnectionPendingException");
+ } catch (NoConnectionPendingException e) {
+ // correct
+ }
+ boolean connected = channel1.connect(localAddr1);
+ if (!connected) {
+ assertFalse(this.channel1.isBlocking());
+ assertFalse(this.channel1.isConnected());
+ assertTrue(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ }
+ this.server1.accept();
+ if (tryFinish()) {
+ assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf));
+ assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBufArr, 0, 1));
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw AlreadyConnectedException");
+ } catch (AlreadyConnectedException e) {
+ // correct
+ }
+ }
+ assertFalse(this.channel1.isRegistered());
+ tryFinish();
+ }
+
+ public void testCFII_Data_FinishConnect_AddrSetServerStartLater()
+ throws IOException, InterruptedException {
+ ensureServerClosed();
+ java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1];
+ writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
+ this.channel1.configureBlocking(false);
+ try {
+ SocketChannel.open(localAddr1);
+ fail("Should throw ConnectException");
+ } catch (ConnectException e) {
+ // correct
+ }
+ assertTrue(this.channel1.isOpen());
+ assertFalse(this.channel1.isBlocking());
+ assertFalse(this.channel1.isConnectionPending());
+ this.channel1.configureBlocking(true);
+ try {
+ this.channel1.finishConnect();
+ fail("Should throw NoConnectionPendingException");
+ } catch (NoConnectionPendingException e) {
+ // correct
+ }
+ try {
+ this.channel1.connect(localAddr2);
+ fail("Should throw ConnectException");
+ } catch (ConnectException e) {
+ // correct
+ }
+
+ assertTrue(this.channel1.isBlocking());
+ try {
+ this.channel1.finishConnect();
+ fail("Should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // correct
+ }
+ assertFalse(this.channel1.isConnected());
+ // finish after finish OK
+ assertFalse(this.channel1.isConnectionPending());
+ this.channel1 = SocketChannel.open();
+ this.channel1.configureBlocking(false);
+ this.channel1.connect(localAddr1);
+ assertFalse(this.channel1.isConnected());
+ ensureServerOpen();
+ // cannot connect?
+ try {
+ assertFalse(this.channel1.finishConnect());
+ assertFalse(this.channel1.isBlocking());
+ assertFalse(this.channel1.isConnected());
+ assertTrue(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw ConnectionPendingException");
+ } catch (ConnectionPendingException e) {
+ // correct
+ }
+ this.channel1.configureBlocking(true);
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw ConnectionPendingException");
+ } catch (ConnectionPendingException e) {
+ // correct
+ }
+ tryFinish();
+ } catch (ConnectException e) {
+ // FIXME: assertEquals(e.getMessage(), "Connection refused");
+ }
+ }
+
+ public void testCFII_Data_FinishConnect_ServerStartLater()
+ throws IOException {
+ ensureServerClosed();
+ java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1];
+ writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
+ this.channel1.configureBlocking(true);
+ try {
+ this.channel1.finishConnect();
+ fail("Should throw NoConnectionPendingException");
+ } catch (NoConnectionPendingException e) {
+ // correct
+ }
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw ConnectException");
+ } catch (ConnectException e) {
+ // correct
+ }
+
+ try {
+ this.channel1.finishConnect();
+ fail("Should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // correct
+ }
+ assertFalse(this.channel1.isConnected());
+ // finish after finish OK
+ assertFalse(this.channel1.isConnectionPending());
+ this.channel1 = SocketChannel.open();
+ this.channel1.configureBlocking(false);
+ this.channel1.connect(localAddr1);
+ assertFalse(this.channel1.isConnected());
+ ensureServerOpen();
+ // cannot connect?
+ try {
+ assertFalse(this.channel1.finishConnect());
+ assertFalse(this.channel1.isBlocking());
+ assertFalse(this.channel1.isConnected());
+ assertTrue(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw ConnectionPendingException");
+ } catch (ConnectionPendingException e) {
+ // correct
+ }
+ this.channel1.configureBlocking(true);
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw ConnectionPendingException");
+ } catch (ConnectionPendingException e) {
+ // correct
+ }
+ tryFinish();
+ } catch (ConnectException e) {
+ // FIXME: assertEquals(e.getMessage(), "Connection refused");
+ }
+ }
+
+ public void testCFII_Data_FinishConnect_Blocking() throws IOException {
+ ensureServerOpen();
+ java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer
+ .allocate(CAPACITY_NORMAL);
+ java.nio.ByteBuffer[] writeBufArr = new java.nio.ByteBuffer[1];
+ writeBufArr[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
+ this.channel1.configureBlocking(true);
+ try {
+ this.channel1.finishConnect();
+ fail("Should throw NoConnectionPendingException");
+ } catch (NoConnectionPendingException e) {
+ // correct
+ }
+
+ this.channel1.connect(localAddr1);
+
+ assertTrue(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ if (tryFinish()) {
+ assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf));
+ assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBufArr, 0, 1));
+
+ try {
+ this.channel1.connect(localAddr1);
+ fail("Should throw AlreadyConnectedException");
+ } catch (AlreadyConnectedException e) {
+ // correct
+ }
+ }
+ assertFalse(this.channel1.isRegistered());
+ tryFinish();
+ }
+
+ /**
+ * Regression test for Harmony-1947.
+ */
+ public void test_finishConnect() throws Exception {
+ SocketAddress address = new InetSocketAddress("localhost", 0);
+
+ ServerSocketChannel theServerChannel = ServerSocketChannel.open();
+ ServerSocket serversocket = theServerChannel.socket();
+ serversocket.setReuseAddress(true);
+ // Bind the socket
+ serversocket.bind(address);
+
+ boolean doneNonBlockingConnect = false;
+ // Loop so that we make sure we're definitely testing finishConnect()
+ while (!doneNonBlockingConnect) {
+ channel1 = SocketChannel.open();
+
+ // Set the SocketChannel to non-blocking so that connect(..) does
+ // not block
+ channel1.configureBlocking(false);
+ boolean connected = channel1.connect(new InetSocketAddress("localhost",serversocket.getLocalPort()));
+ if (!connected) {
+ // Now set the SocketChannel back to blocking so that
+ // finishConnect() blocks.
+ channel1.configureBlocking(true);
+ doneNonBlockingConnect = channel1.finishConnect();
+ }
+ if (doneNonBlockingConnect) {
+ tryFinish();
+ }
+ channel1.close();
+ }
+ if (!serversocket.isClosed()) {
+ serversocket.close();
+ }
+ }
+
+ // -------------------------------------------------------------------
+ // End of original tests. Test method for CFII with real data.
+ // -------------------------------------------------------------------
+
+ /**
+ * @tests java.nio.channels.SocketChannel#read(ByteBuffer)
+ */
+ public void test_readLjava_nio_ByteBuffer_Blocking() throws IOException {
+ // initialize write content
+ byte[] writeContent = new byte[CAPACITY_NORMAL];
+ for (int i = 0; i < writeContent.length; i++) {
+ writeContent[i] = (byte) i;
+ }
+ // establish connection
+ channel1.connect(localAddr1);
+ Socket acceptedSocket = server1.accept();
+
+ // use OutputStream.write to send CAPACITY_NORMAL bytes data
+ OutputStream out = acceptedSocket.getOutputStream();
+ out.write(writeContent);
+ // use close to guarantee all data is sent
+ acceptedSocket.close();
+
+ ByteBuffer readContent = ByteBuffer.allocate(CAPACITY_NORMAL + 1);
+ int totalCount = 0;
+ int count = 0;
+ long startTime = System.currentTimeMillis();
+ // use SocketChannel.read to read data
+ while (totalCount <= CAPACITY_NORMAL) {
+ count = channel1.read(readContent);
+ if (EOF == count) {
+ break;
+ }
+ totalCount += count;
+ // if the channel could not finish reading in TIMEOUT ms, the
+ // test fails. It is used to guarantee the test never hangs even
+ // if there are bugs of SocketChannel implementation. For
+ // blocking read, it possibly returns 0 in some cases.
+ assertTimeout(startTime, TIMEOUT);
+ }
+ assertEquals(CAPACITY_NORMAL, totalCount);
+ readContent.flip();
+ for (int i = 0; i < CAPACITY_NORMAL; i++) {
+ assertEquals(writeContent[i], readContent.get());
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.SocketChannel#read(ByteBuffer)
+ */
+ public void test_readLjava_nio_ByteBuffer_Nonblocking() throws IOException {
+ // initialize write content
+ byte[] writeContent = new byte[CAPACITY_NORMAL];
+ for (int i = 0; i < writeContent.length; i++) {
+ writeContent[i] = (byte) i;
+ }
+
+ // establish connection
+ channel1.connect(localAddr1);
+ Socket acceptedSocket = server1.accept();
+ // use OutputStream.write to write CAPACITY_NORMAL bytes data.
+ OutputStream out = acceptedSocket.getOutputStream();
+ out.write(writeContent);
+ // use close to guarantee all data is sent
+ acceptedSocket.close();
+
+ channel1.configureBlocking(false);
+ ByteBuffer readContent = ByteBuffer.allocate(CAPACITY_NORMAL + 1);
+ int totalCount = 0;
+ int count = 0;
+ long startTime = System.currentTimeMillis();
+ // use SocketChannel.read to read data
+ while (totalCount <= CAPACITY_NORMAL) {
+ count = channel1.read(readContent);
+ if (EOF == count) {
+ break;
+ }
+ totalCount += count;
+ // if the channel could not finish reading in TIMEOUT ms, the
+ // test fails. It is used to guarantee the test never hangs even
+ // if there are bugs of SocketChannel implementation.
+ assertTimeout(startTime, TIMEOUT);
+ }
+
+ // assert read content
+ assertEquals(CAPACITY_NORMAL, totalCount);
+ assertEquals(CAPACITY_NORMAL, readContent.position());
+ readContent.flip();
+ for (int i = 0; i < CAPACITY_NORMAL; i++) {
+ assertEquals(writeContent[i], readContent.get());
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.SocketChannel#write(ByteBuffer)
+ */
+ public void test_writeLjava_nio_ByteBuffer_Blocking() throws IOException {
+ // initialize write content
+ ByteBuffer writeContent = ByteBuffer.allocate(CAPACITY_NORMAL);
+ for (int i = 0; i < CAPACITY_NORMAL; i++) {
+ writeContent.put((byte) i);
+ }
+ writeContent.flip();
+ // establish connection
+ channel1.connect(localAddr1);
+ Socket acceptedSocket = server1.accept();
+
+ // use SocketChannel.write(ByteBuffer) to write CAPACITY_NORMAL bytes
+ // data
+ int writtenCount = channel1.write(writeContent);
+ // assert written count and ByteBuffer position
+ assertEquals(CAPACITY_NORMAL, writtenCount);
+ assertEquals(CAPACITY_NORMAL, writeContent.position());
+ // use close to guarantee all data is sent
+ channel1.close();
+
+ InputStream in = acceptedSocket.getInputStream();
+ int totalCount = 0;
+ int count = 0;
+ byte[] readContent = new byte[CAPACITY_NORMAL + 1];
+ // if the channel could not finish reading in TIMEOUT ms, the test
+ // fails. It is used to guarantee the test never hangs even if there
+ // are bugs of SocketChannel implementation.
+ acceptedSocket.setSoTimeout(TIMEOUT);
+
+ // use InputStream.read to read data.
+ while (totalCount <= CAPACITY_NORMAL) {
+ count = in.read(readContent, totalCount, readContent.length
+ - totalCount);
+ if (EOF == count) {
+ break;
+ }
+ totalCount += count;
+ }
+
+ // assert read content
+ assertEquals(CAPACITY_NORMAL, totalCount);
+ writeContent.flip();
+ for (int i = 0; i < CAPACITY_NORMAL; i++) {
+ assertEquals(writeContent.get(), readContent[i]);
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.SocketChannel#write(ByteBuffer)
+ */
+ public void test_writeLjava_nio_ByteBuffer_NonBlocking() throws Exception {
+ // initialize write content
+ ByteBuffer writeContent = ByteBuffer.allocate(CAPACITY_NORMAL);
+ for (int i = 0; i < CAPACITY_NORMAL; i++) {
+ writeContent.put((byte) i);
+ }
+ writeContent.flip();
+
+ // establish connection
+ channel1.connect(localAddr1);
+ Socket acceptedSocket = server1.accept();
+
+ channel1.configureBlocking(false);
+ int writtenTotalCount = 0;
+ int writtenCount = 0;
+ long startTime = System.currentTimeMillis();
+ // use SocketChannel.write(ByteBuffer) to write CAPACITY_NORMAL bytes
+ while (writtenTotalCount < CAPACITY_NORMAL) {
+ writtenCount = channel1.write(writeContent);
+ writtenTotalCount += writtenCount;
+ // if the channel could not finish writing in TIMEOUT ms, the
+ // test fails. It is used to guarantee the test never hangs even
+ // if there are bugs of SocketChannel implementation.
+ assertTimeout(startTime, TIMEOUT);
+ }
+ // assert written count and ByteBuffer position
+ assertEquals(CAPACITY_NORMAL, writtenTotalCount);
+ assertEquals(CAPACITY_NORMAL, writeContent.position());
+ // use close to guarantee all data is sent
+ channel1.close();
+
+ InputStream in = acceptedSocket.getInputStream();
+ byte[] readContent = new byte[CAPACITY_NORMAL + 1];
+ int totalCount = 0;
+ int count = 0;
+ // if the channel could not finish reading in TIMEOUT ms, the test
+ // fails. It is used to guarantee the test never hangs even if there
+ // are bugs of SocketChannel implementation.
+ acceptedSocket.setSoTimeout(TIMEOUT);
+ // use InputStream.read to read data.
+ while (totalCount <= CAPACITY_NORMAL) {
+ count = in.read(readContent, totalCount, readContent.length
+ - totalCount);
+ if (EOF == count) {
+ break;
+ }
+ totalCount += count;
+ }
+ // assert read content
+ assertEquals(CAPACITY_NORMAL, totalCount);
+ writeContent.flip();
+ for (int i = 0; i < CAPACITY_NORMAL; i++) {
+ assertEquals(writeContent.get(), readContent[i]);
+ }
+ }
+
+ /*
+ * Fails if the difference between current time and start time is greater
+ * than timeout.
+ */
+ private void assertTimeout(long startTime, long timeout) {
+ long currentTime = System.currentTimeMillis();
+ if ((currentTime - startTime) > timeout) {
+ fail("Timeout");
+ }
+ }
+
+ // -------------------------------------------------
+ // Test for read/write but no real data expressed
+ // -------------------------------------------------
+
+ public void testReadByteBuffer() throws Exception {
+ assertTrue(this.server1.isBound());
+ java.nio.ByteBuffer readBuf = java.nio.ByteBuffer
+ .allocate(CAPACITY_NORMAL);
+ assertFalse(this.channel1.isRegistered());
+ assertTrue(this.channel1.isBlocking());
+ assertFalse(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ // note: blocking-mode will make the read process endless!
+ this.channel1.configureBlocking(false);
+ try {
+ channel1.read(readBuf);
+ fail("Should throw NotYetConnectedException");
+ } catch (NotYetConnectedException e) {
+ // correct
+ }
+ boolean connected = this.channel1.connect(localAddr1);
+ if (!connected) {
+ assertFalse(this.channel1.isBlocking());
+ assertTrue(this.channel1.isConnectionPending());
+ assertFalse(this.channel1.isConnected());
+ }
+ if (tryFinish()) {
+ assertEquals(0, this.channel1.read(readBuf));
+ }
+
+ this.channel1.close();
+ try {
+ channel1.read(readBuf);
+ fail("Should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // correct
+ }
+ }
+
+ public void testReadByteBuffer_Direct() throws Exception {
+ assertTrue(this.server1.isBound());
+ java.nio.ByteBuffer readBuf = java.nio.ByteBuffer
+ .allocateDirect(CAPACITY_NORMAL);
+ assertFalse(this.channel1.isRegistered());
+ assertTrue(this.channel1.isBlocking());
+ assertFalse(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ // note: blocking-mode will make the read process endless!
+ this.channel1.configureBlocking(false);
+ try {
+ channel1.read(readBuf);
+ fail("Should throw NotYetConnectedException");
+ } catch (NotYetConnectedException e) {
+ // correct
+ }
+ boolean connected = this.channel1.connect(localAddr1);
+ if (!connected) {
+ assertFalse(this.channel1.isBlocking());
+ assertTrue(this.channel1.isConnectionPending());
+ assertFalse(this.channel1.isConnected());
+ }
+ if (tryFinish()) {
+ assertEquals(0, this.channel1.read(readBuf));
+ }
+
+ this.channel1.close();
+ try {
+ channel1.read(readBuf);
+ fail("Should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // correct
+ }
+ }
+
+ public void testReadByteBuffer_Direct2() throws IOException {
+ byte[] request = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
+ ByteBuffer buffer = ByteBuffer.allocateDirect(128);
+
+ ServerSocketChannel server = ServerSocketChannel.open();
+ server.socket().bind(
+ new InetSocketAddress(InetAddress.getLocalHost(), 0), 5);
+ Socket client = new Socket(InetAddress.getLocalHost(), server.socket()
+ .getLocalPort());
+ client.setTcpNoDelay(false);
+ Socket worker = server.socket().accept();
+ SocketChannel workerChannel = worker.getChannel();
+
+ OutputStream out = client.getOutputStream();
+ out.write(request);
+ out.close();
+
+ buffer.limit(5);
+ int bytesRead = workerChannel.read(buffer);
+ assertEquals(5, bytesRead);
+ assertEquals(5, buffer.position());
+
+ buffer.limit(request.length);
+ bytesRead = workerChannel.read(buffer);
+ assertEquals(6, bytesRead);
+
+ buffer.flip();
+ assertEquals(request.length, buffer.limit());
+
+ assertEquals(ByteBuffer.wrap(request), buffer);
+
+ client.close();
+ worker.close();
+ server.close();
+ }
+
+ public void testReadByteBuffer_BufNull() throws Exception {
+ assertTrue(this.server1.isBound());
+ java.nio.ByteBuffer readBuf = java.nio.ByteBuffer.allocate(0);
+ // note: blocking-mode will make the read process endless!
+ this.channel1.configureBlocking(false);
+ try {
+ channel1.read((java.nio.ByteBuffer) null);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ this.channel1.connect(localAddr1);
+ if (tryFinish()) {
+ try {
+ this.channel1.read((java.nio.ByteBuffer) null);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ assertEquals(0, this.channel1.read(readBuf));
+ }
+ this.server1.close();
+ try {
+ channel1.read((java.nio.ByteBuffer) null);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ }
+
+ /*
+ * SocketChannelImpl.read(ByteBuffer[], int, int)'
+ */
+ public void testReadByteBufferArrayIntInt() throws Exception {
+ assertTrue(this.server1.isBound());
+ java.nio.ByteBuffer[] readBuf = new java.nio.ByteBuffer[2];
+ readBuf[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
+ readBuf[1] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
+ assertFalse(this.channel1.isRegistered());
+ assertTrue(this.channel1.isBlocking());
+ assertFalse(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ // note: blocking-mode will make the read process endless!
+ this.channel1.configureBlocking(false);
+ try {
+ channel1.read(readBuf, 0, 1);
+ fail("Should throw NotYetConnectedException");
+ } catch (NotYetConnectedException e) {
+ // correct
+ }
+ boolean connected = this.channel1.connect(localAddr1);
+ if (!connected) {
+ assertFalse(this.channel1.isBlocking());
+ assertTrue(this.channel1.isConnectionPending());
+ assertFalse(this.channel1.isConnected());
+ }
+ if (tryFinish()) {
+ assertEquals(0, this.channel1.read(readBuf, 0, 1));
+ assertEquals(0, this.channel1.read(readBuf, 0, 2));
+ }
+
+ this.channel1.close();
+ try {
+ channel1.read(readBuf, 0, 1);
+ fail("Should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // correct
+ }
+ }
+
+ /*
+ * SocketChannelImpl.read(ByteBuffer[], int, int)'
+ */
+ public void testReadByteBufferArrayIntInt_Direct() throws Exception {
+ assertTrue(this.server1.isBound());
+ java.nio.ByteBuffer[] readBuf = new java.nio.ByteBuffer[2];
+ readBuf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
+ readBuf[1] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
+ assertFalse(this.channel1.isRegistered());
+ assertTrue(this.channel1.isBlocking());
+ assertFalse(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ // note: blocking-mode will make the read process endless!
+ this.channel1.configureBlocking(false);
+ try {
+ channel1.read(readBuf, 0, 1);
+ fail("Should throw NotYetConnectedException");
+ } catch (NotYetConnectedException e) {
+ // correct
+ }
+ boolean connected = this.channel1.connect(localAddr1);
+ if (!connected) {
+ assertFalse(this.channel1.isBlocking());
+ assertTrue(this.channel1.isConnectionPending());
+ assertFalse(this.channel1.isConnected());
+ }
+ if (tryFinish()) {
+ assertEquals(0, this.channel1.read(readBuf, 0, 1));
+ assertEquals(0, this.channel1.read(readBuf, 0, 2));
+ }
+
+ this.channel1.close();
+ try {
+ channel1.read(readBuf, 0, 1);
+ fail("Should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // correct
+ }
+ }
+
+ public void testReadByteBufferArrayIntInt_BufNull() throws Exception {
+ assertTrue(this.server1.isBound());
+ java.nio.ByteBuffer[] readBuf = new java.nio.ByteBuffer[2];
+ readBuf[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
+ assertFalse(this.channel1.isRegistered());
+ assertTrue(this.channel1.isBlocking());
+ assertFalse(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ // note: blocking-mode will make the read process endless!
+ this.channel1.configureBlocking(false);
+ try {
+ channel1.read(null, 0, 0);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ this.channel1.connect(localAddr1);
+ if (tryFinish()) {
+
+ try {
+ channel1.read(null, 0, 0);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ try {
+ channel1.read(readBuf, 0, 2);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+
+ assertEquals(0, this.channel1.read(readBuf, 0, 1));
+ }
+ this.channel1.close();
+ try {
+ channel1.read(null, 0, 1);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ }
+
+ public void testWriteByteBuffer() throws IOException {
+ assertTrue(this.server1.isBound());
+ java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer
+ .allocate(CAPACITY_NORMAL);
+ assertFalse(this.channel1.isRegistered());
+ assertTrue(this.channel1.isBlocking());
+ assertFalse(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ try {
+ channel1.write(writeBuf);
+ fail("Should throw NotYetConnectedException");
+ } catch (NotYetConnectedException e) {
+ // correct
+ }
+ this.channel1.connect(localAddr1);
+ assertTrue(this.channel1.isBlocking());
+ assertTrue(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf));
+
+ this.channel1.close();
+ try {
+ channel1.write(writeBuf);
+ fail("Should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // correct
+ }
+ }
+
+ public void testWriteByteBuffer_Direct() throws IOException {
+ assertTrue(this.server1.isBound());
+ java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer
+ .allocateDirect(CAPACITY_NORMAL);
+ assertFalse(this.channel1.isRegistered());
+ assertTrue(this.channel1.isBlocking());
+ assertFalse(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ try {
+ channel1.write(writeBuf);
+ fail("Should throw NotYetConnectedException");
+ } catch (NotYetConnectedException e) {
+ // correct
+ }
+ this.channel1.connect(localAddr1);
+ assertTrue(this.channel1.isBlocking());
+ assertTrue(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf));
+
+ this.channel1.close();
+ try {
+ channel1.write(writeBuf);
+ fail("Should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // correct
+ }
+ }
+
+ public void testWriteByteBuffer_BufNull() throws IOException {
+ assertTrue(this.server1.isBound());
+ java.nio.ByteBuffer writeBuf = java.nio.ByteBuffer.allocate(0);
+ this.channel1.connect(localAddr1);
+ assertEquals(this.channel1.write(writeBuf), 0);
+ try {
+ this.channel1.write((java.nio.ByteBuffer) null);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ }
+
+ /*
+ * SocketChannelImpl.write(ByteBuffer[], int, int)'
+ */
+ public void testWriteByteBufferArrayIntInt() throws IOException {
+ java.nio.ByteBuffer[] writeBuf = new java.nio.ByteBuffer[2];
+ writeBuf[0] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
+ writeBuf[1] = java.nio.ByteBuffer.allocate(CAPACITY_NORMAL);
+ assertFalse(this.channel1.isRegistered());
+ assertTrue(this.channel1.isBlocking());
+ assertFalse(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ try {
+ channel1.write(writeBuf, 0, 1);
+ fail("Should throw NotYetConnectedException");
+ } catch (NotYetConnectedException e) {
+ // correct
+ }
+ this.channel1.connect(localAddr1);
+ assertTrue(this.channel1.isBlocking());
+ assertTrue(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf, 0, 1));
+ // still writes the same size as above
+ assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf, 0, 2));
+ writeBuf[0].flip();
+ writeBuf[1].flip();
+ assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2));
+ this.channel1.close();
+ try {
+ channel1.write(writeBuf);
+ fail("Should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // correct
+ }
+ }
+
+ /*
+ * SocketChannelImpl.write(ByteBuffer[], int, int)'
+ */
+ public void testWriteByteBufferArrayIntInt_Direct() throws IOException {
+ java.nio.ByteBuffer[] writeBuf = new java.nio.ByteBuffer[2];
+ writeBuf[0] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
+ writeBuf[1] = java.nio.ByteBuffer.allocateDirect(CAPACITY_NORMAL);
+ assertFalse(this.channel1.isRegistered());
+ assertTrue(this.channel1.isBlocking());
+ assertFalse(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ try {
+ channel1.write(writeBuf, 0, 1);
+ fail("Should throw NotYetConnectedException");
+ } catch (NotYetConnectedException e) {
+ // correct
+ }
+ this.channel1.connect(localAddr1);
+ assertTrue(this.channel1.isBlocking());
+ assertTrue(this.channel1.isConnected());
+ assertFalse(this.channel1.isConnectionPending());
+ assertTrue(this.channel1.isOpen());
+ assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf, 0, 1));
+ // still writes the same size as above
+ assertEquals(CAPACITY_NORMAL, this.channel1.write(writeBuf, 0, 2));
+ writeBuf[0].flip();
+ writeBuf[1].flip();
+ assertEquals(CAPACITY_NORMAL * 2, this.channel1.write(writeBuf, 0, 2));
+ this.channel1.close();
+ try {
+ channel1.write(writeBuf);
+ fail("Should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // correct
+ }
+ }
+
+ public void testWriteByteBufferArrayIntInt_BufNull() throws IOException {
+ java.nio.ByteBuffer[] writeBuf = new java.nio.ByteBuffer[0];
+
+ this.channel1.connect(localAddr1);
+ try {
+ this.channel1.write(null, 0, 1);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ assertEquals(0, this.channel1.write(writeBuf, 0, 0));
+ try {
+ this.channel1.write(writeBuf, 0, 1);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // correct
+ }
+ writeBuf = new java.nio.ByteBuffer[1];
+ try {
+ this.channel1.write(writeBuf, 0, 1);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ try {
+ this.channel1.write(writeBuf, 0, 2);
+ fail("Should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // correct
+ }
+ this.server1.close();
+ try {
+ channel1.read(null, 0, 1);
+ fail("Should throw NPE");
+ } catch (NullPointerException e) {
+ // correct
+ }
+ }
+
+ public void testWriteByteBufferArrayIntInt_SizeError() throws IOException {
+ java.nio.ByteBuffer[] buf = new java.nio.ByteBuffer[1];
+ this.channel1.connect(localAddr1);
+ assertEquals(0, this.channel1.write(buf, 0, 0));
+ try {
+ this.channel1.write(buf, -1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ this.channel1.write(buf, 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ this.channel1.write(buf, 0, 2);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ this.channel1.write(buf, 2, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ this.channel1.write(null, 0, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ this.server1.close();
+ }
+
+ public void testReadByteBufferArrayIntInt_SizeError() throws IOException {
+ java.nio.ByteBuffer[] buf = new java.nio.ByteBuffer[1];
+ this.channel1.connect(localAddr1);
+ assertEquals(0, this.channel1.read(buf, 0, 0));
+ try {
+ this.channel1.read(buf, -1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ this.channel1.read(buf, 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ this.channel1.read(buf, 0, 2);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ this.channel1.read(buf, 2, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ this.channel1.read(null, 0, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ this.server1.close();
+ }
+
+ /*
+ * ==========================================================================
+ * Tests for read/write real data
+ * ==========================================================================
+ */
+
+
+ /**
+ * @tests java.nio.channels.SocketChannel#read(ByteBuffer[])
+ */
+ public void test_read$LByteBuffer() throws IOException {
+ MockSocketChannel sc = new MockSocketChannel(null);
+ ByteBuffer [] byteBufferArray = { ByteBuffer.allocate(1), ByteBuffer.allocate(1)};
+ // Verify that calling read(ByteBuffer[]) leads to the method
+ // read(ByteBuffer[], int, int) being called with a 0 for the
+ // second parameter and targets.length as the third parameter.
+ sc.read(byteBufferArray);
+ assertTrue(sc.isReadCalled);
+ }
+ /**
+ * @tests java.nio.channels.SocketChannel#read(ByteBuffer[],int,int)
+ */
+ public void test_read$LByteBufferII_blocking() throws Exception {
+ assert_read$LByteBuffer(true);
+ }
+
+ /**
+ * @tests java.nio.channels.SocketChannel#read(ByteBuffer[],int,int)
+ */
+ public void test_read$LByteBufferII_nonblocking() throws Exception {
+ assert_read$LByteBuffer(false);
+ }
+
+ private void assert_read$LByteBuffer(boolean isBlocking) throws IOException {
+ // initialize write content
+ byte[] writeContent = new byte[CAPACITY_NORMAL * 2];
+ for (int i = 0; i < CAPACITY_NORMAL * 2; i++) {
+ writeContent[i] = (byte) i;
+ }
+ ByteBuffer[] readContents = new ByteBuffer[2];
+ readContents[0] = ByteBuffer.allocate(CAPACITY_NORMAL);
+ readContents[1] = ByteBuffer.allocate(CAPACITY_NORMAL + 1);
+ // establish connection
+ channel1.connect(localAddr1);
+ Socket acceptedSocket = server1.accept();
+ // use OutputStream.write to send CAPACITY_NORMAL * 2 bytes data
+ OutputStream out = acceptedSocket.getOutputStream();
+ out.write(writeContent);
+ // use close to guarantee all data is sent
+ acceptedSocket.close();
+ // configure block/nonblock mode
+ channel1.configureBlocking(isBlocking);
+ long startTime = System.currentTimeMillis();
+ long totalRead = 0;
+ long countRead = 0;
+
+ while (totalRead <= CAPACITY_NORMAL * 2) {
+ countRead = channel1.read(readContents, 0, 2);
+ if (0 == countRead && !readContents[1].hasRemaining()) {
+ // read returns 0 because readContents is full
+ break;
+ }
+ if (EOF == countRead) {
+ break;
+ }
+ totalRead += countRead;
+ // if the channel could not finish reading in TIMEOUT ms, the
+ // test fails. It is used to guarantee the test never hangs even
+ // if there are bugs of SocketChannel implementation. For
+ // blocking read, it possibly returns 0 in some cases.
+ assertTimeout(startTime, TIMEOUT);
+ }
+
+ // assert total bytes read and the position of ByteBuffers
+ assertEquals(CAPACITY_NORMAL * 2, totalRead);
+ assertEquals(CAPACITY_NORMAL, readContents[0].position());
+ assertEquals(CAPACITY_NORMAL, readContents[1].position());
+ // assert read content
+ readContents[0].flip();
+ readContents[1].flip();
+ for (int i = 0; i < CAPACITY_NORMAL; i++) {
+ assertEquals(writeContent[i], readContents[0].get());
+ }
+ for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) {
+ assertEquals(writeContent[i], readContents[1].get());
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.SocketChannel#write(ByteBuffer[],int,int)
+ */
+ public void test_write$LByteBufferII_blocking() throws Exception {
+ assert_write$LByteBuffer(true);
+ }
+
+ /**
+ * @tests java.nio.channels.SocketChannel#write(ByteBuffer[],int,int)
+ */
+ public void test_write$LByteBufferII_nonblocking()
+ throws Exception {
+ assert_write$LByteBuffer(false);
+ }
+
+ private void assert_write$LByteBuffer(boolean isBlocking)
+ throws IOException {
+ // initialize write contents
+ ByteBuffer writeContents[] = new ByteBuffer[2];
+ writeContents[0] = ByteBuffer.allocate(CAPACITY_NORMAL);
+ writeContents[1] = ByteBuffer.allocate(CAPACITY_NORMAL);
+ for (int i = 0; i < CAPACITY_NORMAL; i++) {
+ writeContents[0].put((byte) i);
+ }
+ for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) {
+ writeContents[1].put((byte) i);
+ }
+ writeContents[0].flip();
+ writeContents[1].flip();
+ // establish connection
+ channel1.connect(localAddr1);
+ Socket acceptedSocket = server1.accept();
+ // set blocking/nonblocking mode
+ channel1.configureBlocking(isBlocking);
+
+ assertEquals(CAPACITY_NORMAL, channel1.write(writeContents, 0, 1));
+ assertEquals(CAPACITY_NORMAL, channel1.write(writeContents, 1, 1));
+
+ // assert written count and ByteBuffer position
+ assertEquals(CAPACITY_NORMAL, writeContents[0].position());
+ assertEquals(CAPACITY_NORMAL, writeContents[1].position());
+ // use close to guarantee all data is sent
+ channel1.close();
+ InputStream in = acceptedSocket.getInputStream();
+ byte[] readContent = new byte[CAPACITY_NORMAL * 2 + 1];
+ int totalCount = 0;
+ int count = 0;
+ // if the channel could not finish reading in TIMEOUT ms, the test
+ // fails. It is used to guarantee the test never hangs even if there
+ // are bugs of SocketChannel implementation.
+ acceptedSocket.setSoTimeout(TIMEOUT);
+ // use InputStream.read to read data.
+ while (totalCount <= CAPACITY_NORMAL) {
+ count = in.read(readContent, totalCount, readContent.length
+ - totalCount);
+ if (EOF == count) {
+ break;
+ }
+ totalCount += count;
+ }
+ // assert read content
+ assertEquals(CAPACITY_NORMAL * 2, totalCount);
+ writeContents[0].flip();
+ writeContents[1].flip();
+ for (int i = 0; i < CAPACITY_NORMAL; i++) {
+ assertEquals(writeContents[0].get(), readContent[i]);
+ }
+ for (int i = CAPACITY_NORMAL; i < CAPACITY_NORMAL * 2; i++) {
+ assertEquals(writeContents[1].get(), readContent[i]);
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.SocketChannel#write(ByteBuffer[])
+ */
+ public void test_write$LByteBuffer() throws IOException {
+ MockSocketChannel sc = new MockSocketChannel(null);
+ ByteBuffer [] byteBufferArray = { ByteBuffer.allocate(1), ByteBuffer.allocate(1)};
+ // Verify that calling write(ByteBuffer[]) leads to the method
+ // write(ByteBuffer[], int, int) being called with a 0 for the
+ // second parameter and sources.length as the third parameter.
+ sc.write(byteBufferArray);
+ assertTrue(sc.isWriteCalled);
+ }
+
+ /**
+ * @tests java.nio.channels.SocketChannel#write(ByteBuffer[])
+ */
+ public void test_writev() throws Exception {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(localAddr2);
+ SocketChannel sc = SocketChannel.open();
+ sc.connect(localAddr2);
+ SocketChannel sock = ssc.accept();
+ ByteBuffer[] buf = { ByteBuffer.allocate(10), ByteBuffer.allocateDirect(20) };
+
+ while (buf[0].remaining() != 0 && buf[1].remaining() !=0) {
+ assertTrue(sc.write(buf, 0, 2) >= 0);
+ }
+
+ ByteBuffer target = ByteBuffer.allocate(30);
+
+ while (target.remaining() != 0) {
+ assertTrue(sock.read(target) >=0);
+ }
+
+ ssc.close();
+ sc.close();
+ sock.close();
+ }
+
+ /**
+ * @tests java.nio.channels.SocketChannel#write(ByteBuffer[])
+ */
+ public void test_writev2() throws Exception {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.configureBlocking(false);
+ ssc.socket().bind(null);
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ boolean connected = sc.connect(ssc.socket().getLocalSocketAddress());
+ SocketChannel sock = ssc.accept();
+ if (!connected) {
+ sc.finishConnect();
+ }
+
+ ByteBuffer buf1 = ByteBuffer.allocate(10);
+ sc.socket().setSendBufferSize(512);
+ int bufSize = sc.socket().getSendBufferSize();
+ ByteBuffer buf2 = ByteBuffer.allocate(bufSize * 10);
+
+ ByteBuffer[] sent = new ByteBuffer[2];
+ sent[0] = buf1;
+ sent[1] = buf2;
+
+ long whole = buf1.remaining() + buf2.remaining();
+
+ long write = sc.write(sent);
+ ssc.close();
+ sc.close();
+ sock.close();
+
+ assertTrue(whole == (write + buf1.remaining() + buf2.remaining()));
+ }
+
+ /**
+ * @tests java.nio.channels.SocketChannel#write(ByteBuffer[])
+ *
+ * In non-blocking mode, the native system call will return EAGAIN/EWOULDBLOCK error
+ * code on Linux/Unix and return WSATRY_AGAIN/WSAEWOULDBLOCK error code on Windows.
+ * These error code means try again but not fatal error, so we should not throw exception.
+ */
+ public void test_write$NonBlockingException() throws Exception {
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.configureBlocking(false);
+ ssc.socket().bind(null);
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ boolean connected = sc.connect(ssc.socket().getLocalSocketAddress());
+ SocketChannel sock = ssc.accept();
+ if (!connected) {
+ sc.finishConnect();
+ }
+
+ try {
+ for (int i = 0; i < 100; i++) {
+ ByteBuffer buf1 = ByteBuffer.allocate(10);
+ sc.socket().setSendBufferSize(512);
+ int bufSize = sc.socket().getSendBufferSize();
+ ByteBuffer buf2 = ByteBuffer.allocate(bufSize * 10);
+
+ ByteBuffer[] sent = new ByteBuffer[2];
+ sent[0] = buf1;
+ sent[1] = buf2;
+
+ sc.write(sent);
+ }
+ } finally {
+ ssc.close();
+ sc.close();
+ sock.close();
+ }
+
+ }
+
+ /**
+ * @tests java.nio.channels.SocketChannel#write(ByteBuffer[])
+ */
+ public void test_write$LByteBuffer2() throws IOException {
+ // Set-up
+ ServerSocketChannel server = ServerSocketChannel.open();
+ server.socket().bind(null);
+ SocketChannel client = SocketChannel.open();
+ client.connect(server.socket().getLocalSocketAddress());
+ SocketChannel worker = server.accept();
+
+ // Test overlapping buffers
+ byte[] data = "Hello world!".getBytes("UTF-8");
+ ByteBuffer[] buffers = new ByteBuffer[3];
+ buffers[0] = ByteBuffer.wrap(data, 0, 6);
+ buffers[1] = ByteBuffer.wrap(data, 6, data.length - 6);
+ buffers[2] = ByteBuffer.wrap(data);
+
+ // Write them out, read what we wrote and check it
+ client.write(buffers);
+ client.close();
+ ByteBuffer readBuffer = ByteBuffer.allocate(1024);
+ while (EOF != worker.read(readBuffer)) {};
+ readBuffer.flip();
+ Buffer expected = ByteBuffer.allocate(1024).put(data).put(data).flip();
+ assertEquals(expected, readBuffer);
+
+ // Tidy-up
+ worker.close();
+ server.close();
+ }
+
+ /**
+ * @tests java.nio.channels.SocketChannel#write(ByteBuffer[])
+ */
+ public void test_write$LByteBuffer_buffers() throws IOException {
+ // Set-up
+ ServerSocketChannel server = ServerSocketChannel.open();
+ server.socket().bind(null);
+ SocketChannel client = SocketChannel.open();
+ client.connect(server.socket().getLocalSocketAddress());
+ SocketChannel worker = server.accept();
+
+ // A variety of buffer types to write
+ byte[] data = "Hello world!".getBytes("UTF-8");
+ ByteBuffer[] buffers = new ByteBuffer[3];
+ buffers[0] = ByteBuffer.wrap(data, 0, 2);
+ assertFalse(buffers[0].isDirect());
+ assertTrue(buffers[0].hasArray());
+
+ buffers[1] = ByteBuffer.wrap(data, 2, 4).asReadOnlyBuffer();
+ assertFalse(buffers[1].isDirect());
+ assertFalse(buffers[1].hasArray());
+
+ buffers[2] = ByteBuffer.allocateDirect(42);
+ buffers[2].put(data, 6, data.length - 6);
+ buffers[2].flip();
+ assertTrue(buffers[2].isDirect());
+ // Android's direct buffers do have a backing array.
+ assertTrue(buffers[2].hasArray());
+
+ // Write them out, read what we wrote and check it
+ client.write(buffers);
+ client.close();
+ ByteBuffer readBuffer = ByteBuffer.allocate(1024);
+ while (EOF != worker.read(readBuffer)) {};
+ readBuffer.flip();
+ assertEquals(ByteBuffer.wrap(data), readBuffer);
+
+ // Tidy-up
+ worker.close();
+ server.close();
+ }
+
+ /**
+ * @tests java.nio.channels.SocketChannel#write(ByteBuffer[])
+ */
+ public void test_write$LByteBuffer_writes() throws IOException {
+ // Set-up
+ ServerSocketChannel server = ServerSocketChannel.open();
+ server.socket().bind(null);
+ SocketChannel client = SocketChannel.open();
+ client.connect(server.socket().getLocalSocketAddress());
+ SocketChannel worker = server.accept();
+
+ // Data to write
+ byte[] data = "Hello world!".getBytes("UTF-8");
+ ByteBuffer[] buffers = new ByteBuffer[3];
+ buffers[0] = ByteBuffer.wrap(data, 0, 6);
+ buffers[1] = ByteBuffer.wrap("world!".getBytes("UTF-8"));
+ buffers[2] = buffers[0];
+ assertTrue(buffers[0].hasArray());
+
+ // Test a sequence of write calls
+ client.write(buffers, 0, 0); // write nothing
+ client.write(buffers, 1, 0); // write nothing
+ client.write(buffers, 0, 1); // write "Hello "
+ assertEquals("Failed to drain buffer 0", 0, buffers[0].remaining());
+ assertEquals("Shouldn't touch buffer 1", buffers[1].limit(), buffers[1]
+ .remaining());
+ client.write(buffers, 0, 2); // writes "world!"
+ assertEquals("Failed to drain buffer 1", 0, buffers[1].remaining());
+ client.write(buffers, 0, 3); // write nothing
+ client.close();
+
+ // Read what we wrote and check it
+ ByteBuffer readBuffer = ByteBuffer.allocate(1024);
+ while (EOF != worker.read(readBuffer)) {};
+ readBuffer.flip();
+ assertEquals(ByteBuffer.wrap(data), readBuffer);
+
+ // Tidy-up
+ worker.close();
+ server.close();
+ }
+
+ /**
+ * @tests java.nio.channels.SocketChannel#write(ByteBuffer[])
+ */
+ public void test_write$LByteBuffer_invalid() throws IOException {
+ // Set-up
+ ServerSocketChannel server = ServerSocketChannel.open();
+ server.socket().bind(null);
+
+ SocketChannel client = SocketChannel.open();
+ client.connect(server.socket().getLocalSocketAddress());
+
+ SocketChannel worker = server.accept();
+
+ // Do some stuff
+ try {
+ client.write((ByteBuffer[]) null);
+ fail("Should throw a NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ client.write((ByteBuffer[]) null, 0, 0);
+ fail("Should throw a NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ client.write((ByteBuffer[]) null, 1, 0);
+ fail("Should throw a NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ client.write((ByteBuffer[]) null, 0, 1);
+ fail("Should throw a NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ client.write((ByteBuffer[]) null, 1, 1);
+ fail("Should throw a NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ ByteBuffer[] buffers = new ByteBuffer[1];
+ buffers[0] = ByteBuffer.wrap("Hello ".getBytes("UTF-8"));
+
+ try {
+ client.write(buffers, -1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ client.write(buffers, 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ client.write(buffers, 0, 2);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ client.write(buffers, 2, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ client.write(null, 0, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ // Tidy-up
+ worker.close();
+ client.close();
+ server.close();
+ }
+
+ public void testSocket_configureblocking() throws IOException {
+ byte[] serverWBuf = new byte[CAPACITY_NORMAL];
+ for (int i = 0; i < serverWBuf.length; i++) {
+ serverWBuf[i] = (byte) i;
+ }
+ java.nio.ByteBuffer buf = java.nio.ByteBuffer
+ .allocate(CAPACITY_NORMAL + 1);
+ channel1.connect(localAddr1);
+ server1.accept();
+ Socket sock = this.channel1.socket();
+ channel1.configureBlocking(false);
+ assertFalse(channel1.isBlocking());
+ OutputStream channelSocketOut = sock.getOutputStream();
+ try {
+ // write operation is not allowed in non-blocking mode
+ channelSocketOut.write(buf.array());
+ fail("Non-Blocking mode should cause IllegalBlockingModeException");
+ } catch (IllegalBlockingModeException e) {
+ // correct
+ }
+ channel1.configureBlocking(true);
+ assertTrue(channel1.isBlocking());
+ // write operation is allowed in blocking mode
+ channelSocketOut.write(buf.array());
+ }
+
+ /**
+ * @tests SocketChannel#read(ByteBuffer[], int, int) when remote server
+ * closed
+ */
+ public void test_socketChannel_read_ByteBufferII_remoteClosed()
+ throws Exception {
+ // regression 1 for HARMONY-549
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(localAddr2);
+ SocketChannel sc = SocketChannel.open();
+ sc.connect(localAddr2);
+ ssc.accept().close();
+ ByteBuffer[] buf = { ByteBuffer.allocate(10) };
+ assertEquals(-1, sc.read(buf, 0, 1));
+ ssc.close();
+ sc.close();
+ }
+
+ /**
+ * @tests SocketChannel#write(ByteBuffer[], int, int)
+ */
+ public void test_socketChannel_write_ByteBufferII() throws Exception {
+ // regression 2 for HARMONY-549
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(localAddr2);
+ SocketChannel sc = SocketChannel.open();
+ sc.connect(localAddr2);
+ SocketChannel sock = ssc.accept();
+ ByteBuffer[] buf = { ByteBuffer.allocate(10), null };
+ try {
+ sc.write(buf, 0, 2);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ ssc.close();
+ sc.close();
+ ByteBuffer target = ByteBuffer.allocate(10);
+ assertEquals(-1, sock.read(target));
+ }
+
+ /**
+ * @tests SocketChannel#read(ByteBuffer[], int, int) with a null ByteBuffer
+ */
+ public void test_socketChannel_read_ByteBufferII_bufNULL() throws Exception {
+ // regression 3 for HARMONY-549
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(localAddr2);
+ SocketChannel sc = SocketChannel.open();
+ sc.connect(localAddr2);
+ ssc.accept();
+ ByteBuffer[] buf = new ByteBuffer[2];
+ buf[0] = ByteBuffer.allocate(1);
+ // let buf[1] be null
+ try {
+ sc.read(buf, 0, 2);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ ssc.close();
+ sc.close();
+ }
+
+ /**
+ * @tests SocketChannel#write(ByteBuffer) after close
+ */
+ public void test_socketChannel_write_close() throws Exception {
+ // regression 4 for HARMONY-549
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(localAddr2);
+ SocketChannel sc = SocketChannel.open();
+ sc.connect(localAddr2);
+ SocketChannel sock = ssc.accept();
+ ByteBuffer buf = null;
+ ssc.close();
+ sc.close();
+ try {
+ sc.write(buf);
+ fail("should throw NPE");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ sock.close();
+ }
+
+ /**
+ * @tests SocketChannel#write(ByteBuffer) if position is not zero
+ */
+ public void test_socketChannel_write_ByteBuffer_posNotZero()
+ throws Exception {
+ // regression 5 for HARMONY-549
+ final String testStr = "Hello World";
+ ByteBuffer readBuf = ByteBuffer.allocate(11);
+ ByteBuffer buf = ByteBuffer.wrap(testStr.getBytes());
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.socket().bind(localAddr2);
+ SocketChannel sc = SocketChannel.open();
+ sc.connect(localAddr2);
+ buf.position(2);
+ ssc.accept().write(buf);
+ assertEquals(9, sc.read(readBuf));
+ buf.flip();
+ readBuf.flip();
+ byte[] read = new byte[9];
+ byte[] write = new byte[11];
+ buf.get(write);
+ readBuf.get(read);
+ for (int i = 0; i < 9; i++) {
+ assertEquals(read[i], write[i + 2]);
+ }
+ }
+
+ /**
+ * @tests SocketChannelImpl#read(ByteBuffer[])
+ */
+ public void test_read_$ByteBuffer_Blocking() throws IOException {
+ // regression test for Harmony-728
+ byte[] data = new byte[CAPACITY_NORMAL];
+ for (int i = 0; i < CAPACITY_NORMAL; i++) {
+ data[i] = (byte) i;
+ }
+ ByteBuffer[] buf = new ByteBuffer[2];
+ buf[0] = ByteBuffer.allocate(CAPACITY_NORMAL);
+ buf[1] = ByteBuffer.allocate(CAPACITY_NORMAL);
+ channel1.connect(localAddr1);
+ Socket socket = null;
+ try {
+ socket = server1.accept();
+ OutputStream out = socket.getOutputStream();
+ out.write(data);
+ // should not block here
+ channel1.read(buf);
+ } finally {
+ if (null != socket) {
+ socket.close();
+ }
+ }
+ }
+
+ public void test_socket_getOutputStream_nonBlocking_read_Exception() throws IOException {
+ byte[] buf = new byte[1];
+ channel1.connect(this.localAddr1);
+ InputStream is = channel1.socket().getInputStream();
+ channel1.configureBlocking(false);
+ try {
+ is.read();
+ fail();
+ } catch (IllegalBlockingModeException expected) {
+ }
+ try {
+ is.read(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ try {
+ is.read(buf, -1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ is.read(buf, 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ is.read(buf, 0, 2);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ is.read(buf, 2, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ is.read(null, 0, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ is.close();
+
+ try {
+ is.read();
+ fail();
+ } catch (IllegalBlockingModeException expected) {
+ }
+ try {
+ is.read(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ try {
+ is.read(buf, -1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ is.read(buf, 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ is.read(buf, 0, 2);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ is.read(buf, 2, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ is.read(null, 0, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void test_socket_getOutputStream_blocking_read_Exception() throws IOException {
+ byte[] buf = new byte[1];
+ channel1.connect(this.localAddr1);
+ InputStream is = channel1.socket().getInputStream();
+ try {
+ is.read(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ try {
+ is.read(buf, -1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ is.read(buf, 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ is.read(buf, 0, 2);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ is.read(buf, 2, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ is.read(null, 0, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ is.close();
+
+ try {
+ is.read(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ try {
+ is.read(buf, -1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ is.read(buf, 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ is.read(buf, 0, 2);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ is.read(buf, 2, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ is.read(null, 0, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void test_socket_getOutputStream_nonBlocking_write_Exception() throws IOException {
+ byte[] buf = new byte[1];
+ channel1.connect(this.localAddr1);
+ OutputStream os = channel1.socket().getOutputStream();
+ channel1.configureBlocking(false);
+
+ try {
+ os.write(1);
+ fail();
+ } catch (IllegalBlockingModeException expected) {
+ }
+ try {
+ os.write(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ try {
+ os.write(buf, -1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ os.write(buf, 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ os.write(buf, 0, 2);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ os.write(buf, 2, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ os.write(null, 0, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ os.close();
+
+ try {
+ os.write(1);
+ fail();
+ } catch (IllegalBlockingModeException expected) {
+ }
+ try {
+ os.write(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ try {
+ os.write(buf, -1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ os.write(buf, 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ os.write(buf, 0, 2);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ os.write(buf, 2, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ os.write(null, 0, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ public void test_socket_getOutputStream_blocking_write_Exception() throws IOException {
+ byte[] buf = new byte[1];
+ channel1.connect(this.localAddr1);
+ OutputStream os = channel1.socket().getOutputStream();
+ try {
+ os.write(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ try {
+ os.write(buf, -1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ os.write(buf, 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ os.write(buf, 0, 2);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ os.write(buf, 2, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ os.write(null, 0, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+
+ os.close();
+
+ try {
+ os.write(null);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ try {
+ os.write(buf, -1, 1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ os.write(buf, 0, -1);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ os.write(buf, 0, 2);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ os.write(buf, 2, 0);
+ fail();
+ } catch (IndexOutOfBoundsException expected) {
+ }
+ try {
+ os.write(null, 0, 0);
+ fail();
+ } catch (NullPointerException expected) {
+ }
+ }
+
+ /**
+ * @tests SocketChannelImpl#socket().getOutputStream().write(int)
+ */
+ public void test_socket_getOutputStream_write_oneByte()
+ throws IOException {
+
+ // Regression test for Harmony-3475
+
+ int MAGIC = 123;
+
+ channel1.connect(this.localAddr1);
+
+ OutputStream os = channel1.socket().getOutputStream();
+
+ Socket acceptedSocket = server1.accept();
+
+ InputStream in = acceptedSocket.getInputStream();
+
+ os.write(MAGIC);
+ channel1.close();
+
+ int lastByte = in.read();
+ if (lastByte == -1) {
+ fail("Server received nothing. Expected 1 byte.");
+ } else if (lastByte != MAGIC) {
+ fail("Server received wrong single byte: " + lastByte +
+ ", expected: " + MAGIC);
+ }
+
+ lastByte = in.read();
+ if (lastByte != -1) {
+ fail("Server received too long sequence. Expected 1 byte.");
+ }
+ }
+
+ public void testSocket_setOptions() throws IOException {
+ channel1.connect(localAddr1);
+ Socket socket = channel1.socket();
+
+ ByteBuffer buffer = ByteBuffer.wrap(new byte[] {1, 2, 3});
+ socket.setKeepAlive(true);
+ channel1.write(buffer);
+
+ socket.setOOBInline(true);
+ channel1.write(buffer);
+
+ socket.setReceiveBufferSize(100);
+ channel1.write(buffer);
+
+ socket.setReuseAddress(true);
+ channel1.write(buffer);
+
+ socket.setSendBufferSize(100);
+ channel1.write(buffer);
+
+ socket.setSoLinger(true, 100);
+ channel1.write(buffer);
+
+ socket.setSoTimeout(1000);
+ channel1.write(buffer);
+
+ socket.setTcpNoDelay(true);
+ channel1.write(buffer);
+
+ socket.setTrafficClass(10);
+ channel1.write(buffer);
+ }
+
+ class MockSocketChannel extends SocketChannel{
+
+ private boolean isWriteCalled = false;
+
+ private boolean isReadCalled = false;
+
+ public MockSocketChannel(SelectorProvider provider){
+ super(provider);
+ }
+
+ public Socket socket() {
+ return null;
+ }
+
+ public boolean isConnected() {
+ return false;
+ }
+
+ public boolean isConnectionPending() {
+ return false;
+ }
+
+ public boolean connect(SocketAddress address) throws IOException {
+ return false;
+ }
+
+ public boolean finishConnect() throws IOException {
+ return false;
+ }
+
+ public int read(ByteBuffer target) throws IOException {
+ return 0;
+ }
+
+ public long read(ByteBuffer[] targets, int offset, int length) throws IOException {
+ // Verify that calling read(ByteBuffer[]) leads to the method
+ // read(ByteBuffer[], int, int) being called with a 0 for the
+ // second parameter and targets.length as the third parameter.
+ if(0 == offset && length == targets.length){
+ isReadCalled = true;
+ }
+ return 0;
+ }
+
+ public int write(ByteBuffer source) throws IOException {
+ return 0;
+ }
+
+ public long write(ByteBuffer[] sources, int offset, int length) throws IOException {
+ // Verify that calling write(ByteBuffer[]) leads to the method
+ // write(ByteBuffer[], int, int) being called with a 0 for the
+ // second parameter and sources.length as the third parameter.
+ if(0 == offset && length == sources.length){
+ isWriteCalled = true;
+ }
+ return 0;
+ }
+
+ protected void implCloseSelectableChannel() throws IOException {
+ // empty
+ }
+
+ protected void implConfigureBlocking(boolean blockingMode) throws IOException {
+ // empty
+ }
+
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SourceChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SourceChannelTest.java
new file mode 100644
index 0000000..e14c1ec
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/SourceChannelTest.java
@@ -0,0 +1,532 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.Pipe;
+import java.nio.channels.SelectionKey;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for java.nio.channels.Pipe.SourceChannel
+ */
+public class SourceChannelTest extends TestCase {
+
+ private static final int BUFFER_SIZE = 5;
+
+ private static final String ISO8859_1 = "ISO8859-1";
+
+ private Pipe pipe;
+
+ private Pipe.SinkChannel sink;
+
+ private Pipe.SourceChannel source;
+
+ private ByteBuffer buffer;
+
+ private ByteBuffer positionedBuffer;
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ pipe = Pipe.open();
+ sink = pipe.sink();
+ source = pipe.source();
+ buffer = ByteBuffer.wrap("bytes".getBytes(ISO8859_1));
+ positionedBuffer = ByteBuffer.wrap("12345bytes".getBytes(ISO8859_1));
+ positionedBuffer.position(BUFFER_SIZE);
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SourceChannel#validOps()
+ */
+ public void test_validOps() {
+ assertEquals(SelectionKey.OP_READ, source.validOps());
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
+ */
+ public void test_read_LByteBuffer_DataAvailable() throws IOException {
+ // if anything can read, read method will not block
+ sink.write(ByteBuffer.allocate(1));
+ int count = source.read(ByteBuffer.allocate(10));
+ assertEquals(1, count);
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
+ */
+ public void test_read_LByteBuffer_Exception() throws IOException {
+ ByteBuffer nullBuf = null;
+ try {
+ source.read(nullBuf);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
+ */
+ public void test_read_LByteBuffer_SinkClosed() throws IOException {
+ ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
+ sink.write(buffer);
+ sink.close();
+ long count = source.read(readBuf);
+ assertEquals(BUFFER_SIZE, count);
+ // readBuf is full, read 0 byte expected
+ count = source.read(readBuf);
+ assertEquals(0, count);
+ // readBuf is not null, -1 is expected
+ readBuf.position(0);
+ count = source.read(readBuf);
+ assertEquals(-1, count);
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
+ */
+ public void test_read_LByteBuffer_SourceClosed() throws IOException {
+ ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
+ source.close();
+ try {
+ source.read(readBuf);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ readBuf.position(BUFFER_SIZE);
+ try {
+ // readBuf is full
+ source.read(readBuf);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ ByteBuffer nullBuf = null;
+ try {
+ source.read(nullBuf);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ ByteBuffer[] bufArray = null;
+ try {
+ source.read(bufArray);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ ByteBuffer[] nullBufArray = {nullBuf};
+ try {
+ source.read(nullBufArray);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer[])
+ */
+ public void test_read_$LByteBuffer() throws IOException {
+ ByteBuffer[] bufArray = { buffer, positionedBuffer };
+ boolean[] sinkBlockingMode = { true, true, false, false };
+ boolean[] sourceBlockingMode = { true, false, true, false };
+ for (int i = 0; i < sinkBlockingMode.length; ++i) {
+ // open new pipe everytime, will be closed in finally block
+ pipe = Pipe.open();
+ sink = pipe.sink();
+ source = pipe.source();
+ sink.configureBlocking(sinkBlockingMode[i]);
+ source.configureBlocking(sourceBlockingMode[i]);
+ buffer.position(0);
+ positionedBuffer.position(BUFFER_SIZE);
+ try {
+ long writeCount = sink.write(bufArray);
+ assertEquals(10, writeCount);
+ // invoke close to ensure all data will be sent out
+ sink.close();
+ // read until EOF is meet or readBufArray is full.
+ ByteBuffer[] readBufArray = { ByteBuffer.allocate(BUFFER_SIZE),
+ ByteBuffer.allocate(BUFFER_SIZE) };
+ long totalCount = 0;
+ do {
+ long count = source.read(readBufArray);
+ if (count < 0) {
+ break;
+ }
+ if (0 == count && BUFFER_SIZE == readBufArray[1].position()) {
+ // source.read returns 0 because readBufArray is full
+ break;
+ }
+ totalCount += count;
+ } while (totalCount <= 10);
+ // assert read result
+ for (ByteBuffer readBuf : readBufArray) {
+ // RI may fail because of its bug implementation
+ assertEquals(BUFFER_SIZE, readBuf.position());
+ assertEquals("bytes",
+ new String(readBuf.array(), ISO8859_1));
+ }
+ } finally {
+ // close pipe everytime
+ sink.close();
+ source.close();
+ }
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
+ */
+ public void test_read_$LByteBuffer_Exception() throws IOException {
+ ByteBuffer[] nullBufArrayRef = null;
+ try {
+ source.read(nullBufArrayRef);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ // ByteBuffer array contains null element
+ ByteBuffer nullBuf = null;
+ ByteBuffer[] nullBufArray1 = { nullBuf };
+ try {
+ source.read(nullBufArray1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ ByteBuffer[] nullBufArray2 = { buffer, nullBuf };
+ try {
+ source.read(nullBufArray2);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
+ */
+ public void test_read_$LByteBuffer_SinkClosed() throws IOException {
+ ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
+ ByteBuffer[] readBufArray = { readBuf };
+ sink.write(buffer);
+ sink.close();
+ long count = source.read(readBufArray);
+ assertEquals(BUFFER_SIZE, count);
+ // readBuf is full, read 0 byte expected
+ count = source.read(readBufArray);
+ assertEquals(0, count);
+ // readBuf is not null, -1 is expected
+ readBuf.position(0);
+ assertTrue(readBuf.hasRemaining());
+ count = source.read(readBufArray);
+ assertEquals(-1, count);
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
+ */
+ public void test_read_$LByteBuffer_SourceClosed() throws IOException {
+ ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
+ ByteBuffer[] readBufArray = { readBuf };
+ source.close();
+ try {
+ source.read(readBufArray);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ readBuf.position(BUFFER_SIZE);
+ try {
+ // readBuf is full
+ source.read(readBufArray);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ ByteBuffer[] nullBufArrayRef = null;
+ try {
+ source.read(nullBufArrayRef);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ // ByteBuffer array contains null element
+ ByteBuffer nullBuf = null;
+ ByteBuffer[] nullBufArray1 = { nullBuf };
+ try {
+ source.read(nullBufArray1);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer[], int, int)
+ */
+ public void test_read_$LByteBufferII() throws IOException {
+ ByteBuffer[] bufArray = { buffer, positionedBuffer };
+ boolean[] sinkBlockingMode = { true, true, false, false };
+ boolean[] sourceBlockingMode = { true, false, true, false };
+ for (int i = 0; i < sinkBlockingMode.length; ++i) {
+ Pipe pipe = Pipe.open();
+ sink = pipe.sink();
+ source = pipe.source();
+
+ sink.configureBlocking(sinkBlockingMode[i]);
+ source.configureBlocking(sourceBlockingMode[i]);
+
+ buffer.position(0);
+ positionedBuffer.position(BUFFER_SIZE);
+ try {
+ sink.write(bufArray);
+ // invoke close to ensure all data will be sent out
+ sink.close();
+ // read until EOF is meet or readBufArray is full.
+ ByteBuffer[] readBufArray = { ByteBuffer.allocate(BUFFER_SIZE),
+ ByteBuffer.allocate(BUFFER_SIZE) };
+ long totalCount = 0;
+ do {
+ long count = source.read(readBufArray, 0, 2);
+ if (count < 0) {
+ break;
+ }
+ if (0 == count && BUFFER_SIZE == readBufArray[1].position()) {
+ // source.read returns 0 because readBufArray is full
+ break;
+ }
+ totalCount += count;
+ } while (totalCount != 10);
+
+ // assert read result
+ for (ByteBuffer readBuf : readBufArray) {
+ // RI may fail because of its bug implementation
+ assertEquals(BUFFER_SIZE, readBuf.position());
+ assertEquals("bytes",
+ new String(readBuf.array(), ISO8859_1));
+ }
+ } finally {
+ sink.close();
+ source.close();
+ }
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
+ */
+ public void test_read_$LByteBufferII_Exception() throws IOException {
+
+ ByteBuffer[] nullBufArrayRef = null;
+ try {
+ source.read(nullBufArrayRef, 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ source.read(nullBufArrayRef, 0, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ // ByteBuffer array contains null element
+ ByteBuffer nullBuf = null;
+ ByteBuffer[] nullBufArray1 = { nullBuf };
+ try {
+ source.read(nullBufArray1, 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ source.read(nullBufArray1, 0, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ source.read(nullBufArray1, -1, 0);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ source.read(nullBufArray1, -1, 1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ ByteBuffer[] nullBufArray2 = { buffer, nullBuf };
+
+ try {
+ source.read(nullBufArray1, 1, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ source.read(nullBufArray2, 0, 3);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ source.read(nullBufArray2, 0, 2);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
+ */
+ public void test_read_$LByteBufferII_SinkClosed() throws IOException {
+ ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
+ ByteBuffer[] readBufArray = { readBuf };
+ sink.write(buffer);
+ sink.close();
+ long count = source.read(readBufArray, 0, 1);
+ assertEquals(BUFFER_SIZE, count);
+ // readBuf is full, read 0 byte expected
+ count = source.read(readBufArray);
+ assertEquals(0, count);
+ // readBuf is not null, -1 is expected
+ readBuf.position(0);
+ count = source.read(readBufArray, 0, 1);
+ assertEquals(-1, count);
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SourceChannel#read(ByteBuffer)
+ */
+ public void test_read_$LByteBufferII_SourceClosed() throws IOException {
+ ByteBuffer readBuf = ByteBuffer.allocate(BUFFER_SIZE);
+ ByteBuffer[] readBufArray = { readBuf };
+ source.close();
+ try {
+ source.read(readBufArray, 0, 1);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ readBuf.position(BUFFER_SIZE);
+ try {
+ // readBuf is full
+ source.read(readBufArray, 0, 1);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ ByteBuffer[] nullBufArrayRef = null;
+ try {
+ source.read(nullBufArrayRef, 0, 1);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ try {
+ source.read(nullBufArrayRef, 0, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ // ByteBuffer array contains null element
+ ByteBuffer nullBuf = null;
+ ByteBuffer[] nullBufArray1 = { nullBuf };
+ try {
+ source.read(nullBufArray1, 0, 1);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ try {
+ source.read(nullBufArray1, 0, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ source.read(nullBufArray1, -1, 0);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+ try {
+ source.read(nullBufArray1, -1, 1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ ByteBuffer[] nullBufArray2 = { buffer, nullBuf };
+
+ try {
+ source.read(nullBufArray1, 1, -1);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ source.read(nullBufArray2, 0, 3);
+ fail("should throw IndexOutOfBoundsException");
+ } catch (IndexOutOfBoundsException e) {
+ // expected
+ }
+
+ try {
+ source.read(nullBufArray2, 0, 2);
+ fail("should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests java.nio.channels.Pipe.SourceChannel#close()
+ */
+ public void test_close() throws IOException {
+ sink.close();
+ assertFalse(sink.isOpen());
+ }
+
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnixSelectorTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnixSelectorTest.java
new file mode 100644
index 0000000..95fbbd6
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnixSelectorTest.java
@@ -0,0 +1,130 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.nio.channels.SelectableChannel;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
+
+import junit.framework.TestCase;
+
+public class UnixSelectorTest extends TestCase {
+ static class Server {
+ private ServerSocketChannel serverChannel = ServerSocketChannel.open();
+ private ServerSocket socket = null;
+
+ Server() throws Exception {
+ serverChannel.configureBlocking(false);
+ }
+
+ public void initialize() throws Exception {
+ this.socket = serverChannel.socket();
+ socket.bind(new InetSocketAddress("localhost", 0));
+ }
+
+ public int getPort() {
+ return socket.getLocalPort();
+ }
+
+ public boolean isOpen() {
+ return !socket.isClosed();
+ }
+
+ public ServerSocketChannel getServerChannel() {
+ return serverChannel;
+ }
+
+ public void accept() {
+ Thread serverThread = new Thread(new Runnable() {
+ public void run() {
+ try {
+ while (serverChannel.accept() == null) {
+ Thread.sleep(1000);
+ }
+ } catch (Exception e) {}
+ }
+ });
+ serverThread.start();
+ }
+
+ public void close() throws Exception{
+ serverChannel.close();
+ }
+ }
+
+ public void testSelectorAcceptAndRead() throws Exception {
+ Selector sel0 = Selector.open();
+ Selector sel1 = Selector.open();
+ Server server = new Server();
+ SelectableChannel serverChannel = server.getServerChannel();
+ SelectionKey mkey0 = serverChannel.register(sel0, SelectionKey.OP_ACCEPT);
+ serverChannel.register(sel1, SelectionKey.OP_ACCEPT);
+
+ // HUP is treating as acceptable
+ assertEquals(1, sel0.select(100));
+ assertEquals(true, sel0.selectedKeys().contains(mkey0));
+ server.initialize();
+ // after bind can not accept
+ assertEquals(0, sel1.select(100));
+ server.accept();
+ Thread.sleep(1000);
+ int port = server.getPort();
+ SocketChannel socketChannel = SocketChannel.open();
+ socketChannel.configureBlocking(false);
+ Selector sel2 = Selector.open();
+ socketChannel.register(sel2, SelectionKey.OP_WRITE);
+ boolean isConnected = socketChannel.connect(new InetSocketAddress("localhost", port));
+ if (!isConnected) {
+ socketChannel.finishConnect();
+ }
+
+ assertEquals(true, socketChannel.isConnected());
+ server.close();
+ Thread.sleep(3000);
+ assertEquals(true, socketChannel.isConnected());
+ assertEquals(1, sel2.select(100));
+ }
+
+ public void testSelectUnConnectedChannel() throws Exception {
+ SocketChannel socketChannel2 = SocketChannel.open();
+ socketChannel2.configureBlocking(false);
+ Selector sel3 = Selector.open();
+ SelectionKey mkey3 = socketChannel2.register(sel3, SelectionKey.OP_WRITE);
+ // HUP is also treating as writable
+ assertEquals(1, sel3.select(100));
+ assertEquals(false, mkey3.isConnectable());
+ // even the channel is not connected, the selector could be writable
+ assertEquals(false, socketChannel2.isConnected());
+ assertEquals(true, mkey3.isWritable());
+
+ Selector sel4 = Selector.open();
+ SelectionKey mkey4 = socketChannel2.register(sel4, SelectionKey.OP_CONNECT);
+ assertEquals(1, sel4.select(100));
+ assertEquals(false, mkey4.isWritable());
+ assertEquals(true, mkey4.isConnectable());
+
+ Selector sel5 = Selector.open();
+ SelectionKey mkey5 = socketChannel2.register(sel5, SelectionKey.OP_CONNECT | SelectionKey.OP_WRITE);
+ assertEquals(1, sel5.select(100));
+ assertEquals(true, mkey5.isWritable());
+ assertEquals(true, mkey5.isConnectable());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnresolvedAddressExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnresolvedAddressExceptionTest.java
new file mode 100644
index 0000000..827dcd7
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnresolvedAddressExceptionTest.java
@@ -0,0 +1,54 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.UnresolvedAddressException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for UnresolvedAddressException
+ */
+public class UnresolvedAddressExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.UnresolvedAddressException#UnresolvedAddressException()}
+ */
+ public void test_Constructor() {
+ UnresolvedAddressException e = new UnresolvedAddressException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new UnresolvedAddressException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this, new UnresolvedAddressException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.java
new file mode 100644
index 0000000..e032ea4
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/UnsupportedAddressTypeExceptionTest.java
@@ -0,0 +1,55 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.harmony.nio.tests.java.nio.channels;
+
+import java.nio.channels.UnsupportedAddressTypeException;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+
+/**
+ * Tests for UnsupportedAddressTypeException
+ */
+public class UnsupportedAddressTypeExceptionTest extends TestCase {
+
+ /**
+ * @tests {@link java.nio.channels.UnsupportedAddressTypeException#UnsupportedAddressTypeException()}
+ */
+ public void test_Constructor() {
+ UnsupportedAddressTypeException e = new UnsupportedAddressTypeException();
+ assertNull(e.getMessage());
+ assertNull(e.getLocalizedMessage());
+ assertNull(e.getCause());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+
+ SerializationTest.verifySelf(new UnsupportedAddressTypeException());
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SerializationTest.verifyGolden(this,
+ new UnsupportedAddressTypeException());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractInterruptibleChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractInterruptibleChannelTest.java
new file mode 100644
index 0000000..e2dab1e
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractInterruptibleChannelTest.java
@@ -0,0 +1,136 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels.spi;
+
+import java.io.IOException;
+import java.nio.channels.AsynchronousCloseException;
+import java.nio.channels.spi.AbstractInterruptibleChannel;
+
+import junit.framework.TestCase;
+
+public class AbstractInterruptibleChannelTest extends TestCase {
+
+ /**
+ * @tests AbstractInterruptibleChannel#close()
+ */
+ public void test_close() throws IOException {
+ MockInterruptibleChannel testMiChannel = new MockInterruptibleChannel();
+ assertTrue(testMiChannel.isOpen());
+ testMiChannel.isImplCloseCalled = false;
+ testMiChannel.close();
+ assertTrue(testMiChannel.isImplCloseCalled);
+ assertFalse(testMiChannel.isOpen());
+ }
+
+ /**
+ * @tests AbstractInterruptibleChannel#begin/end()
+ */
+ public void test_begin_end() throws IOException {
+ boolean complete = false;
+ MockInterruptibleChannel testChannel = new MockInterruptibleChannel();
+ try {
+ testChannel.superBegin();
+ complete = true;
+ } finally {
+ testChannel.superEnd(complete);
+ }
+
+ try {
+ testChannel.superBegin();
+ complete = false;
+ } finally {
+ testChannel.superEnd(complete);
+ }
+
+ try {
+ testChannel.superBegin();
+ complete = true;
+ } finally {
+ testChannel.superEnd(complete);
+ }
+ testChannel.superEnd(complete);
+
+ testChannel.superBegin();
+ try {
+ testChannel.superBegin();
+ complete = true;
+ } finally {
+ testChannel.superEnd(complete);
+ }
+ assertTrue(testChannel.isOpen());
+ testChannel.close();
+ }
+
+ /**
+ * @tests AbstractInterruptibleChannel#close/begin/end()
+ */
+ public void test_close_begin_end() throws IOException {
+ boolean complete = false;
+ MockInterruptibleChannel testChannel = new MockInterruptibleChannel();
+ assertTrue(testChannel.isOpen());
+ try {
+ testChannel.superBegin();
+ complete = true;
+ } finally {
+ testChannel.superEnd(complete);
+ }
+ assertTrue(testChannel.isOpen());
+ testChannel.close();
+ try {
+ testChannel.superBegin();
+ complete = false;
+ } finally {
+ try {
+ testChannel.superEnd(complete);
+ fail("should throw AsynchronousCloseException");
+ } catch (AsynchronousCloseException e) {
+ // expected
+ }
+ }
+ assertFalse(testChannel.isOpen());
+ try {
+ testChannel.superBegin();
+ complete = true;
+ } finally {
+ testChannel.superEnd(complete);
+ }
+ assertFalse(testChannel.isOpen());
+ }
+
+ private class MockInterruptibleChannel extends AbstractInterruptibleChannel {
+
+ private boolean isImplCloseCalled = false;
+
+ public MockInterruptibleChannel() {
+ super();
+ }
+
+ protected void implCloseChannel() throws IOException {
+ isImplCloseCalled = true;
+ }
+
+ // call super.begin() for test
+ void superBegin() {
+ super.begin();
+ }
+
+ // call super.end() for test
+ void superEnd(boolean completed) throws AsynchronousCloseException {
+ super.end(completed);
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectableChannelTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectableChannelTest.java
new file mode 100644
index 0000000..b396264
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectableChannelTest.java
@@ -0,0 +1,313 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels.spi;
+
+import java.io.IOException;
+import java.nio.channels.ClosedChannelException;
+import java.nio.channels.IllegalBlockingModeException;
+import java.nio.channels.IllegalSelectorException;
+import java.nio.channels.SelectableChannel;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.SocketChannel;
+import java.nio.channels.spi.AbstractSelectableChannel;
+import java.nio.channels.spi.SelectorProvider;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for AbstractSelectableChannel
+ */
+public class AbstractSelectableChannelTest extends TestCase {
+
+ private MockSelectableChannel testChannel;
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ testChannel = new MockSelectableChannel(SelectorProvider.provider());
+ }
+
+ protected void tearDown() throws Exception {
+ if (testChannel.isOpen()) {
+ testChannel.close();
+ }
+ }
+
+ /**
+ * @tests AbstractSelectableChannel#implCloseChannel()
+ */
+ public void test_implClose() throws IOException {
+ testChannel.isImplCloseSelectableChannelCalled = false;
+ testChannel.implCloseSelectableChannelCount = 0;
+ testChannel.close();
+ assertFalse(testChannel.isOpen());
+ assertTrue(testChannel.isImplCloseSelectableChannelCalled);
+ assertEquals(1, testChannel.implCloseSelectableChannelCount);
+
+ testChannel = new MockSelectableChannel(SelectorProvider.provider());
+ testChannel.isImplCloseSelectableChannelCalled = false;
+ testChannel.implCloseSelectableChannelCount = 0;
+ // close twice.
+ // make sure implCloseSelectableChannelCount is called only once.
+ testChannel.close();
+ testChannel.close();
+ assertFalse(testChannel.isOpen());
+ assertTrue(testChannel.isImplCloseSelectableChannelCalled);
+ assertEquals(1, testChannel.implCloseSelectableChannelCount);
+ }
+
+ /**
+ * @tests AbstractSelectableChannel#provider()
+ */
+ public void test_provider() {
+ SelectorProvider provider = testChannel.provider();
+ assertSame(SelectorProvider.provider(), provider);
+ testChannel = new MockSelectableChannel(null);
+ provider = testChannel.provider();
+ assertNull(provider);
+ }
+
+ /**
+ * @tests AbstractSelectableChannel#isBlocking()
+ */
+ public void test_isBlocking() throws IOException {
+ assertTrue(testChannel.isBlocking());
+ testChannel.configureBlocking(false);
+ assertFalse(testChannel.isBlocking());
+ testChannel.configureBlocking(true);
+ assertTrue(testChannel.isBlocking());
+ }
+
+ /**
+ *
+ * @tests AbstractSelectableChannel#blockingLock()
+ */
+ public void test_blockingLock() {
+ Object gotObj = testChannel.blockingLock();
+ assertNotNull(gotObj);
+ }
+
+ /**
+ * @tests AbstractSelectableChannel#register(Selector, int, Object)
+ */
+ public void test_register_LSelectorILObject() throws IOException {
+ assertFalse(testChannel.isRegistered());
+ Selector acceptSelector1 = SelectorProvider.provider().openSelector();
+ Selector acceptSelector2 = new MockAbstractSelector(SelectorProvider
+ .provider());
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ SelectionKey acceptKey = sc.register(acceptSelector1,
+ SelectionKey.OP_READ, null);
+ assertNotNull(acceptKey);
+ assertTrue(acceptKey.isValid());
+ assertSame(sc, acceptKey.channel());
+
+ //test that sc.register invokes Selector.register()
+ acceptKey = sc.register(acceptSelector2, SelectionKey.OP_READ, null);
+ assertNull(acceptKey);
+
+ // Regression test to ensure acceptance of a selector with empty
+ // interest set.
+ SocketChannel channel = SocketChannel.open();
+ channel.configureBlocking(false);
+ Selector selector = Selector.open();
+ channel.register(selector, 0);
+ selector.close();
+ channel.close();
+ }
+
+ /**
+ * @tests AbstractSelectableChannel#register(Selector, int, Object)
+ */
+ public void test_register_LSelectorILObject_IllegalArgument()
+ throws IOException {
+ Selector acceptSelector = SelectorProvider.provider().openSelector();
+ assertTrue(acceptSelector.isOpen());
+ MockSelectableChannel msc = new MockSelectableChannel(SelectorProvider
+ .provider());
+ msc.configureBlocking(false);
+ // in nonblocking mode
+ try {
+ //different SelectionKey with validOps
+ msc.register(acceptSelector, SelectionKey.OP_READ, null);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ msc.register(null, 0, null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ // in nonblocking mode, if selector closed
+ acceptSelector.close();
+ try {
+ msc.register(acceptSelector, SelectionKey.OP_READ, null);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ msc.register(null, 0, null);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ try {
+ msc.register(acceptSelector, 0, null);
+ fail("Should throw IllegalSelectorException");
+ } catch (IllegalSelectorException e) {
+ // expected
+ }
+
+ acceptSelector = SelectorProvider.provider().openSelector();
+ // test in blocking mode
+ msc.configureBlocking(true);
+ try {
+ msc.register(acceptSelector, SelectionKey.OP_READ, null);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ msc.register(null, 0, null);
+ fail("Should throw IllegalBlockingModeException");
+ } catch (IllegalBlockingModeException e) {
+ // expected
+ }
+ acceptSelector.close();
+ // in blocking mode, if selector closed
+ try {
+ msc.register(acceptSelector, SelectionKey.OP_READ, null);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ msc.register(null, 0, null);
+ fail("Should throw IllegalBlockingModeException");
+ } catch (IllegalBlockingModeException e) {
+ // expected
+ }
+
+ // register with an object
+ Object argObj = new Object();
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ try {
+ sc.register(null, SelectionKey.OP_READ, argObj);
+ fail("Should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+
+ // if channel closed
+ msc.close();
+ try {
+ msc.register(acceptSelector, SelectionKey.OP_READ, null);
+ fail("Should throw ClosedChannelException");
+ } catch (ClosedChannelException e) {
+ // expected
+ }
+
+ }
+
+ /**
+ * @tests AbstractSelectableChannel#keyFor(Selector)
+ */
+ public void test_keyfor_LSelector() throws Exception {
+ SocketChannel sc = SocketChannel.open();
+ Object argObj = new Object();
+ sc.configureBlocking(false);
+ Selector acceptSelector = SelectorProvider.provider().openSelector();
+ Selector acceptSelectorOther = SelectorProvider.provider()
+ .openSelector();
+ SelectionKey acceptKey = sc.register(acceptSelector,
+ SelectionKey.OP_READ, argObj);
+ assertEquals(sc.keyFor(acceptSelector), acceptKey);
+ SelectionKey acceptKeyObjNull = sc.register(acceptSelector,
+ SelectionKey.OP_READ, null);
+ assertSame(sc.keyFor(acceptSelector), acceptKeyObjNull);
+ assertSame(acceptKeyObjNull, acceptKey);
+ SelectionKey acceptKeyOther = sc.register(acceptSelectorOther,
+ SelectionKey.OP_READ, null);
+ assertSame(sc.keyFor(acceptSelectorOther), acceptKeyOther);
+ }
+
+ /**
+ * @tests AbstractSelectableChannel#configureBlocking(boolean)
+ */
+ public void test_configureBlocking_Z_IllegalBlockingMode() throws Exception {
+ SocketChannel sc = SocketChannel.open();
+ sc.configureBlocking(false);
+ Selector acceptSelector = SelectorProvider.provider().openSelector();
+ SelectionKey acceptKey = sc.register(acceptSelector,
+ SelectionKey.OP_READ, null);
+ assertEquals(sc.keyFor(acceptSelector), acceptKey);
+ SelectableChannel getChannel = sc.configureBlocking(false);
+ assertEquals(getChannel, sc);
+ try {
+ sc.configureBlocking(true);
+ fail("Should throw IllegalBlockingModeException");
+ } catch (IllegalBlockingModeException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests AbstractSelectableChannel#configureBlocking(boolean)
+ */
+ public void test_configureBlocking_Z() throws Exception {
+ MockSelectableChannel mock = new MockSelectableChannel(SelectorProvider
+ .provider());
+ //default blocking mode is true
+ //the implConfigureBlocking is only invoked if the given mode is different with current one
+ mock.configureBlocking(true);
+ assertFalse(mock.implConfigureBlockingCalled);
+ mock.configureBlocking(false);
+ assertTrue(mock.implConfigureBlockingCalled);
+ }
+
+ private class MockSelectableChannel extends AbstractSelectableChannel {
+
+ private boolean isImplCloseSelectableChannelCalled = false;
+
+ private int implCloseSelectableChannelCount = 0;
+
+ private boolean implConfigureBlockingCalled = false;
+
+ public MockSelectableChannel(SelectorProvider arg0) {
+ super(arg0);
+ }
+
+ protected void implCloseSelectableChannel() throws IOException {
+ isImplCloseSelectableChannelCalled = true;
+ ++implCloseSelectableChannelCount;
+ }
+
+ protected void implConfigureBlocking(boolean arg0) throws IOException {
+ implConfigureBlockingCalled = true;
+ }
+
+ public int validOps() {
+ return SelectionKey.OP_ACCEPT;
+ }
+
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectionKeyTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectionKeyTest.java
new file mode 100644
index 0000000..1404fc1
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectionKeyTest.java
@@ -0,0 +1,76 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels.spi;
+
+import java.nio.channels.SelectableChannel;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.spi.AbstractSelectionKey;
+
+import junit.framework.TestCase;
+
+public class AbstractSelectionKeyTest extends TestCase {
+
+ /**
+ * @tests AbstractSelectionKey#isValid() without selector
+ */
+ public void test_isValid() throws Exception {
+ MockSelectionKey testKey = new MockSelectionKey();
+ assertTrue(testKey.isValid());
+ }
+
+ /**
+ * @tests AbstractSelectionKey#cancel
+ */
+ public void test_cancel() throws Exception {
+ MockSelectionKey testKey = new MockSelectionKey();
+ try {
+ testKey.cancel();
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected: no selector available
+ }
+ assertFalse(testKey.isValid());
+ }
+
+ private class MockSelectionKey extends AbstractSelectionKey {
+
+ MockSelectionKey() {
+ super();
+ }
+
+ public SelectableChannel channel() {
+ return null;
+ }
+
+ public Selector selector() {
+ return null;
+ }
+
+ public int interestOps() {
+ return 0;
+ }
+
+ public SelectionKey interestOps(int arg0) {
+ return null;
+ }
+
+ public int readyOps() {
+ return 0;
+ }
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectorTest.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectorTest.java
new file mode 100644
index 0000000..4b39001
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/AbstractSelectorTest.java
@@ -0,0 +1,160 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels.spi;
+
+import java.io.IOException;
+import java.nio.channels.IllegalBlockingModeException;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.spi.SelectorProvider;
+
+import junit.framework.TestCase;
+
+/**
+ * Tests for AbstractSelector and register of its default implementation
+ */
+public class AbstractSelectorTest extends TestCase {
+
+ /**
+ * @tests AbstractSelector#provider()
+ */
+ public void test_provider() throws IOException {
+ Selector mockSelector = new MockAbstractSelector(SelectorProvider
+ .provider());
+ assertTrue(mockSelector.isOpen());
+ assertSame(SelectorProvider.provider(), mockSelector.provider());
+ mockSelector = new MockAbstractSelector(null);
+ assertNull(mockSelector.provider());
+ }
+
+ /**
+ * @tests AbstractSelector#close()
+ */
+ public void test_close() throws IOException {
+ MockAbstractSelector mockSelector = new MockAbstractSelector(
+ SelectorProvider.provider());
+ mockSelector.close();
+ assertTrue(mockSelector.isImplCloseSelectorCalled);
+ }
+
+ /**
+ *
+ * @tests AbstractSelector#begin/end()
+ */
+ public void test_begin_end() throws IOException {
+ MockAbstractSelector mockSelector = new MockAbstractSelector(
+ SelectorProvider.provider());
+ try {
+ mockSelector.superBegin();
+ } finally {
+ mockSelector.superEnd();
+ }
+
+ mockSelector = new MockAbstractSelector(SelectorProvider.provider());
+ try {
+ mockSelector.superBegin();
+ mockSelector.close();
+ } finally {
+ mockSelector.superEnd();
+ }
+
+ try {
+ // begin twice
+ mockSelector.superBegin();
+ mockSelector.superBegin();
+ } finally {
+ mockSelector.superEnd();
+ }
+
+ try {
+ mockSelector.superBegin();
+ } finally {
+ // end twice
+ mockSelector.superEnd();
+ mockSelector.superEnd();
+ }
+
+ mockSelector.close();
+ try {
+ mockSelector.superBegin();
+ } finally {
+ mockSelector.superEnd();
+ }
+ }
+
+ /**
+ * @tests AbstractSelector#isOpen()
+ */
+ public void test_isOpen() throws Exception {
+ Selector acceptSelector = SelectorProvider.provider().openSelector();
+ assertTrue(acceptSelector.isOpen());
+ acceptSelector.close();
+ assertFalse(acceptSelector.isOpen());
+ }
+
+ /**
+ * @tests AbstractSelector#register(Selector,int)
+ */
+ public void test_register_LSelectorI() throws Exception {
+ Selector acceptSelector = SelectorProvider.provider().openSelector();
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.configureBlocking(false);
+
+ assertFalse(ssc.isRegistered());
+ SelectionKey acceptKey = ssc.register(acceptSelector,
+ SelectionKey.OP_ACCEPT);
+ assertTrue(ssc.isRegistered());
+ assertNotNull(acceptKey);
+ assertTrue(acceptSelector.keys().contains(acceptKey));
+ }
+
+ /**
+ * @tests AbstractSelector#register(Selector,int)
+ */
+ public void test_register_LSelectorI_error() throws IOException {
+ Selector acceptSelector = SelectorProvider.provider().openSelector();
+ ServerSocketChannel ssc = ServerSocketChannel.open();
+ ssc.configureBlocking(false);
+ acceptSelector.close();
+
+ assertFalse(acceptSelector.isOpen());
+ try {
+ ssc.register(acceptSelector, SelectionKey.OP_ACCEPT);
+ fail("should throw NullPointerException");
+ } catch (NullPointerException e) {
+ // expected
+ }
+ assertFalse(ssc.isRegistered());
+
+ acceptSelector = Selector.open();
+ ssc.configureBlocking(true);
+ try {
+ ssc.register(acceptSelector, SelectionKey.OP_ACCEPT);
+ fail("should throw IllegalBlockingModeException");
+ } catch (IllegalBlockingModeException e) {
+ // expected
+ }
+ assertFalse(ssc.isRegistered());
+ ssc.configureBlocking(false);
+ SelectionKey acceptKey = ssc.register(acceptSelector,
+ SelectionKey.OP_ACCEPT);
+ assertNotNull(acceptKey);
+ assertTrue(acceptSelector.keys().contains(acceptKey));
+ assertTrue(ssc.isRegistered());
+ }
+}
diff --git a/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/MockAbstractSelector.java b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/MockAbstractSelector.java
new file mode 100644
index 0000000..6e016b0
--- /dev/null
+++ b/harmony-tests/src/test/java/org/apache/harmony/nio/tests/java/nio/channels/spi/MockAbstractSelector.java
@@ -0,0 +1,89 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.nio.tests.java.nio.channels.spi;
+
+import java.io.IOException;
+import java.nio.channels.SelectionKey;
+import java.nio.channels.Selector;
+import java.nio.channels.spi.AbstractSelectableChannel;
+import java.nio.channels.spi.AbstractSelectionKey;
+import java.nio.channels.spi.AbstractSelector;
+import java.nio.channels.spi.SelectorProvider;
+import java.util.Set;
+
+public class MockAbstractSelector extends AbstractSelector {
+
+ public boolean isImplCloseSelectorCalled = false;
+
+ public MockAbstractSelector(SelectorProvider arg0) {
+ super(arg0);
+ }
+
+ public static MockAbstractSelector openSelector() {
+ return new MockAbstractSelector(SelectorProvider.provider());
+ }
+
+ public Set getCancelledKeys() {
+ return super.cancelledKeys();
+ }
+
+ protected void implCloseSelector() throws IOException {
+ isImplCloseSelectorCalled = true;
+ }
+
+ protected SelectionKey register(AbstractSelectableChannel arg0, int arg1,
+ Object arg2) {
+ return null;
+ }
+
+ public void superBegin() {
+ super.begin();
+ }
+
+ public void superEnd() {
+ super.end();
+ }
+
+ protected void mockDeregister(AbstractSelectionKey key) {
+ super.deregister(key);
+ }
+
+ public Set<SelectionKey> keys() {
+ return null;
+ }
+
+ public Set<SelectionKey> selectedKeys() {
+ return null;
+ }
+
+ public int selectNow() throws IOException {
+ return 0;
+ }
+
+ public int select(long arg0) throws IOException {
+ return 0;
+ }
+
+ public int select() throws IOException {
+ return 0;
+ }
+
+ public Selector wakeup() {
+ return null;
+ }
+
+}